python - 如何使用 matplotlib/mplot3d 绘制 3D 直方图?

标签 python matplotlib mplot3d

我有三个数组,我正在尝试制作 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 直方图中?

最佳答案

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

enter image description here

关于python - 如何使用 matplotlib/mplot3d 绘制 3D 直方图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54014645/

相关文章:

python - 如何在 DataFrame 中将单词与数字相乘?

Python – Pandas : Get max value of last 5 days

python-2.7 - 具有自定义颜色的离散值的 matplotlib 热图

python-3.x - 使用 Matplotlib 绘制二进制 Numpy 数组的边界

python - 如何在 matplotlib 中显示 x10(上标数字)而不是 1e(数字)轴?

python - 使用 matplotlib、python 从三个正交向量和幅度绘制椭球体

python - 为什么Python中的id函数对不同的整型对象返回相同的值?

python - 如何从两个列表创建所有可能的短语,并遵循一些条件

Python - 为 3d 线图着色

python - matplotlib 3d 轴刻度、标签和 LaTeX