我有三个数组,我正在尝试制作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直方图中?
答案 0 :(得分:1)
z
数组的形状必须与x
和y
相同,而不是xpos
和ypos
(形状相同) 。您可能会发现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()