In my previous post, we have seen how we can plot multiple bar graph on a single plot. In this post, we will see how we can plot a stacked bar graph using Python’s Matplotlib library. A stacked bar graph also known as a stacked bar chart is a graph that is used to break down and compare parts of a whole.
Stacked Bar Graphs place each value for the segment after the previous one. The total value of the bar is all the segment values added together. They are basically ideal for comparing the total amounts across each group/segmented bar.
First of all, to create any type of bar graph whether it’s a single bar graph or a multiple bar graph, we need to import libraries that will help us to implement our task.
- Pandas library in this task will help us to import our ‘countries.csv’ file.
- From NumPy library, we will use np.array() to create an array
- And the final and most important library which helps us to visualize our data is Matplotlib. It will help us to plot multiple bar graph.
With the below lines of code, we can import all three libraries with their standard alias.
import numpy as np import pandas as pd import matplotlib.pyplot as plt
Let’s see how we can plot a stacked bar graph using Python’s Matplotlib library:
The below code will create the stacked bar graph using Python’s Matplotlib library. To create a stacked bar graph or stacked bar chart we have to pass the parameter bottom in the plt.bar () which informs Matplotlib library to stack the silver medal bars on top of the bronze medals bars and similarly gold medal bar on top. Have a look at the below code:
countries = ['Norway', 'Germany', 'Canada', 'United States', 'Netherlands'] bronzes = np.array([10,7,10,6,6]) silvers = np.array([14,10,8,8,6]) golds = np.array([14,14,11,9,8]) ind = [country for country in countries] plt.bar(ind, golds, width=0.6, label='golds', color='gold', bottom=silvers+bronzes) plt.bar(ind, silvers, width=0.6, label='silvers', color='silver', bottom=bronzes) plt.bar(ind, bronzes, width=0.6, label='bronzes', color='#CD7F32') plt.xticks(ind, countries) plt.ylabel("Medals") plt.xlabel("Countries") plt.legend(loc="upper right") plt.title("2018 Winter Olympics Top Scorers") plt.show()
Hope you like our post. To learn more about Matplotlib package, you can go through the official documentation here.