如何使用Matplotlib在python中定义和绘制10 * 10数组?

时间:2015-02-24 19:50:35

标签: python matplotlib plot mplot3d

我对Python Matplot很新。我试图绘制一个3d条形图,其中条形图的高度是z,条形图的位置是我的数组的x,y。

这是我的数据示例,我有一个10 * 10阵列:

data = np.array([[0.1729,0.8658,0.9283,0.9381,0.9535,1.0000,1.0000,0.9999,0.9999,1.0000],
[-0.0430,0.3109,0.2788,0.5846,0.5369,0.5717,0.6357,0.5619,0.5866,0.6587],
[-0.2228,0.3427,0.1842,0.2106,0.4398,0.3896,0.4687,0.5749,0.4684,0.5484],
[0.0011,0.2899,0.1854,0.1040,0.3513,0.3863,0.3971,0.4485,0.2514,0.4946],
[-0.0096,0.0630,0.1564,-0.0077,0.0825,0.1637,0.2627,0.4800,0.3931,0.3244],
[0.0134,0.1198,0.3339,0.1243,-0.0864,0.4048,0.1996,0.3988,0.1970,0.5248],
[-0.0153,0.2806,0.1926,0.1918,0.0860,0.1054,0.3202,0.3063,0.2644,0.3791],
[-0.1118,0.3065,0.1396,0.0949,0.3459,0.1168,0.3730,0.0741,0.3518,0.2150],
[0.1022,0.3144,-0.1165,0.0509,0.1462,0.3265,0.2087,0.2549,0.3914,0.2683],
[-0.0083,-0.0228,0.0721,0.1086,0.2400,0.1899,0.0922,0.1006,0.2430,0.2768]])

我使用以下代码生成3d条形图:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax1 = Axes3D(fig)

xpos = np.arange(data.shape[0])
ypos = np.arange(data.shape[1])
zpos = data

xposM, yposM = np.meshgrid(xpos, ypos, copy=False)

dx=0.5
dy=0.5
dz=zpos

ax1.bar3d(xposM.ravel(), yposM.ravel(), dz, dx, dy, dz)
plt.show()

但是我收到了这个错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

有没有人知道我的代码有什么问题?

1 个答案:

答案 0 :(得分:4)

您的代码存在两个问题。

1:zpos不应该是=data;这是你的主要挂断。

2:你应该(可能)将bar3d称为ax1.bar3d(xposM.ravel(), yposM.ravel(), zpos, dx, dy, dz)。按照目前的情况,你要将你的酒吧放在他们应该去的地方。也就是说,高度为3的条形将从z = 3开始并转到z = 6,高度为-2.1的条形将从z = -2.1开始。

至于第一个问题,xpos和ypos有形状(100,),而数据有形状(10,10)。你需要它们具有相同的尺寸,所以我建议包括zpos = np.zeros(len(data.ravel()))。这也意味着您需要设置dz = data.ravel()