我正在尝试使用matplotlib 中带有 pcolor 的 Heatmappcolor
的示例来创建热图?但我遇到了麻烦。
首先,接受的 anwser 中的示例对我不起作用,并且我收到以下错误消息:
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'
以“我的”方式创建绘图会产生良好的结果,但有一个例外:y 轴上的标签/刻度会在一段时间后停止。似乎 y 轴上的标签数量必须与 x 轴上的标签数量相同。
这是我负责创建热图的代码部分。请注意,这data_test
是一个二维 numpy 数组(data_test.shape
yield (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)
如果你能告诉我这种行为的原因以及如何改变它,我会很高兴。