TypeError:C的尺寸与X Y

时间:2016-04-07 17:17:42

标签: python matplotlib colormap

当我致电plt.pcolormesh

时,Matplotlib正在引发以下错误
TypeError: Dimensions of C (16, 1000) are incompatible with X (16) and/or Y (1000); see help(pcolormesh)

除非我遗漏某些东西,这很可能,尺寸匹配?为什么会发生错误?

我在其他地方看到的问题与我自己的不一样,所以我不知道如何解决这个问题。

所要求的代码:

def Colormap(lst):

    intensity = np.array(lst)

    x, y = intensity.shape

    x1 = range(0, x)
    y1 = range(0, y)

    x2,y2 = np.meshgrid(x1,y1)

    print x2,y2

    print intensity.shape

    plt.pcolormesh(x2,y2,intensity)
    plt.colorbar()
    plt.savefig('colormap.pdf', dpi = 1200)
    plt.show()

印刷语句给出:

[[ 0  1  2 ..., 13 14 15]
 [ 0  1  2 ..., 13 14 15]
 [ 0  1  2 ..., 13 14 15]
 ..., 
 [ 0  1  2 ..., 13 14 15]
 [ 0  1  2 ..., 13 14 15]
 [ 0  1  2 ..., 13 14 15]] [[  0   0   0 ...,   0   0   0]
 [  1   1   1 ...,   1   1   1]
 [  2   2   2 ...,   2   2   2]
 ..., 
 [997 997 997 ..., 997 997 997]
 [998 998 998 ..., 998 998 998]
 [999 999 999 ..., 999 999 999]]

(16, 1000)

正如我所料。我缺少一些非常基本的东西吗?感谢。

1 个答案:

答案 0 :(得分:2)

问题是你要改变尺寸(x到y,y到x),所以尺寸不对。检查以下更改:

import matplotlib.pyplot as plt
import numpy as np

def Colormap(lst):

    intensity = np.array(lst)

    x, y = intensity.shape

    x1 = range(x+1) # changed this also
    y1 = range(y+1) # changed this also

    x2,y2 = np.meshgrid(x1,y1)

    print(x2.shape,y2.shape)

    print(intensity.shape)
    print(np.swapaxes(intensity,0,1).shape)
    plt.pcolormesh(x2,y2,np.swapaxes(intensity,0,1)) # Transpose of intensity
    plt.colorbar()
    plt.savefig('colormap.pdf', dpi = 1200)
    plt.show()

Colormap(np.random.randint(0,100,(16,1000)))

,结果如下:

Transpose of array

我必须进行转置以使代码正常工作。