How to plot mulitiple subplots of barplots using seaborn


Sometimes we want to plot multiple barplots in subplots, this examples shows a nice way to do it.

load sample data

import seaborn as sns
sns.set_theme(style="whitegrid")
tips = sns.load_dataset("tips")

tips.head(2)

total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3

aggregate the data by day and sex, and sum tips for each dimension

tips_agg = tips.groupby(['day','sex'])['tip'].sum().reset_index()
tips_agg

day sex tip
0 Thur Male 89.41
1 Thur Female 82.42
2 Fri Male 26.93
3 Fri Female 25.03
4 Sat Male 181.95
5 Sat Female 78.45
6 Sun Male 186.78
7 Sun Female 60.61

install the latest seaborn package if not installed

!pip install seaborn==0.11.2

visualize the total tips of male vs female, for each different weekday in the data

from matplotlib import pyplot as plt
import seaborn as sns
import math

# automatically adjust the rows and colums
all_days = list(set(tips_agg['day']))
n_cols = 3
n_rows = math.ceil(len(all_days)/n_cols)


# give the figsize
fig, axes = plt.subplots( n_rows, n_cols, figsize=(20, 10))


for i in range(n_rows):
for j in range(n_cols):
index = i*n_cols+j

if index >= len(all_days):
break

day = all_days[index]
bp = sns.barplot(ax=axes[i, j], data=tips_agg[tips_agg['day']==day], x='sex', y='tip')
bp.set(title=day)
for item in bp.get_xticklabels():
item.set_rotation(45)

# if the x axis title is very long, this configuration will be very useful
plt.tight_layout()

png


Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC