A Guided Introduction to Seaborn

What is Seaborn?

  • A high-level plotting library built on top of matplotlib
  • Works directly with pandas DataFrames: you name columns, Seaborn handles the mapping
  • Built-in statistical aggregation (means, confidence intervals, density estimates)
  • Sensible defaults for color, layout, and legends, with full matplotlib access when you need it
  • Core idea: map variables to visual properties (x, y, hue, size, style, col, row)

Setup

  • Standard import aliases: sns, plt, pd, np
  • sns.set_theme() applies Seaborn’s default look to every plot that follows
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

sns.set_theme()                      # default Seaborn theme
print("seaborn", sns.__version__)
seaborn 0.13.2

Part 1: The Gapminder Data

About the dataset

  • Popularized by Hans Rosling and the Gapminder Foundation to show global development trends
  • One row per country-year, sampled every 5 years from 1952 to 2007
  • Columns: country, continent, year, lifeExp (years), pop (people), gdpPercap (inflation-adjusted USD)
  • Tidy (“long”) format: exactly what Seaborn wants

Loading the data

  • Read the CSV directly from a public URL
  • Alternative if offline: plotly.express.data.gapminder() returns the same table
url = "https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv"
gm_raw = pd.read_csv(url)
gm_raw.head()
country year pop continent lifeExp gdpPercap
0 Afghanistan 1952 8425333.0 Asia 28.801 779.445314
1 Afghanistan 1957 9240934.0 Asia 30.332 820.853030
2 Afghanistan 1962 10267083.0 Asia 31.997 853.100710
3 Afghanistan 1967 11537966.0 Asia 34.020 836.197138
4 Afghanistan 1972 13079460.0 Asia 36.088 739.981106

First look: shape, types, missing values

  • Always check size, dtypes, and missingness before plotting
  • info() gives all three at once
print(gm_raw.shape)
gm_raw.info()
(1704, 6)
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1704 entries, 0 to 1703
Data columns (total 6 columns):
 #   Column     Non-Null Count  Dtype  
---  ------     --------------  -----  
 0   country    1704 non-null   object 
 1   year       1704 non-null   int64  
 2   pop        1704 non-null   float64
 3   continent  1704 non-null   object 
 4   lifeExp    1704 non-null   float64
 5   gdpPercap  1704 non-null   float64
dtypes: float64(3), int64(1), object(2)
memory usage: 80.0+ KB
print("Missing values:", gm_raw.isna().sum().sum())
print("Duplicate rows:", gm_raw.duplicated().sum())
print("Countries:", gm_raw["country"].nunique(), "| Years:", sorted(gm_raw["year"].unique()))
Missing values: 0
Duplicate rows: 0
Countries: 142 | Years: [np.int64(1952), np.int64(1957), np.int64(1962), np.int64(1967), np.int64(1972), np.int64(1977), np.int64(1982), np.int64(1987), np.int64(1992), np.int64(1997), np.int64(2002), np.int64(2007)]

Quick summary statistics

  • describe() for numeric columns; value_counts() for categories
  • Note the scale differences: pop and gdpPercap span several orders of magnitude (a hint that log scales will help)
gm_raw.describe().round(1)
year pop lifeExp gdpPercap
count 1704.0 1.704000e+03 1704.0 1704.0
mean 1979.5 2.960121e+07 59.5 7215.3
std 17.3 1.061579e+08 12.9 9857.5
min 1952.0 6.001100e+04 23.6 241.2
25% 1965.8 2.793664e+06 48.2 1202.1
50% 1979.5 7.023596e+06 60.7 3531.8
75% 1993.2 1.958522e+07 70.8 9325.5
max 2007.0 1.318683e+09 82.6 113523.1
gm_raw.drop_duplicates("country")["continent"].value_counts()   # countries per continent
continent
Africa      52
Asia        33
Europe      30
Americas    25
Oceania      2
Name: count, dtype: int64

Basic cleaning

  • Data is already clean (no missing values, no duplicates), so cleaning is light:
  • Rename columns to consistent snake_case
  • Make continent an ordered categorical so every plot uses the same order and colors
  • Add convenience columns: population in millions and log10 GDP per capita
gm = gm_raw.rename(columns={"lifeExp": "life_exp", "gdpPercap": "gdp_per_cap"})

continent_order = ["Africa", "Americas", "Asia", "Europe", "Oceania"]
gm["continent"] = pd.Categorical(gm["continent"], categories=continent_order, ordered=True)

gm["pop_m"] = gm["pop"] / 1e6                     # population in millions
gm["log_gdp"] = np.log10(gm["gdp_per_cap"])       # log10 GDP per capita
gm.head()
country year pop continent life_exp gdp_per_cap pop_m log_gdp
0 Afghanistan 1952 8425333.0 Asia 28.801 779.445314 8.425333 2.891786
1 Afghanistan 1957 9240934.0 Asia 30.332 820.853030 9.240934 2.914265
2 Afghanistan 1962 10267083.0 Asia 31.997 853.100710 10.267083 2.931000
3 Afghanistan 1967 11537966.0 Asia 34.020 836.197138 11.537966 2.922309
4 Afghanistan 1972 13079460.0 Asia 36.088 739.981106 13.079460 2.869221

A useful snapshot: 2007

  • Many plots are clearer with one year (one row per country)
  • We will use gm07 for cross-sectional plots and the full gm for trends over time
  • Oceania has only 2 countries (Australia, New Zealand): keep this in mind when comparing continents
gm07 = gm[gm["year"] == 2007].copy()
print(gm07.shape)
gm07.sort_values("life_exp").head(3)
(142, 8)
country year pop continent life_exp gdp_per_cap pop_m log_gdp
1463 Swaziland 2007 1133066.0 Africa 39.613 4513.480643 1.133066 3.654512
1043 Mozambique 2007 19951656.0 Africa 42.082 823.685621 19.951656 2.915761
1691 Zambia 2007 11746035.0 Africa 42.384 1271.211593 11.746035 3.104218

Part 2: Univariate Visualizations

The Seaborn API in one slide

  • Axes-level functions draw onto a single matplotlib Axes: histplot, kdeplot, boxplot, scatterplot, …
  • Figure-level functions manage a whole figure and can facet: displot, catplot, relplot
  • Three families:
    • Distributions: histplot, kdeplot, ecdfplot → displot
    • Categorical: countplot, barplot, boxplot, violinplot, stripplot → catplot
    • Relational: scatterplot, lineplot → relplot
  • Common signature: sns.func(data=df, x="col", y="col", hue="col")

The simplest plot: a histogram

  • histplot bins one numeric variable and counts observations per bin
  • Question: how is life expectancy distributed across countries in 2007?
sns.histplot(data=gm07, x="life_exp")

Controlling bins and the statistic

  • bins= sets number of bins; binwidth= sets their width (often more interpretable)
  • stat= changes the y-axis: "count", "percent", "density", "probability"
  • kde=True overlays a smooth density estimate
sns.histplot(data=gm07, x="life_exp", binwidth=5, stat="percent", kde=True)

Splitting by a category with hue

  • hue= maps a categorical column to color
  • multiple= controls overlap: "layer" (default), "stack", "dodge", "fill"
  • The bimodal shape from the last slide is largely Africa vs. everyone else
sns.histplot(data=gm07, x="life_exp", hue="continent", multiple="stack", binwidth=5)

Caption: In a stacked histogram, each bar’s total height represents the total number of observations for that bin, with each color stacked on top of the previous one. For example, the blue bars at the top do not show large counts on their own—they are added above the other colors, so a short blue bar still means a small number, even if it’s high up on the plot.

sns.histplot(data=gm07, x="life_exp", hue="continent", multiple="fill", binwidth=5, alpha=0.5)

sns.histplot(data=gm07, x="life_exp", hue="continent", multiple="dodge", binwidth=5, alpha=0.5)

Kernel density estimates

  • kdeplot draws a smoothed estimate of the distribution
  • fill=True shades the area; common_norm=False normalizes each group separately
  • bw_adjust= controls smoothness (smaller = wigglier)
  • Caution: KDEs can extend past real data limits (e.g., below 0)
sns.kdeplot(data=gm07, x="life_exp", hue="continent", fill=True, common_norm=True, alpha=0.3)

sns.kdeplot(data=gm07, x="life_exp", hue="continent", fill=True, common_norm=False, alpha=0.3)

Skewed data and log scales

  • GDP per capita is heavily right-skewed: most countries are poor, a few are very rich
  • log_scale=True bins on a log axis, revealing structure hidden in the raw scale
  • Compare the two: same data, very different stories
sns.histplot(data=gm07, x="gdp_per_cap")

sns.histplot(data=gm07, x="gdp_per_cap", log_scale=True)

Empirical CDFs

  • ecdfplot shows the fraction of observations at or below each value
  • No binning or smoothing choices: nothing to tune, nothing hidden
  • Read it as: “what share of countries have life expectancy below X?”
sns.kdeplot(data=gm07, x="life_exp", hue="continent", fill=True, common_norm=False, alpha=0.3)

sns.ecdfplot(data=gm07, x="life_exp", hue="continent")

Figure-level distributions: displot

  • displot wraps histplot, kdeplot, ecdfplot (choose with kind=)
  • Adds faceting: col= and row= create small multiples, one panel per category
  • col_wrap= wraps panels onto multiple rows; height= / aspect= size each panel
sns.displot(data=gm07, x="life_exp", col="continent", col_wrap=3, binwidth=5, height=2.5)

Categorical counts: countplot

  • Univariate for a categorical variable: bar height = number of rows
  • Here, number of countries per continent
sns.countplot(data=gm07, x="continent")

Box plots: one variable, compared across groups

  • Box = interquartile range (IQR); line = median; whiskers = 1.5 × IQR; points = outliers
  • Still a univariate summary, just repeated per group
  • Swap x and y for horizontal boxes (often easier to read with long labels)
sns.boxplot(data=gm07, x="life_exp", y="continent")

Violin plots

  • A box plot plus a mirrored KDE: shows shape, not just quartiles
  • inner="quart" draws quartile lines; inner="point" shows observations
  • cut=0 stops the density at the data range
sns.violinplot(data=gm07, x="life_exp", y="continent", inner="quart", cut=0)
plt.show() 

Showing every observation: strip and swarm

  • stripplot plots each point with random jitter
  • swarmplot arranges points so none overlap (best for small to medium n)
  • Layering points over a box plot is a common, honest combination
sns.boxplot(data=gm07, x="life_exp", y="continent", color="white", fliersize=0) 
sns.stripplot(data=gm07, x="life_exp", y="continent", alpha=0.6)
plt.show()

Bar plots show an estimate, not raw data

  • barplot computes a statistic per group (default: mean) with an error bar
  • estimator= changes the statistic (e.g., "median", "sum")
  • errorbar= controls the interval: ("ci", 95), "sd", "se", or None
  • Question: which continents hold the most people in 2007?
sns.barplot(data=gm07, x="continent", y="pop_m", estimator="mean", errorbar=None)

Part 3: Under the Hood: Seaborn Draws on Matplotlib

Axes-level functions return a matplotlib Axes

  • Every axes-level Seaborn call returns the Axes it drew on
  • That object has the full matplotlib API: set_title, set_xlabel, axvline, annotate, …
  • Seaborn handles the data mapping; matplotlib handles the fine details
ax = sns.histplot(data=gm07, x="life_exp", binwidth=5)
ax.annotate("Maximum peak", xy=(65, 30), xytext=(65, 30), fontsize=12)
print(type(ax))
print(type(ax.figure))
<class 'matplotlib.axes._axes.Axes'>
<class 'matplotlib.figure.Figure'>

Titles, labels, and limits

  • ax.set(...) sets many properties in one call
  • Use descriptive axis labels with units, not raw column names
ax = sns.histplot(data=gm07, x="life_exp", binwidth=5)
# ax.set_title("A damped spring: the model matches the measurements", fontsize=12 + 4)
ax.set(title="Life expectancy, 2007", xlabel="Life expectancy (years)", ylabel="Number of countries", xlim=(35, 85))
FS=16
ax.title.set_fontsize(FS + 4)
ax.xaxis.label.set_fontsize(FS + 2)
ax.yaxis.label.set_fontsize(FS + 2)

Reference lines and annotations

  • axvline / axhline add vertical or horizontal reference lines
  • ax.annotate places text with an optional arrow
  • Use these to point the reader at the key takeaway
ax = sns.histplot(data=gm07, x="life_exp", binwidth=5)
med = gm07["life_exp"].median()
ax.axvline(med, color="crimson", ls="--", lw=2)
ax.annotate(f"Median: {med:.1f} yrs", xy=(med, 25), xytext=(48, 27), arrowprops=dict(arrowstyle="->"))
ax.set(xlabel="Life expectancy (years)", ylabel="Countries")

Tick formatting

  • matplotlib.ticker formatters control tick label text
  • Useful for currency, percentages, thousands separators
  • ax.tick_params adjusts size, rotation, and direction
from matplotlib.ticker import StrMethodFormatter

ax = sns.histplot(data=gm07, x="gdp_per_cap", log_scale=True)
ax.xaxis.set_major_formatter(StrMethodFormatter("${x:,.0f}"))
ax.tick_params(axis="x", labelrotation=90)
ax.set(xlabel="GDP per capita (log scale)")

Building multi-panel layouts

  • Create the layout with plt.subplots, then pass each Axes to Seaborn via ax=
  • This gives you full control over mixing different plot types
  • fig.suptitle adds an overall title; fig.tight_layout() fixes overlaps
fig, axes = plt.subplots(1, 3, figsize=(13, 3.5))

sns.histplot(data=gm07, x="life_exp", ax=axes[0])
sns.boxplot(data=gm07, x="continent", y="life_exp", ax=axes[1])
sns.ecdfplot(data=gm07, x="gdp_per_cap", log_scale=True, ax=axes[2])
axes[1].tick_params(axis="x", labelrotation=45)
fig.suptitle("Three views of the 2007 snapshot")
fig.tight_layout()

Figure-level functions return a FacetGrid

  • displot, catplot, relplot return a grid object, not an Axes
  • g.figure is the matplotlib Figure; g.axes is an array of Axes
  • Grid helpers: g.set_axis_labels, g.set_titles, g.figure.suptitle
  • Do not pass ax= to figure-level functions: they create their own figure
g = sns.displot(data=gm07, x="life_exp", col="continent", col_wrap=3, binwidth=5, height=2.5)
print(type(g))
g.set_axis_labels("Life expectancy (years)", "Countries")
g.set_titles("{col_name}")
g.figure.suptitle("Life expectancy by continent, 2007", y=1.03)
<class 'seaborn.axisgrid.FacetGrid'>
Text(0.5, 1.03, 'Life expectancy by continent, 2007')

Saving figures

  • Save from the matplotlib Figure: fig.savefig(...) or g.savefig(...)
  • dpi= controls resolution; bbox_inches="tight" trims whitespace
  • Vector formats (.pdf, .svg) scale cleanly in papers and slides

Part 4: Multivariate Visualizations

Two numeric variables: scatter plot

  • scatterplot maps one column to x and one to y
  • Question: are richer countries healthier?
  • The raw relationship looks strongly curved
sns.scatterplot(data=gm07, x="gdp_per_cap", y="life_exp")

Fixing the scale

  • A log x-axis turns the curve into a near-straight line
  • Interpretation: each multiplicative increase in income is associated with a roughly constant gain in life expectancy
  • Use ax.set_xscale("log") (matplotlib) after plotting
ax = sns.scatterplot(data=gm07, x="gdp_per_cap", y="life_exp")
ax.set_xscale("log")

Adding a third variable with hue

  • Color by continent (categorical): Seaborn chooses a qualitative palette and builds the legend
  • Color by a numeric column gives a continuous colormap instead
ax = sns.scatterplot(data=gm07, x="gdp_per_cap", y="life_exp", hue="continent")
ax.set_xscale("log")

Four variables: the Gapminder bubble chart

  • size= maps a numeric column to marker area; sizes= sets the min and max size
  • Now position, color, and size each carry information
  • legend= and bbox_to_anchor move the crowded legend outside the plot
ax = sns.scatterplot(data=gm07, x="gdp_per_cap", y="life_exp", hue="continent", size="pop_m",
                     sizes=(20, 1200), alpha=0.7, edgecolor="black")
ax.set_xscale("log")
ax.xaxis.set_major_formatter(StrMethodFormatter("${x:,.0f}"))
ax.tick_params(axis="x", labelrotation=90)

ax.set(xlabel="GDP per capita (USD, log scale)", ylabel="Life expectancy (years)", title="Wealth and health, 2007")
sns.move_legend(ax, "upper left", bbox_to_anchor=(1, 1), fontsize=8, labelspacing=1.3)

Adding a trend: regplot

  • regplot draws a scatter plus a linear fit with a confidence band
  • logx=True fits y against log(x); lowess=True fits a flexible smooth curve
  • scatter_kws / line_kws pass styling to each layer
ax = sns.regplot(data=gm07, x="gdp_per_cap", y="life_exp", logx=True,
                 scatter_kws={"alpha": 0.5}, line_kws={"color": "crimson"})
ax.set_xscale("log")

Faceted regressions: lmplot

  • Figure-level version of regplot: supports hue, col, row
  • Here, a separate fit for each continent (using the pre-computed log_gdp column)
  • Does the wealth and health slope differ by region?
sns.lmplot(data=gm07, x="log_gdp", y="life_exp", hue="continent", height=4, aspect=1.4, ci=None)

Joint and marginal distributions: jointplot

  • Combines a bivariate plot with univariate marginals on the edges
  • kind= options: "scatter", "kde", "hex", "reg", "hist"
  • A natural bridge between Parts 2 and 4
sns. (data=gm07, x="log_gdp", y="life_exp", hue="continent", height=5)

Change over time: lineplot

  • Now we switch to the full multi-year gm data
  • With many rows per x value, lineplot aggregates: plots the mean with a 95% CI band
  • Here: average life expectancy across all countries, by year
sns.lineplot(data=gm, x="year", y="life_exp")

One line per country: units

  • Without aggregation, use units= with estimator=None to draw each country separately
  • Low alpha produces a “spaghetti plot” that shows spread and outliers
  • The sharp dips are real events (e.g., Rwanda in 1992, Cambodia in 1977)
sns.lineplot(data=gm, x="year", y="life_exp", hue="continent", units="country", estimator=None, lw=0.8, alpha=0.4)

Small multiples over time: relplot

  • Figure-level version of scatterplot / lineplot (kind="line" or "scatter")
  • Facet by continent with col=, highlight a few countries on top with matplotlib
g = sns.relplot(data=gm, x="year", y="life_exp", col="continent", col_wrap=3, kind="line",
                units="country", estimator=None, color="gray", alpha=0.3, lw=0.8, height=2.6)
g.set_titles("{col_name}")

Heatmaps for country-by-year grids

  • heatmap displays a 2-D table as colored cells
  • Reshape first: pivot rows = country, columns = year, values = life expectancy
  • cmap= sets the colormap; annot=True would print values in each cell
asia = gm[gm["continent"] == "Asia"].pivot(index="country", columns="year", values="life_exp")
asia = asia.sort_values(2007)
plt.figure(figsize=(8, 8))
sns.heatmap(asia, cmap="viridis", cbar_kws={"label": "Life expectancy (years)"})

Correlation heatmap

  • A common pattern: compute df.corr(), then heatmap with a diverging colormap centered at 0
  • annot=True, fmt=".2f" prints each coefficient
  • Note: log GDP correlates more strongly than raw GDP
corr = gm07[["life_exp", "gdp_per_cap", "log_gdp", "pop_m"]].corr()
sns.heatmap(corr, annot=True, fmt=".2f", cmap="vlag", center=0, vmin=-1, vmax=1, square=True)

All pairs at once: pairplot

  • Scatter plot for every pair of numeric columns, distributions on the diagonal
  • Great for a first exploratory pass; can get crowded with many columns
  • vars= selects columns; corner=True drops the redundant upper triangle
sns.pairplot(data=gm07, vars=["life_exp", "log_gdp", "pop_m"], hue="continent", corner=True, height=2.3)

Categorical plots with two groupings: catplot

  • Figure-level wrapper for all categorical plots (kind="box", "violin", "bar", "strip", …)
  • Combine x (category), y (numeric), and hue (second category)
  • Here: life expectancy by continent at three snapshot years
years = gm[gm["year"].isin([1957, 1982, 2007])]
sns.catplot(data=years, x="continent", y="life_exp", hue="year", kind="box", height=4, aspect=1.8, palette="crest")

Part 5: Themes and Seaborn Customization

set_theme: one call for the global look

  • sns.set_theme(style=..., context=..., palette=..., font_scale=...)
  • Affects every plot after the call, until you change it again
  • Five built-in styles: darkgrid (default), whitegrid, dark, white, ticks
fig = plt.figure(figsize=(16, 2.6))
for i, style in enumerate(["darkgrid", "whitegrid", "dark", "white", "ticks"]):
    with sns.axes_style(style):                  # style applies to axes created inside the block
        ax = fig.add_subplot(1, 5, i + 1)
        sns.kdeplot(data=gm07, x="life_exp", fill=True, ax=ax)
        ax.set(title=style, xlabel="", ylabel="", yticks=[])
fig.tight_layout()

Temporary styles and despine

  • with sns.axes_style("..."): applies a style to only the plots inside the block
  • sns.despine() removes the top and right spines; trim=True and offset= tighten the frame
  • Pairs especially well with white and ticks
with sns.axes_style("ticks"):
    ax = sns.boxplot(data=gm07, x="life_exp", y="continent")
    sns.despine(offset=8, trim=True)

Contexts: scaling for the audience

  • context= rescales fonts, lines, and markers for where the figure will be shown
  • "paper" < "notebook" (default) < "talk" < "poster"
  • font_scale= fine-tunes on top of the context
sns.set_theme(style="whitegrid", context="talk")
ax = sns.lineplot(data=gm, x="year", y="life_exp", hue="continent", errorbar=None)
sns.move_legend(ax, "upper left", bbox_to_anchor=(1, 1))
sns.set_theme()   # reset to defaults

Color palettes: three kinds

  • Qualitative for unordered categories: "deep" (default), "Set2", "colorblind"
  • Sequential for ordered or numeric values: "viridis", "rocket", "crest", "Blues"
  • Diverging for values around a midpoint: "vlag", "coolwarm", "RdBu"
  • sns.color_palette(name, n) returns a palette; sns.palplot previews it
for name in ["colorblind", "Set2", "crest", "rocket", "vlag"]:
    sns.palplot(sns.color_palette(name, 7))
    plt.title(name, loc="left", fontsize=10)

Using palettes in plots

  • Per plot: palette="name" on any function with hue
  • Globally: sns.set_palette("name") or sns.set_theme(palette="name")
  • Numeric hue uses a continuous colormap; pass a sequential palette
ax = sns.scatterplot(data=gm07, x="gdp_per_cap", y="life_exp", hue="pop_m", palette="rocket_r", hue_norm=(0, 300), size="pop_m", sizes=(10, 400))
ax.set_xscale("log")
sns.move_legend(ax, "upper left", bbox_to_anchor=(1, 1))

Custom palettes with a dictionary

  • Pass palette={category: color} to fix colors per group
  • Guarantees consistent colors across every figure in a report
  • Colors can be names, hex codes, or RGB tuples
cont_colors = {"Africa": "#E69F00", "Americas": "#56B4E9", "Asia": "#009E73", "Europe": "#0072B2", "Oceania": "#CC79A7"}
sns.lineplot(data=gm, x="year", y="gdp_per_cap", hue="continent", palette=cont_colors, errorbar=None)

Fine-tuning with rc parameters

  • set_theme(rc={...}) passes any matplotlib setting through Seaborn
  • Common tweaks: figure size, font family, grid style, spine visibility
  • Discover names with plt.rcParams.keys()
sns.set_theme(style="whitegrid", rc={"figure.figsize": (8, 4), "axes.spines.top": False, "axes.spines.right": False, "grid.linestyle": ":"})
sns.histplot(data=gm07, x="life_exp", hue="continent", multiple="stack", palette=cont_colors, binwidth=5)

Putting it all together

  • Theme and context from Seaborn, data mapping from Seaborn, final polish from matplotlib
  • Every element on the page is intentional: labels with units, consistent colors, a clear title, a source note
sns.set_theme(style="ticks", context="notebook", font_scale=1.05)
fig, ax = plt.subplots(figsize=(10, 6))
sns.scatterplot(data=gm07, x="gdp_per_cap", y="life_exp", hue="continent", size="pop_m", sizes=(30, 1200),
                palette=cont_colors, alpha=0.75, edgecolor="white", linewidth=0.8, ax=ax)
ax.set_xscale("log")
ax.xaxis.set_major_formatter(StrMethodFormatter("${x:,.0f}"))
for name in ["China", "India", "United States", "Japan", "Nigeria"]:
    r = gm07.loc[gm07["country"] == name].iloc[0]
    ax.annotate(name, (r["gdp_per_cap"], r["life_exp"]), xytext=(6, 6), textcoords="offset points", fontsize=9)
ax.set(xlabel="GDP per capita (USD, log scale)", ylabel="Life expectancy (years)")
ax.set_title("Richer countries live longer, but continent still matters (2007)", loc="left", fontweight="bold")
ax.text(0, -0.13, "Source: Gapminder. Bubble area proportional to population.", transform=ax.transAxes, fontsize=8, color="gray")
sns.move_legend(ax, "upper left", bbox_to_anchor=(1.01, 1), frameon=False, fontsize=9, labelspacing=1.4)
sns.despine()

Wrap-up

Cheat sheet

  • Distributions: histplot, kdeplot, ecdfplot → facet with displot
  • Categorical: countplot, barplot, boxplot, violinplot, stripplot → facet with catplot
  • Relational: scatterplot, lineplot → facet with relplot
  • Models and matrices: regplot / lmplot, heatmap, jointplot, pairplot
  • Semantic mappings: hue, size, style, units; facets: col, row, col_wrap
  • Matplotlib access: axes-level returns Axes; figure-level returns a grid with .figure and .axes
  • Styling: set_theme(style, context, palette, font_scale, rc), axes_style, despine, move_legend

Practice exercises

  • Plot the distribution of log GDP per capita in 1952 vs. 2007 on the same axes (hint: filter, then hue="year")
  • Make a relplot of GDP per capita over time for 5 countries of your choice, one panel each, with a log y-axis
  • Recreate the bubble chart for 1952: what changed compared to 2007?
  • Build a catplot of median life expectancy by continent with kind="bar", estimator="median", and your own palette dictionary
  • Choose one figure from today and polish it for a poster: context="poster", clean labels, annotation, and save it as a PDF