Python 带matplotlib的堆叠三维条形图

Python 带matplotlib的堆叠三维条形图,python,matplotlib,charts,3d,Python,Matplotlib,Charts,3d,我使用以下代码制作了一个简单的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

我使用以下代码制作了一个简单的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个部分,组成整个条

基本上,我想用例子的方式来做这件事

但是我想要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)]
...

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

要制作堆叠的三维条形图,您可以累积
dz
值,并将其用作下一个条形图的基础。下面是一个例子:


我也做了类似的事情,但使用matplotlib绘制深度信息的方法可能会遇到困难。我的答案应该适用于你的问题,只是你需要更改
zpos
而不是条形图的颜色/不透明度。这看起来确实很好。和我想象的一样,谢谢!如果我有每个堆栈(和颜色)的值,例如,我的第一个条形图由值v=[0.5,0.2,0.6,0.9]-组成,并且这些值随条形图的不同而变化:我如何在变量dz中输入它们?在设置时,dz是4个数组的列表,每个数组中的元素是所有条形图的单个级别的高度(例如,第一个数组是所有红色条,第二个数组是所有蓝色条,等等)。我这样做只是为了配合你的计划大纲。总的来说,如果你有一个想要使用的数据结构,在问题陈述中给出它是很有帮助的,因为这些东西在评论中很难解决。我在原始问题中为我的数据添加了一个示例。也许你可以帮助我?
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()