If you have groups and subgroups, you probably want to display the subgroups values in a grouped barplot or a stacked barplot. In the first case, subgroups are displayed one beside each other, in the second case subgroups are displayed on top of each other.
Here is a code showing how to do a stacked barplot. Note that it can easily be turned as a stacked percent barplot.
# libraries import numpy as np import matplotlib.pyplot as plt from matplotlib import rc import pandas as pd # y-axis in bold rc('font', weight='bold') # Values of each group bars1 = [12, 28, 1, 8, 22] bars2 = [28, 7, 16, 4, 10] bars3 = [25, 3, 23, 25, 17] # Heights of bars1 + bars2 bars = np.add(bars1, bars2).tolist() # The position of the bars on the x-axis r = [0,1,2,3,4] # Names of group and bar width names = ['A','B','C','D','E'] barWidth = 1 # Create brown bars plt.bar(r, bars1, color='#7f6d5f', edgecolor='white', width=barWidth) # Create green bars (middle), on top of the firs ones plt.bar(r, bars2, bottom=bars1, color='#557f2d', edgecolor='white', width=barWidth) # Create green bars (top) plt.bar(r, bars3, bottom=bars, color='#2d7f5e', edgecolor='white', width=barWidth) # Custom X axis plt.xticks(r, names, fontweight='bold') plt.xlabel("group") # Show graphic plt.show()
Thanks for this simple example, it’s helping me on a project!
A couple notes: it seems pandas and numpy are being imported unnecessarily and you still have a TO DO in your comment.
Thanks again!
Thanks! but it doesn’t need to import pandas.
# Heights of bars1 + bars2 (TO DO better)
bars = [40, 35, 17, 12, 32]
# better(tm)
bars = [b1 + b2 for b1, b2 in zip(bars1, bars2)]
the way you “bottom” will only work properly if all values in all the lists are >= 0. If any are < 0, the addition does not yield a correct graph
the way you “bottom” will only work properly if all values in all the lists are >= 0. If any are < 0, the addition does not yield a correct graph