pbPassingBI
/
Visualisation & export intermediate 5 min

Statistical charts with seaborn

Better defaults, and the charts that are painful in raw matplotlib.

What you'll be able to do
  • Build seaborn charts from a DataFrame
  • Split a chart by category with hue
  • Use box plots and heatmaps

The seaborn idea

import seaborn as sns
sns.set_theme(style='whitegrid')

sns.barplot(data=df, x='region', y='revenue')
sns.lineplot(data=df, x='month', y='revenue', hue='region')
sns.scatterplot(data=df, x='spend', y='revenue', hue='segment', size='orders')

Seaborn takes the DataFrame plus column names, which means it handles grouping, colouring and the legend for you.

This is why long-form data matters — hue='region' needs region as a column, not as several columns.

Distributions

sns.histplot(data=df, x='revenue', bins=30, kde=True)
sns.boxplot(data=df, x='region', y='revenue')
sns.violinplot(data=df, x='region', y='revenue')

A box plot compares distributions across categories in one chart — median, quartiles and outliers — which takes considerable work in raw matplotlib.

Heatmaps

pivot = df.pivot_table(index='region', columns='month', values='revenue', aggfunc='sum')
sns.heatmap(pivot, annot=True, fmt='.0f', cmap='Blues')

Good for spotting patterns across two dimensions. annot=True keeps the exact numbers visible, which makes it readable as a table as well as a picture.

A correlation heatmap is a one-liner: sns.heatmap(df.corr(numeric_only=True), annot=True).

Small multiples

sns.relplot(data=df, x='month', y='revenue',
            col='region', col_wrap=3, kind='line')

One small chart per category, on a shared scale. Often clearer than cramming five lines into one axis — and it is a single line of code.

Key points
  • Seaborn takes a DataFrame and column names, and handles grouping for you
  • hue= requires long-form data, which is why melt matters
  • Box plots and heatmaps are where seaborn saves the most effort
Check yourself