Python中matplotlib的3D直方图异常行为
我有一个 Nx3 的矩阵,使用 scipy/numpy 来处理。我想用这个矩阵制作一个三维柱状图,其中 X 轴和 Y 轴的值分别来自矩阵的第一列和第二列,而每根柱子的高度则是矩阵的第三列。柱子的数量由 N 决定。
另外,我还想绘制几个这样的矩阵组,每组用不同的颜色(也就是一个“分组”的三维柱状图)。
当我尝试这样绘制时:
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 点的值。
1 个回答
2
你没有正确使用关键字参数 zs
。这个参数是用来指定每组柱子放置在哪个平面上的(这个平面是沿着 zdir
轴定义的)。柱子看起来歪歪的,是因为它假设通过 ax.bar
调用定义的一组柱子是在同一个平面上的。其实你可以多次调用 ax.bar
,每次为一个平面绘制柱子,这样效果会更好。可以参考 这个例子。你需要将 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()