mplot3d python不兼容的尺寸错误

时间:2015-01-12 01:46:49

标签: python arrays matplotlib mplot3d

我正在尝试使用python mplot3d在3D中绘制2D数组但是我收到有关轴1上不兼容尺寸的错误 我已经看过其他问题,其中答案建议使用meshgrid,但我已经使用了它仍然得到一个错误,我的X和Y范围也乘以Z值的数量。 这是我的代码:

def view_3d(map3d):
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    X = []
    Y = []
    Z = []
    for wid in range(len(map3d)):
        X.append(wid)
        for hi in range(len(map3d[wid])):
            if wid is 0:
                Y.append(hi)
            Z.append(map3d[wid][hi])
    print(len(X), len(Y), len(Z))
    X = np.array(X)
    Y = np.array(Y)

    X2, Y2 = np.meshgrid(X, Y)
    Z = np.array(Z)
    print(len(X2),len(Y2),len(Z))
    print(len(X2[0]), len(Y2[0]))
    surf = ax.plot_surface(X2, Y2, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
            linewidth=0, antialiased=False)

    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

    fig.colorbar(surf, shrink=0.5, aspect=5)

    plt.show()

传递的2d数组(map3d)的长度为566×566

打印语句只是为了确认数组的长度

错误是:

Traceback (most recent call last):
  File "__init__.py", line 199, in <module>
    view_3d(map_results)
  File "__init__.py", line 163, in view_3d
    linewidth=0, antialiased=False)
  File "C:\Python27\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 1564, in plot_surface
    X, Y, Z = np.broadcast_arrays(X, Y, Z)
  File "C:\Python27\lib\site-packages\numpy\lib\stride_tricks.py", line 101, in broadcast_arrays
    "incompatible dimensions on axis %r." % (axis,))
ValueError: shape mismatch: two or more arrays have incompatible dimensions on axis 1.

运行代码并查看错误所需的代码和图片的google驱动器链接如下: https://drive.google.com/folderview?id=0B2ssDQewnhReWGJZYXZRSXNxRFU&usp=sharing

感谢所有帮助, 感谢

1 个答案:

答案 0 :(得分:1)

您的Z数组必须与X2,Y2具有相同的形状,才能使plot_surface正常工作。 所以我改变了行

Z = np.array(Z)

Z = np.array(Z).reshape(Y.size,X.size)

并且它有效!