【发布时间】:2019-05-04 12:56:06
【问题描述】:
我在论坛中进行了搜索,但只找到了相似但不同的答案和问题。我在从 z 值矩阵开始绘制 3D 直方图时遇到问题。
这是我之前操作得到的矩阵:
[[ 84. 80.76923077 68.05555556 56.57894737 60.
44.7761194 55.2238806 39.0625 27.41935484 29.8245614 ]
[ 82.44274809 67.70833333 63.75 44.44444444 47.76119403
33.33333333 22.78481013 19.23076923 9.21052632 2.63157895]
[ 53.33333333 61.76470588 48.64864865 34.61538462 0.
16.66666667 0. 0. 0. 0. ]
[ 48. 25. 0. 0. 0.
0. 0. 0. 0. 0. ]]
这些都是 z 值。 x 和 y 值只是它们沿矩阵的位置。 我刚刚查看了 matplotlib 页面,但所有示例都从 x,y 值开始。我也看过论坛,但这个问题略有不同。
我正在尝试类似的东西:
hist, xedges, yedges = np.histogram2d(x, y, bins=(20,20))
xpos, ypos = np.meshgrid(xedges[:-1]+xedges[1:], yedges[:-1]+yedges[1:])
dx = xedges [1] - xedges [0]
dy = yedges [1] - yedges [0]
dz = hist.flatten()
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, zsort='average')
但是我在理解如何输入 x,y 值方面遇到了麻烦。 有人可以帮助我吗?
更新:
len_x, len_y = matrix.shape
x = np.linspace(0,len_x-1,len_x)
y = np.linspace(0,len_y-1,len_y)
# 3D PLOT:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
hist, xedges, yedges = np.histogram2d(x,y)
xpos, ypos = np.meshgrid(xedges[:-1]+xedges[1:], yedges[:-1]+yedges[1:])
xpos = xpos.flatten()/2.
ypos = ypos.flatten()/2.
zpos = np.zeros_like(xpos)
dx = xedges [1] - xedges [0]
dy = yedges [1] - yedges [0]
dz = hist.flatten()
max_height = np.max(dz)
min_height = np.min(dz)
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, zsort='average')
【问题讨论】:
-
您展示的代码与数据有何关系?该代码将生成一个 20 x 20 矩阵,而您拥有的是 4 x 10 矩阵。究竟是什么问题?也许您确切地展示了您尝试过的内容,在代码中明确编写
x = ...、y= ...等,以便了解您面临的问题。 -
问题是如何从第一个矩阵中得到x和y。我展示的代码是一个不起作用的试验......我不明白如何从初始矩阵中选择 x 和 y 值。
-
在您的情况下,x 将是 [0,1,2,...9],y 将是 [0,1,2,3]。然后
x,y = meshgrid(x,y)得到x和y矩阵。 -
谢谢,我已经更新了代码,但还是不行……
-
嗯,您要绘制直方图吗?还是您想在问题之上绘制您拥有的数组?
标签: python matplotlib 3d histogram