Tuesday, August 27, 2013

Python matplotlib pcolor some labels are missing if the plot is not square

Python matplotlib pcolor some labels are missing if the plot is not square

I am trying to create a heatmap with pcolor using the example from Heatmap
in matplotlib with pcolor? but I run into trouble.
First the example from the accepted anwser doesnt work for me and I get
the following error message:
Traceback (most recent call last):
File "/home/knorrs/temp/HeatMapTest.py", line 22, in <module>
heatmap = ax.pcolor(nba_sort, cmap=plt.cm.Blues, alpha=0.8)
File
"/home/martin/pybin/lib/python2.7/site-packages/matplotlib/axes.py",
line 7309, in pcolor
X, Y, C = self._pcolorargs('pcolor', *args)
File
"/home/martin/pybin/lib/python2.7/site-packages/matplotlib/axes.py",
line 7132, in _pcolorargs
numRows, numCols = C.shape
AttributeError: 'NoneType' object has no attribute 'shape'
Creating the plot "my" way leads to a good result with one exception: the
labels / ticks on the y-axis stop after a while. It seems that the number
of labels on the y-axis has to be of the same size as the number of labels
on the x-axis.
Here is the part of my code responsible for the creation of the heatmap.
Note that data is a two dimensional array (data.shape yields (20, 13)).
AA = ['G', 'A', 'V', 'S', 'T', 'C', 'M', 'L', 'I', 'K', 'R', 'E', 'D',
'Q', 'N', 'F', 'Y', 'W', 'P', 'H']
def plot_heatmap(data):
x_min = ((data.shape[1]-1)/2)*-1 #if the shape is for example 13
(has to be odd) we set the x_min to -6
x_max = (data.shape[1]-1)/2 #and the x_max to +6
x_labels = range(x_min,x_max+1,1) #this way we create the x_labels
going from -6 over 0 to +6
fig = pl.figure(figsize=(24,18))
ax = fig.add_subplot(1,1,1)
plot = ax.pcolor(data, cmap=pl.cm.Blues, edgecolors='k')
# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_yticks(np.arange(data.shape[1])+0.5, minor=False)
ax.set_ybound(lower = 0, upper = data.shape[0])
ax.set_xbound(lower = 0, upper = data.shape[1])
# want a more natural, table-like display
ax.invert_yaxis()
#ax.xaxis.tick_top()
ax.set_xticklabels(x_labels, minor=False)
ax.set_yticklabels(AA, minor=False)
fig.colorbar(plot)
pl.show()
You can find the resulting figure at
http://picload.org/view/oaidpww/heatmap.png.html
If you could tell me the reason for this behaviour and the way to change
it, I would be very happy.

No comments:

Post a Comment