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

前端 未结 4 484
悲哀的现实
悲哀的现实 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:21

    I solved it like this:

    import numpy as np
    
    dates = # somehow get a list of dates
    labels = # a list of various labels
    colors = # somehow get a list of colors
    
    margin_bottom = np.zeros(dates)
    
    for index, label in enumerate(labels):
        values = # get your values for the label at index-th position from somewhere
        ax.bar(
            dates, values, 
            align='center', label=label, color=colors[index], bottom=margin_bottom
        )
        margin_bottom += values # here you simply add it to the previous margin
        # margin_bottom is a numpy array, adding a list will not change that
    

    It's similar to some other solutions, but it doesn't require all of the margins being stored at all time. Instead it "builds" the stacks from bottom up, adding more and more margin with each iteration.

提交回复
热议问题