How to Create Stacked Bar Chart in Matplotlib

Spread the love

In this post, you will learn How to create Stacked Bar Chart in Matplotlib.

plt.bar() –

Let’s create a dataset to work with.

import pandas as pd
df = pd.DataFrame({'nation': ['South Korea','China','Canada'],
                  'gold':[24, 10, 9],
                  'silver':[13, 15, 12],
                  'bronze':[11, 8, 12]})

Now, Let’s create a Stacked Bar Chart. Our goal is to put bronze data at bottom, then silver on top of it and gold at the top. Let’s see how to do it.

plt.figure(figsize=(8,7))

plt.bar(df['nation'], df['bronze'], label='bronze', 
        color='#CD7F32')

plt.bar(df['nation'], df['silver'], bottom=df['bronze'], 
        label='silver', color='silver')

plt.bar(df['nation'], df['gold'], bottom=df['bronze'] + df['silver'], 
        label='gold', color='gold')

plt.legend()
plt.savefig('stacked_mat1')
plt.show()

Here, First we created that bar that goes at the bottom in our case it is Bronze. Then we created the Silver bars and told matplotlib to keep bronze at the bottom of it with bottom = df[‘bronze’]. At last we created the Gold bars which will be at the top and told matplotlib to keep bronze and silver at the bottom of it with bottom=df[‘bronze’] + df[‘silver’]

Leave a Reply