A stacked bar plot is a type of chart that uses bars divided into a number of sub-bars to visualize the values of multiple variables at once.
This tutorial provides a step-by-step example of how to create the following stacked bar plot in Python using the Seaborn data visualization package:
Step 1: Create the Data
First, let’s create the following pandas DataFrame that shows the total number of customers that a restaurant receives in the morning and evening from Monday through Friday:
import pandas as pd #create DataFrame df = pd.DataFrame({'Day': ['Mon', 'Tue', 'Wed', 'Thur', 'Fri'], 'Morning': [44, 46, 49, 59, 54], 'Evening': [33, 46, 50, 49, 60]}) #view DataFrame df Day Morning Evening 0 Mon 44 33 1 Tue 46 46 2 Wed 49 50 3 Thur 59 49 4 Fri 54 60
Step 2: Create the Stacked Bar Chart
We can use the following code to create a stacked bar chart to visualize the total customers each day:
import matplotlib.pyplot as plt
import seaborn as sns
#set seaborn plotting aesthetics
sns.set(style='white')
#create stacked bar chart
df.set_index('Day').plot(kind='bar', stacked=True, color=['steelblue', 'red'])
The x-axis displays the day of the week and the bars display how many customers visited the restaurant in the morning and evening each day.
Step 3: Customize the Stacked Bar Chart
The following code shows how to add axis titles, add an overall title, and rotate the x-axis labels to make them easier to read:
import matplotlib.pyplot as plt
import seaborn as sns
#set seaborn plotting aesthetics
sns.set(style='white')
#create stacked bar chart
df.set_index('Day').plot(kind='bar', stacked=True, color=['steelblue', 'red'])
#add overall title
plt.title('Customers by Time & Day of Week', fontsize=16)
#add axis titles
plt.xlabel('Day of Week')
plt.ylabel('Number of Customers')
#rotate x-axis labels
plt.xticks(rotation=45)
Note: We set the seaborn style to ‘white’ for this plot, but you can find a complete list of seaborn plotting aesthetics on this page.
Additional Resources
The following tutorials explain how to create other common visualizations in Seaborn:
How to Create a Pie Chart in Seaborn
How to Create a Time Series Plot in Seaborn
How to Create an Area Chart in Seaborn