Issue with colorbar in pylab - python

I am trying to plot a two dimensional numpy matrix (say, Kappa) using pcolor .
The skeleton of the code is this:
from pylab import pcolor, show, colorbar, xticks, yticks
import numpy as np
plt.figure(1)
pcolor(np.transpose(Kappa))
plt.colorbar()
plt.tight_layout()
plt.show()
At the top of the colorbar, I see a weird way in which the highest scale of the colorbar is written. I have attached a picture of the the said output (and I have highlighted the troublesome part by putting it inside a red box.)
Following suggestions, I have uploaded the matrix to my Google Drive. You can use this link to access the matrix.
I am wondering if anyone has faced similar issues with colorbars in pylab? I will appreciate any help.

Related

project numpy array to aitoff projection

I have an (as yet incomplete) image of the whole sky. In order to display it properly it needs to be projected onto an ellipse (specifically an Aitoff projection).
I have tried various versions of this:
plt.subplot(111, projection="aitoff")
plt.imshow(image, vmin=0.004, vmax=0.01, extent=[0,360,-90,90])
plt.show()
...and have tried changing the values in the extent kwarg to radians, as well as using pcolor or pcolormesh instead of imshow.
These have given me: an empty Aitoff plot, various Aitoff plots with all or part of my image sitting inside it, but not filling it, or an Aitoff plot with a small part of my image (one or two pixels by the looks of things) completely filling it.
My whole image sitting within a plot
The unprojected image
I also do not have access to things like Basemap or astroproj as I'm using a machine owned by my university.
Edit: As was pointed out by another user the above example is not Minimal, Complete, and Verifiable. Below is a version which should be:
A=np.random.rand(180,360)
plt.imshow(A)
plt.show()
plt.subplot(111, projection="aitoff")
plt.pcolormesh(A)
plt.show()
I want the entire image generated in the plt.imshow() command to be projected in the Aitoff figure. Instead only a few pixels are. Any ideas?
Thanks!
Using imshow in non-rectilinear projections will mostly fail. But instead pcolormesh may be used.
The aitoff projection ranges from -π to π in horizontal and from -π/2 to π/2 in vertical direction. This is the range of values to use when plotting the pcolormesh plot.
import numpy as np
import matplotlib.pyplot as plt
im = plt.imread("house.jpg")
x = np.linspace(-np.pi,np.pi,im.shape[1])
y = np.linspace(-np.pi/2,np.pi/2,im.shape[0])
X,Y = np.meshgrid(x,y)
plt.subplot(111, projection="aitoff")
plt.pcolormesh(X,Y[::-1],im[:,:,2])
plt.show()

Python Heatmaps (Basic and Complex)

What's the best way to do a heatmap in python (2.7)? I've found the heatmap.py module, and I was wondering if people have any advice on using it, or if there are other packages that do a good job.
I'm dealing with pretty basic data, like xy = np.random.rand(1000,2) superimposed on an image.
Although there's another thing I want to try, which is doing a heatmap that's scaled to a different heatmap. E.g., I have
attempts = np.random.rand(5000,2)
successes = np.random.rand(500,2)
And I want a heatmap of the successes relative to the density of the attempts. Is this possible?
Seaborn is a pretty widely-used library for making nice-looking plots, and has a heatmap function. Seaborn uses matplotlib under the hood.
import numpy as np
import seaborn as sns
xy = np.random.rand(1000,2)
sns.heatmap(xy, yticklabels=100)
Regarding your second question, I'm not sure what you mean. But my advice would be to create a numpy array or pandas dataframe of "successes [scaled] relative to the density of the attempts", however you mean that, and then pass that scaled array or dataframe to sns.heatmap
You can plot very complex heatmap using python package PyComplexHeatmap: https://github.com/DingWB/PyComplexHeatmap
https://github.com/DingWB/PyComplexHeatmap/blob/main/examples.ipynb
The most basic heatmap you can get is an image plot:
import matplotlib.pyplot as plt
import numpy as np
xy = np.random.rand(100,2)
plt.imshow(xy, aspect="auto")
plt.colorbar()
plt.show()
Note that using more points than you have pixels to show the heatmap might not make too much sense.
There are of course also different methods to draw a heatmaps and you may go through the matplotlib example gallery and see which plot appeals most to you.

Plot size changes on saving plot in matplotlib

I have plotted a graph with 14 subplots in matplotlib. In the window the plot looks like this-
I save this plot using following command-
import matplotlib.pyplot as plt
plt.savefig('img.png')
But the image that is saved looked like this-
Notice that the x axis labels get overlapped because the image is shrinked. The savefig() function has optional argument dpi, but it changes the resolution/quality of saved plot.
I also tried this, but it is used to improve image resolution.
I want the axis labels to be nicely spaced as in the window. Thanks
Ok, So I found the solution myself and posting it here for anyone who might face similar problem. I changed the figure size before saving and following code does the trick-
import matplotlib.pyplot as plt
fig =plt.gcf()
fig.set_size_inches(20, 11,dpi=100)
plt.savefig('img.png')

Matplotlib: poor resolution of PDF figures with hatching

When using Matplotlib to generate figures with hatching (e.g. pie, bar, bubble charts), I'm having some trouble getting decent resolution out of the PDF version of the figure. Saving as EPS is fine, but as soon as I use epstopdf or MPL's savefig(*.pdf), the hatching becomes pixellated and distored... the vector nature of the image appears to have been lost.
See minimal code below.
from matplotlib import pyplot as plt
# Define hatching styles
hatching = ["/", "o"]
fig, ax = plt.subplots()
wedges, texts = ax.pie([0.4, 0.6], colors=("SteelBlue", "Tomato"))
# Apply the hatching
for j, patch in enumerate(wedges): patch.set_hatch(hatching[j])
fig.savefig("hatchtest.pdf")
I've used Gimp to zoom in on a part of the plot to illustrate the difference...
Zoomed in on the EPS figure
Zoomed in on the PDF figure
As for system specific details, I'm using Ubuntu 13.04, Python 2.7.4 with MPL 1.2.1. I've tried different backends but nothing seems to resolve this. I'd ideally like to have nice vector images in EPS and PDF so that it's all journal-friendly. Any pointers would be much appreciated.
Just a problem with Evince PDF viewer. Viewing in Adobe Reader or printing the plot gives the desired result.

How do I let my matplotlib plot go beyond the axes?

I have to translate an image plotting script from matlab to matplotlib/pylab, and I'm trying to achieve the same effect as the matlab image below:
As you can see, the z order of the plots seem to be higher than the z order of the grid, so the markers are not hidden by the axes. However, I can't figure out a way to do the same with my matplotlib image:
I'm wondering if it is possible to get the same display without having to increase the limits of the y axis.
To get the marker to show beyond the axes you can turn the clipping off. This can be done using the keyword argument in the plot command clip_on=False.
For example:
import matplotlib.pyplot as plt
plt.plot(range(5), range(5), 'ro', markersize=20, clip_on=False, zorder=100)
plt.show()
This is a complete example of how to use the zorder kwarg: http://matplotlib.sourceforge.net/examples/pylab_examples/zorder_demo.html
Note that a higher z-order equates to a graph-element being more in the foreground.
For your second question, have a look at the figsize kwarg to instances of the Figure class: http://matplotlib.sourceforge.net/api/figure_api.html?highlight=figsize#matplotlib.figure.Figure
If you run into issues, please post some of your code and we'll be able to give more-detailed recommendations. Best of luck.
If you're plotting the lines one after the other, just change the order of the plotting calls and that would fix the z order.

Categories

Resources