与matplotlib堆叠的3d条形图

发布于 2021-01-29 14:55:17

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

基本上,我想以此处的示例方式执行此操作。

但是,我希望有2个堆栈,而不是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)]
...

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

关注者
0
被浏览
146
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    要制作堆叠的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()
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看