美文网首页
Matplotlib: 堆积柱形图的画法

Matplotlib: 堆积柱形图的画法

作者: wzNote | 来源:发表于2020-03-10 00:18 被阅读0次

    两层堆积

    import numpy as np 
    import matplotlib.pyplot as plt
     
    y1 = np.array([1,2,3,4])
    y2 = np.array([1,1,1,1])
    x = np.array([2009,2010,2011,2012])
     
    plt.figure(figsize=(4,4))
    plt.bar(x, y1, label='a')
    plt.bar(x, y2, bottom=y1, label='b') 
    
    leg = plt.legend(loc='lower center',frameon=False,bbox_to_anchor=(0.5, -0.18),ncol=2)
    plt.show()
    

    效果

    多层堆积

    关键点在于在画yi时,要计算出yi之前所有数据的和作为bottom,例如:
    y3的bottom为y1+y2
    y4的bottom为y1+y2+y3

    import numpy as np
    import matplotlib.pyplot as plt
     
    y1 = np.array([1,2,3,4])
    y2 = np.array([1,1,1,1])
    y3 = np.array([2,1,2,3])
    y = [y1, y2, y3]
    
    y_c = np.cumsum(y, 0)
    labels = ['a', 'b', 'c']
    
    x = np.array([2009,2010,2011,2012])
     
    plt.figure(figsize=(4,4.5))
    for i in range(3):
        if i == 0:
            plt.bar(x, y[i], label=labels[i])
        else:
            plt.bar(x, y[i], bottom=y_c[i-1], label=labels[i]) 
    
    leg = plt.legend(loc='lower center',frameon=False,bbox_to_anchor=(0.5, -0.18),ncol=3)
    
    plt.show()
    

    效果

    相关文章

      网友评论

          本文标题:Matplotlib: 堆积柱形图的画法

          本文链接:https://www.haomeiwen.com/subject/xaivdhtx.html