【问题标题】:How to plot a 3D histogram with matplotlib/mplot3d?如何使用 matplotlib/mplot3d 绘制 3D 直方图?
【发布时间】:2019-01-02 23:45:50
【问题描述】:

我有三个数组,我正在尝试制作 3D 直方图。

x = [1, 2, 3, 2, 5, 2, 6, 8, 6, 7]
y = [10, 10, 20, 50, 20, 20, 30, 10, 40, 50, 60]
z = [105, 25, 26, 74, 39, 85, 74, 153, 52, 98]

到目前为止,这是我的尝试:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = plt.axes(projection='3d')

binsOne = sorted(set(x))
binsTwo = sorted(set(y))
hist, xedges, yedges = np.histogram2d(x, y, bins=[binsOne, binsTwo])
xpos, ypos = np.meshgrid(xedges[:-1] + 0.25 , yedges[:-1] + 0.25)
xpos = xpos.flatten('F')
ypos = ypos.flatten('F')
zpos = np.zeros_like(xpos)

dx = dx.flatten()
dy = dy.flatten()
dz = hist.flatten()

ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average')

如何将 z 数组合并到我的 3D 直方图中?

【问题讨论】:

标签: python matplotlib mplot3d


【解决方案1】:

z 数组必须具有相同的形状,不是xy,而是xposypos(它们本身的形状相同)。你可能会发现this example 比你看起来是drawing from 更有用。以下代码是为了演示应用于您问题的第一个链接中的示例,

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')

_x = [1, 2, 3, 2, 5, 2, 6, 8, 6, 7]
_y = [10, 10, 20, 50, 20, 20, 30, 10, 40, 50]
_xx, _yy = np.meshgrid(_x, _y)
x, y = _xx.ravel(), _yy.ravel()
_z = np.array([105, 25, 26, 74, 39, 85, 74, 153, 52, 98])

# There may be an easier way to do this, but I am not aware of it
z = np.zeros(len(x))
for i in range(1, len(x)):
    z[i] = _z[(i*len(_z)) / len(x)]

bottom = np.zeros_like(z)
width = depth = 1

ax.bar3d(x, y, bottom, width, depth, z, shade=True)
plt.show()

【讨论】:

  • 感谢您的回答,为什么 ax.bar3d 中的 z 不跟随 x 和 y?你也可以向我解释一下 for 循环对 _z 有什么作用吗?
  • @Matt-pow 我不明白你的问题,数组中的z 值决定了条形的高度,x 值决定了x 的位置和y 值确定 y 位置。对于对应于公共 z 值的 xy 对,您会看到多个条形。 yx 轴上的值有点令人困惑,因为 x 中的条形 1 实际上从 12889
  • @Matt-pow _zfor 循环将 _z,一个形状 (10L, ) 数组转换为 z 一个形状 (100L, ) 数组,由每个值的 10 个实例填充
  • 感谢您的解释
猜你喜欢
  • 2020-12-02
  • 1970-01-01
  • 2019-03-05
  • 2016-06-09
  • 2015-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多