More efficient matplotlib stacked bar chart - how to calculate bottom values

前端 未结 4 600
悲哀的现实
悲哀的现实 2021-01-30 23:26

I need some help making a set of stacked bar charts in python with matlibplot. My basic code is below but my problems is how to generate the value for bottom fo

4条回答
  •  情话喂你
    2021-01-31 00:22

    [sum(values) for values in zip(a, b, c)]
    

    In Python 2 you can also do

    map(sum, zip(a, b, c))
    

    but Python 3 would need

    list(map(sum, zip(a, b, c)))
    

    which is less nice.


    You could encapsulate this:

    def sumzip(*items):
        return [sum(values) for values in zip(*items)]
    

    and then do

    p1 = plt.bar(ind, a, 1, color='#ff3333')
    p2 = plt.bar(ind, b, 1, color='#33ff33', bottom=sumzip(a))
    p3 = plt.bar(ind, c, 1, color='#3333ff', bottom=sumzip(a, b))
    p4 = plt.bar(ind, d, 1, color='#33ffff', bottom=sumzip(a, b, c))
    

    too.


    If a, b, c and d are numpy arrays you can also do sum([a, b, c]):

    a = np.array([3,6,9])
    b = np.array([2,7,1])
    c = np.array([0,3,1])
    d = np.array([4,0,3])
    
    p1 = plt.bar(ind, a, 1, color='#ff3333')
    p2 = plt.bar(ind, b, 1, color='#33ff33', bottom=sum([a]))
    p3 = plt.bar(ind, c, 1, color='#3333ff', bottom=sum([a, b]))
    p4 = plt.bar(ind, d, 1, color='#33ffff', bottom=sum([a, b, c]))
    

提交回复
热议问题