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 for any element beyond the 2nd one efficiently. I can get the example graph to stack correctly (always a,b,c,d from bottom to top)
import numpy as np import matplotlib.pyplot as plt ind = np.arange(3) a = [3,6,9] b = [2,7,1] c = [0,3,1] d = [4,0,3] p1 = plt.bar(ind, a, 1, color='#ff3333') p2 = plt.bar(ind, b, 1, color='#33ff33', bottom=a) p3 = plt.bar(ind, c, 1, color='#3333ff', bottom=[a[j] +b[j] for j in range(len(a))]) p4 = plt.bar(ind, d, 1, color='#33ffff', bottom=[a[j] +b[j] +c[j] for j in range(len(a))]) plt.show()
My final code could have very large number of bars and the ever expanding function bottom = [...] cannot be the best solution. It would be great if you could also explain how I need to derive the value. Is there a numpy function.
Thank you very much!!! PS I have searched for an answer but I did not understand what I could find.
How to create better stacked column charts. Bring the most important value to the bottom of the chart and use color to make it stand out. Your readers can compare values easier with each other if they have the same baseline. Consider stacking percentages (so that every total will sum up to 100%).
Here we'll use the figsize() method to change the bar plot size. Import matplotlib. pyplot library. To change the figure size, use figsize argument and set the width and the height of the plot.
Select the data that you want to display in the form of a chart. In the Insert tab, click Column Charts (in Charts section) and select “2-D stacked bar.” A chart appears, as shown in the following image. The stacked bar chart compares the sales revenue generated in different months with respect to time.
I have just recently faced the same problem. Afterwards I decided to wrap it all up in a nice class. For anyone interested you get an implementation of a stacked bar graph class here:
https://github.com/minillinim/stackedBarGraph
It allows scaled stacked graphs as well as setting bar widths and set heights (with scaled inners).
Given a data set like this:
d = np.array([[101.,0.,0.,0.,0.,0.,0.], [92.,3.,0.,4.,5.,6.,0.], [56.,7.,8.,9.,23.,4.,5.], [81.,2.,4.,5.,32.,33.,4.], [0.,45.,2.,3.,45.,67.,8.], [99.,5.,0.,0.,0.,43.,56.]]) d_heights = [1.,2.,3.,4.,5.,6.] d_widths = [.5,1.,3.,2.,1.,2.] d_labels = ["fred","julie","sam","peter","rob","baz"] d_colors = ['#2166ac', '#fee090', '#fdbb84', '#fc8d59', '#e34a33', '#b30000', '#777777']
It can make images like this:
GPLv3 with love.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With