【问题标题】:Stacked 3d bar chart with matplotlib使用 matplotlib 堆叠的 3d 条形图
【发布时间】:2016-06-28 21:57:23
【问题描述】:

我使用以下代码制作了一个简单的 3d 条形图:

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

ax.set_xlabel("x")
ax.set_ylabel("y") 
ax.set_zlabel("z")
ax.set_xlim3d(0,10)
ax.set_ylim3d(0,10) 
ax.set_zlim3d(0,2)

xpos = [2,5,8,2,5,8,2,5,8]
ypos = [1,1,1,5,5,5,9,9,9]
zpos = np.zeros(9)

dx = np.ones(9)
dy = np.ones(9)
dz = np.ones(9)

ax.bar3d(xpos, ypos, zpos, dx, dy, dz)
plt.gca().invert_xaxis()
plt.show()

把这当作一个测试,到目前为止一切似乎都很清楚。我只是想知道如何以堆叠的方式绘制这 9 个条形图中的每一个,例如每个条分为 4 个部分,构成整个条。

基本上,我正在考虑以示例here. 的方式这样做

但是,我想要 4 个,而不是 2 个堆栈。有什么想法可以从我现在的位置开始吗?非常感谢每一个提示。

谢谢!

编辑:如果我想为每个堆叠条实现给定值,例如:

...
z = [np.array([ 0.2, 0.6, 0.3, 0.6, 0.4, 0.3, 0.8, 0.5,  0.7]), 
     np.array([ 0.8, 0.4, 0.5, 0.2, 0.8, 0.7, 0.4, 0.2,  0.9]),
     np.array([ 0.1, 0.2, 0.4, 0.4, 0.2, 0.6, 0.3, 0.6,  0.9]),
     np.array([ 0.9, 0.5, 0.7, 0.2, 0.5, 0.6, 0.7, 0.9,  0.7])]
dz = [z for i in range(4)]
...

这似乎不起作用,我不知道为什么?

【问题讨论】:

  • 我做了类似here 的操作,但您可能会在使用 matplotlib 绘制深度信息的方式时遇到困难。不过,我的回答应该适用于您的问题,只有您必须更改 zpos 而不是条形图的颜色/不透明度。

标签: python matplotlib charts 3d


【解决方案1】:

要制作堆叠的 3d 条形图,您可以累积您的 dz 值并将它们用作每个下一个条形的基础。这是一个例子:

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

ax.set_xlabel("x")
ax.set_ylabel("y") 
ax.set_zlabel("z")
ax.set_xlim3d(0,10)
ax.set_ylim3d(0,10) 

xpos = [2,5,8,2,5,8,2,5,8]
ypos = [1,1,1,5,5,5,9,9,9]
zpos = np.zeros(9)

dx = np.ones(9)
dy = np.ones(9)
dz = [np.random.random(9) for i in range(4)]  # the heights of the 4 bar sets

_zpos = zpos   # the starting zpos for each bar
colors = ['r', 'b', 'g', 'y']
for i in range(4):
    ax.bar3d(xpos, ypos, _zpos, dx, dy, dz[i], color=colors[i])
    _zpos += dz[i]    # add the height of each bar to know where to start the next

plt.gca().invert_xaxis()
plt.show()

【讨论】:

  • 这看起来确实不错。符合我想象的方式,到目前为止!如果我有每个堆栈(和颜色)的值,例如我的第一个条包含值 v = [0.5,0.2,0.6,0.9] - 这些值因条而异:我如何在我的变量 dz 中实现它们?
  • 按照我的设置,dz 是 4 个数组的列表,每个数组中的元素是所有条形的单个级别的高度(例如,第一个数组是红色条,下一个是所有蓝色条等)。不过,我这样做只是为了匹配您的程序大纲。总的来说,如果你有一个想要使用的数据结构,那么在问题陈述中给出它会很有帮助,因为这些东西在 cmets 中很难解决。
  • 我在原始问题中为我的数据添加了一个示例。也许你能帮帮我?
猜你喜欢
  • 2019-05-30
  • 2021-10-22
  • 1970-01-01
  • 1970-01-01
  • 2017-11-02
  • 2020-10-05
  • 1970-01-01
相关资源
最近更新 更多