Python 如何使用matplotlib/mplot3d绘制三维直方图?
我有三个数组,我正在尝试制作一个3D直方图Python 如何使用matplotlib/mplot3d绘制三维直方图?,python,matplotlib,mplot3d,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 nump
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数组必须具有相同的形状,而不是
x
和y
,而是xpos
和ypos
(它们本身的形状相同)。你可能会发现比你看上去更有用。下面的代码将演示应用于您的问题的第一个链接中的示例
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
值的x
和y
对,您会看到多个条。y
和x
轴上的值有点混乱,因为x
中的1
条实际上从1
到2
,8
从8
到9
@Matt pow的循环将/z
转换为/code>,形状(10L,)
array-intoz
a-shape(100L,)
数组由每个值的10个实例填充感谢您的解释我建议您这篇文章:Matplotlib在3D打印方面有一些问题,请注意!