Stacked bar chart in Seaborn

Since this question asked for a stacked bar chart in Seaborn and the accepted answer uses pandas, I thought I’d give an alternative approach that actually uses Seaborn.

Seaborn gives an example of a stacked bar but it’s a bit hacky, plotting the total and then overlaying bars on top of it. Instead, you can actually use the histogram plot and weights argument.

import pandas as pd
import seaborn as sns

# Put data in long format in a dataframe.
df = pd.DataFrame({
    'country': countries2012 + countries2013,
    'year': ['2012'] * len(countries2012) + ['2013'] * len(countries2013),
    'percentage': percentage2012 + percentage2013
})

# One liner to create a stacked bar chart.
ax = sns.histplot(df, x='year', hue="country", weights="percentage",
             multiple="stack", palette="tab20c", shrink=0.8)
ax.set_ylabel('percentage')
# Fix the legend so it's not on top of the bars.
legend = ax.get_legend()
legend.set_bbox_to_anchor((1, 1))

seaborn stacked bar chart

Leave a Comment