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

前端 未结 4 487
悲哀的现实
悲哀的现实 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条回答
  •  -上瘾入骨i
    2021-01-31 00:30

    Converting your values to numpy arrays will make your life easier:

    data = np.array([a, b, c, d])
    bottom = np.cumsum(data, axis=0)
    colors = ('#ff3333', '#33ff33', '#3333ff', '#33ffff')
    
    plt.bar(ind, data[0], color=colors[0])
    for j in xrange(1, data.shape[0]):
        plt.bar(ind, data[1], color=colors[j], bottom=bottom[i-1])
    

    Alternatively, to get rid of the nasty particular case for the first bar:

    data = np.array([a, b, c, d])
    bottom = np.vstack((np.zeros((data.shape[1],), dtype=data.dtype),
                        np.cumsum(data, axis=0)[:-1]))
    colors = ('#ff3333', '#33ff33', '#3333ff', '#33ffff')
    for dat, col, bot in zip(data, colors, bottom):
        plt.bar(ind, dat, color=col, bottom=bot)
    

提交回复
热议问题