【问题标题】:Python 3D stacked bar char plotPython 3D堆积条形图
【发布时间】:2017-02-20 22:14:13
【问题描述】:

我希望制作一个 3D 条形图,如 herehere 所示,但带有堆叠条形图,如 here 所示。

有人知道如何在同一个情节中做这两个吗?

谢谢!

【问题讨论】:

    标签: python matplotlib plot


    【解决方案1】:

    您也可以使用 bar3d 来做到这一点:zpos 参数允许您设置条的底部。这是一个基于 matplotlib 示例 (hist3d_demo.py) 的演示代码的示例

    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')
    x, y = np.random.rand(2, 100) * 4
    hist, xedges, yedges = np.histogram2d(x, y, bins=4, range=[[0, 4], [0, 4]])
    
    # Construct arrays for the anchor positions of the 16 bars.
    # Note: np.meshgrid gives arrays in (ny, nx) so we use 'F' to flatten xpos,
    # ypos in column-major order. For numpy >= 1.7, we could instead call meshgrid
    # with indexing='ij'.
    xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25)
    xpos = xpos.flatten('F')
    ypos = ypos.flatten('F')
    # z position set to zero
    zpos = np.zeros_like(xpos)
    
    # Construct arrays with the dimensions for the 16 bars.
    dx = 0.5 * np.ones_like(zpos)
    dy = dx.copy()
    dz = hist.flatten()
    # Create a random second histogram
    dz2 = dz * np.random.rand(16)
    # Set z position to the values of the first histogram
    zpos2 = dz
    
    ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average', alpha=0.7)
    ax.bar3d(xpos, ypos, zpos2, dx, dy, dz2, color='r', zsort='average', alpha=0.7)
    
    plt.show()
    

    Figure with the 3-D bar chart

    【讨论】:

      【解决方案2】:

      您可以在 3-D 条形图中设置bottom,与 2-D 相同:

      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')
      colors = ['r', 'g', 'b', 'y']
      for i, (c, z) in enumerate(zip(colors, [30, 20, 10, 0])):
          xs = np.arange(20)
          ys = np.random.rand(20)
          ys2 = np.random.rand(20)
          ys3 = np.random.rand(20)
      
          # You can provide either a single color or an array. To demonstrate this,
          # the first bar of each set will be colored cyan.
          cs = [c] * len(xs)
          cs[0] = 'c'
          ax.bar(xs, ys, zs=z, zdir='y', color=cs, alpha=0.8)
          ax.bar(xs, ys2, bottom=ys, zs=z, zdir='y', color=colors[(i+1)%4], alpha=0.8)
          ax.bar(xs, ys3, bottom=ys+ys2, zs=z, zdir='y', color=colors[(i+2)%4], alpha=0.8)
      
      ax.set_xlabel('X')
      ax.set_ylabel('Y')
      ax.set_zlabel('Z')
      
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-02-26
        • 2014-02-09
        • 2019-04-15
        • 2023-03-11
        • 2018-03-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多