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 doesn't 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 the same 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_test
is a two-dimensional numpy array (data_test.shape
yields (20, 13)
).
import matplotlib.pyplot as pl
import numpy as np
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()
AA = ['G', 'A', 'V', 'S', 'T', 'C', 'M', 'L', 'I', 'K', 'R', 'E', 'D', 'Q', 'N', 'F', 'Y', 'W', 'P', 'H']
data_test = np.random.rand(20,13)
plot_heatmap(data_test)
If you could tell me the reason for this behavior and the how to change it, I would be very happy.