gpt4 book ai didi

python - Python 中 matplotlib 中 3d 直方图的奇怪行为

转载 作者:行者123 更新时间:2023-12-01 06:11:53 25 4
gpt4 key购买 nike

我在 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()

关于python - Python 中 matplotlib 中 3d 直方图的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5489732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com