我在scipy / numpy中有一个Nx3矩阵,我想用它制作一个3维条形图,其中X和Y轴由矩阵的第一和第二列的值,每个条的高度确定是矩阵中的第三列,条形数由N确定。

此外,我想绘制几组这些矩阵,每组采用不同的颜色(“分组” 3D条形图。)

当我尝试如下绘制时:

ax.bar(data[:, 0], data[:, 1], zs=data[:, 2],
               zdir='z', alpha=0.8, color=curr_color)


我真的很奇怪-如此处所示:http://tinypic.com/r/anknzk/7

知道为什么酒吧如此弯曲和奇怪的形状?我只想在X-Y点上一个小节,它的高度等于Z点。

最佳答案

您没有正确使用关键字参数zs。它指的是放置每组钢筋的平面(沿轴zdir定义)。它们之所以弯曲,是因为它假设由ax.bar调用定义的一组条形图在同一平面上。最好多次调用ax.bar(每架飞机一次)。密切关注this example。您将希望zdir'x''y'

编辑

这是完整的代码(很大程度上基于上面的链接示例)。

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

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# this is just some setup to get the data
r = numpy.arange(5)
x1,y1 = numpy.meshgrid(r,r)
z1 = numpy.random.random(x1.shape)

# this is what your data probably looks like (1D arrays):
x,y,z = (a.flatten() for a in (x1,y1,z1))
# preferrably you would have it in the 2D array format
# but if the 1D is what you must work with:
# x is: array([0, 1, 2, 3, 4, 0, 1, 2, 3, 4,
#              0, 1, 2, 3, 4, 0, 1, 2, 3, 4,
#              0, 1, 2, 3, 4])
# y is: array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
#              2, 2, 2, 2, 2, 3, 3, 3, 3, 3,
#              4, 4, 4, 4, 4])

for i in range(0,25,5):
    # iterate over layers
    # (groups of same y)
    xs = x[i:i+5] # slice each layer
    ys = y[i:i+5]
    zs = z[i:i+5]
    layer = ys[0] # since in this case they are all equal.
    cs = numpy.random.random(3) # let's pick a random color for each layer
    ax.bar(xs, zs, zs=layer, zdir='y', color=cs, alpha=0.8)

plt.show()

10-07 14:37