如何从二维数据中得到三维直方图?

2024-04-27 00:15:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数据列表:

x=[2006, 2007, 2008, 2009, 2010]
y=[700, 560, 450, 500, 570]

我需要建立一个规则的直方图(这并不困难)。但我也需要一个三维图,如图figure。我尝试了各种选择(例如,bar3d),但结果不是这样。请救命。你知道吗

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x= [float(i) for i in input('Input x ').split()]
y= [float(i) for i in input('Input y ').split()]

hist, xedges, yedges = np.histogram2d(x, y, bins=(4,4))
xpos, ypos = np.meshgrid(xedges[:-1]+xedges[1:], yedges[:-1]+yedges[1:])

xpos = xpos.flatten()/2.
ypos = ypos.flatten()/2.
zpos = np.ones_like (xpos)

dx = xedges [1] - xedges [0]
dy = yedges [1] - yedges [0]
dz = hist.flatten()

ax.bar3d(xpos, ypos,zpos , dx, 1, dz, color='b')
plt.xlabel ("X")
plt.ylabel ("Y")

plt.show()

Tags: inimportforasnpfigpltax
1条回答
网友
1楼 · 发布于 2024-04-27 00:15:07

将此行添加到代码的第一行:

from mpl_toolkits.mplot3d import Axes3D

已更新 希望这对你有帮助。你知道吗

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x=[2006, 2007, 2008, 2009, 2010]
z=[700, 560, 450, 500, 570]
ax.bar3d(x, 0, 0, 0.5, 0.5, z)
plt.show()

enter image description here

相关问题 更多 >