如果pcolor图不是正方形,则会丢失一些标签

时间:2013-08-27 08:46:51

标签: python matplotlib

我正在尝试使用Heatmap in matplotlib with pcolor?中的示例创建一个pcolor的热图,但我遇到了麻烦。

首先来自接受的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'

创建绘图“my”方式会产生一个好结果,但有一个例外:y轴上的标签/刻度会在一段时间后停止。似乎y轴上的标签数量必须与x轴上的标签数量相同。

以下是我的代码中负责创建热图的部分。请注意,data_test是一个二维的numpy数组(data_test.shape会产生(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)

Resulting plot

如果你能告诉我这种行为的原因以及如何改变它,我会非常高兴。

1 个答案:

答案 0 :(得分:3)

此行为是由您的代码的以下行引起的:

ax.set_yticks(np.arange(data.shape[1])+0.5, minor=False)

您正在使用错误的数据维度定义yticks!

如果你更正:

ax.set_xticks(np.arange(data.shape[1])+0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0])+0.5, minor=False)

它会起作用。

相关问题