【问题标题】:Some labels are missing if pcolor plot is not square如果 pcolor 图不是正方形,则缺少某些标签
【发布时间】:2013-08-27 08:46:51
【问题描述】:

我正在尝试使用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'

以“我的”方式创建绘图会产生良好的结果,但有一个例外: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)

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

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    此行为是由于您的以下代码行造成的:

    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)
    

    它会起作用的。

    【讨论】:

    • 非常感谢,效果很好。我总是对这些事情感到困惑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-24
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多