28. Visualization — Cheat sheet
The essentials of module 28 on one page. Every runnable block on this page is checked against its output.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| start a chart | plt.subplots() |
fig, ax = plt.subplots(figsize=(7, 4)) |
| a grid of charts | plt.subplots(rows, cols, ...) |
plt.subplots(2, 2, sharey=True, layout="constrained") |
| an uneven layout | plt.subplot_mosaic |
plt.subplot_mosaic([["a", "a"], ["b", "c"]]) |
| loop over a grid | axs.flat |
for ax in axs.flat: ... |
| title and labels in one call | ax.set(...) |
ax.set(title="...", xlabel="...", ylabel="...") |
| one title or y label for the figure | fig.suptitle, fig.supylabel |
fig.suptitle("Q4 review") |
| start the y-axis at 0 | ax.set_ylim(0, None) |
|
| month names on the x-axis | ax.set_xticks(pos, labels=...) |
ax.set_xticks(range(1, 13), labels=calendar.month_abbr[1:]) |
thousands as k |
FuncFormatter |
FuncFormatter(lambda v, p: f"{v / 1000:,.0f}k") |
| a percent axis | PercentFormatter |
ax.yaxis.set_major_formatter(PercentFormatter(xmax=1)) |
| short date labels | ConciseDateFormatter |
mdates.ConciseDateFormatter(ax.xaxis.get_major_locator()) |
| values on bars | ax.bar_label |
ax.bar_label(bars, fmt="{:.1%}") |
| a reference line | ax.axhline, ax.axvline |
ax.axhline(4.5, linestyle="--") |
| shade a period | ax.axvspan |
ax.axvspan(start, end, alpha=0.1) |
| point at a value | ax.annotate |
ax.annotate("peak", xy=(x, y), xytext=(tx, ty), arrowprops={"arrowstyle": "->"}) |
| a style for the whole script | plt.style.use |
plt.style.use("petroff10") |
| a style for one block | plt.style.context, plt.rc_context |
with plt.rc_context({"font.size": 12}): ... |
| Seaborn’s look everywhere | sns.set_theme |
sns.set_theme(style="whitegrid", palette="colorblind") |
| save a figure | fig.savefig |
fig.savefig("output/x.png", dpi=200, bbox_inches="tight") |
| free memory after saving | plt.close(fig) |
|
| the distribution of a column | sns.histplot, kdeplot, ecdfplot |
sns.histplot(data=df, x="price", log_scale=True) |
| compare groups of different size | stat="density", common_norm=False |
sns.histplot(..., hue="churned", stat="density", common_norm=False) |
| a rate per group with uncertainty | sns.barplot(errorbar=...) |
sns.barplot(data=df, x="contract", y="churned", errorbar=("ci", 95)) |
| distributions side by side | ax.boxplot, sns.violinplot |
sns.violinplot(data=df, x="plan", y="monthly_charges") |
| two numeric columns | sns.scatterplot, sns.regplot |
sns.regplot(data=df, x="sqft", y="price") |
| a value over time per group | sns.lineplot |
sns.lineplot(data=df, x="month", y="revenue", hue="year") |
| a table as colors | sns.heatmap |
sns.heatmap(pivot, annot=True, fmt=".0%") |
| one panel per group | relplot, displot, catplot, lmplot with col= |
sns.relplot(..., col="category", col_wrap=3) |
| all pairs of a few columns | sns.pairplot |
sns.pairplot(df[cols].sample(400, random_state=42)) |
| an interactive chart | plotly.express |
px.line(df, x="date", y="visits", hover_data=["signups"]) |
| save an interactive chart | fig.write_html |
fig.write_html("output/x.html", include_plotlyjs="cdn") |
Matplotlib objects
Section titled “Matplotlib objects”| Object | What it is | Get it with |
|---|---|---|
| Figure | the whole image | fig, ax = plt.subplots(), ax.figure, plt.gcf() |
| Axes | one plot area | ax, axs[r, c], fig.axes, plt.gca() |
| Axis | the x or y axis of an Axes | ax.xaxis, ax.yaxis |
| Artist | anything drawn | ax.lines, ax.patches, ax.texts, ax.collections |
| pyplot | Object-oriented |
|---|---|
plt.plot, plt.bar, plt.hist |
ax.plot, ax.bar, ax.hist |
plt.title, plt.xlabel, plt.ylabel |
ax.set_title, ax.set_xlabel, ax.set_ylabel |
plt.xlim, plt.ylim, plt.xticks |
ax.set_xlim, ax.set_ylim, ax.set_xticks |
plt.legend, plt.grid |
ax.legend, ax.grid |
plt.savefig |
fig.savefig |
import matplotlib.pyplot as plt
fig, axs = plt.subplots(2, 3) # 2-D array of Axesprint(axs.shape, axs[1, 2] is axs.flat[5]) # flat walks row by rowfig, axd = plt.subplot_mosaic([["top", "top"], ["left", "right"]])print(sorted(axd), len(fig.axes)) # a dict of named Axesplt.close("all") # close every open figure(2, 3) True['left', 'right', 'top'] 3Plot methods
Section titled “Plot methods”| Method | Chart | Key options |
|---|---|---|
ax.plot(x, y) |
line | marker="o", linestyle="--", linewidth=2, label="..." |
ax.scatter(x, y) |
points | s=10 (size), alpha=0.3, c=values, cmap="viridis" |
ax.bar(x, h), ax.barh(y, w) |
bars | color=, bottom= (stacking), width=0.4, yerr=, capsize=4 |
ax.hist(v, bins=30) |
histogram | bins= int or edges, density=True, histtype="step" |
ax.boxplot(groups) |
box plot | tick_labels=[...], orientation="horizontal", showfliers=False |
ax.errorbar(x, y, yerr=e) |
points with error bars | fmt="o", capsize=4 |
ax.fill_between(x, lo, hi) |
band | alpha=0.2 |
ax.hexbin(x, y, gridsize=30) |
2-D density | cmap="viridis", mincnt=1 |
ax.imshow(m) |
image or matrix | cmap=, aspect="auto" |
ax.axline((x0, y0), slope=m) |
infinite line | linestyle="--" |
ax.twinx() |
second y-axis | use rarely: two scales mislead |
Labels, ticks and formatters
Section titled “Labels, ticks and formatters”| Task | Code |
|---|---|
| title, labels | ax.set(title="...", xlabel="...", ylabel="...") |
| legend | ax.legend(title="Year", loc="upper left", frameon=False, ncols=2) |
| legend outside | ax.legend(loc="upper left", bbox_to_anchor=(1, 1)) |
| rotate tick labels | ax.tick_params(axis="x", labelrotation=45) |
| log axis | ax.set_yscale("log") |
| fewer ticks | ax.xaxis.set_major_locator(MaxNLocator(5)) |
| hide minor log ticks | ax.minorticks_off() |
| font size for everything | plt.rcParams["font.size"] = 11 |
from matplotlib.ticker import EngFormatter, FuncFormatter, StrMethodFormatter
k = FuncFormatter(lambda value, pos: f"{value / 1000:,.0f}k") # 241098 -> 241kcomma = StrMethodFormatter("{x:,.0f}") # the field is always named xeng = EngFormatter(places=1) # SI prefixes: k, M, Gfor value in [950, 241_098, 1_808_108]: print(f"{k(value, 0):>7} {comma(value, 0):>10} {eng(value, 0):>8}") 1k 950 950.0 241k 241,098 241.1 k 1,808k 1,808,108 1.8 MPercentFormatter(xmax=1, decimals=0) and the date formatters need an axis to format; set them with ax.yaxis.set_major_formatter(...).
Styles and colors
Section titled “Styles and colors”import seaborn as sns
print(len(plt.style.available), "styles, e.g.", plt.style.available[:3])with plt.style.context("petroff10"): # a temporary style print(plt.rcParams["axes.prop_cycle"].by_key()["color"][:3])print(sns.color_palette("colorblind").as_hex()[:3]) # Seaborn's CVD-safe palette28 styles, e.g. ['Solarize_Light2', 'bmh', 'classic']['#3f90da', '#ffa90e', '#bd1f01']['#0173b2', '#de8f05', '#029e73']| Palette or colormap | Kind | Use for |
|---|---|---|
colorblind (Seaborn), petroff10, tableau-colorblind10 (Matplotlib), px.colors.qualitative.Safe (Plotly) |
qualitative | unordered categories |
viridis, cividis, rocket, mako |
sequential | counts, rates, magnitudes |
vlag, RdBu, coolwarm with symmetric vmin=-v, vmax=v |
diverging | correlation, growth, residuals |
jet, rainbow, hsv |
avoid | false edges, not color-blind safe |
"C0"…"C9" |
the current color cycle | one consistent accent color |
"0.7" |
a gray (0 = black, 1 = white) | de-emphasize the rest |
name + "_r" |
reversed map | rocket_r: dark = high |
Useful rcParams:
| Key | Example |
|---|---|
figure.figsize |
(7, 4) |
figure.dpi, savefig.dpi |
100, 200 |
axes.spines.top, axes.spines.right |
False |
axes.grid, grid.alpha |
True, 0.3 |
axes.titleweight |
"bold" |
axes.prop_cycle |
plt.cycler(color=sns.color_palette("colorblind")) |
Annotations and saving
Section titled “Annotations and saving”from pathlib import Path
import numpy as np
months = np.arange(1, 13)revenue = np.array([120, 106, 146, 115, 129, 156, 149, 152, 142, 166, 268, 303])fig, ax = plt.subplots(figsize=(6, 3))ax.plot(months, revenue, marker="o")ax.annotate("peak 303k", xy=(12, 303), xytext=(6, 280), # text with an arrow arrowprops={"arrowstyle": "->", "color": "0.3"})ax.axvspan(10.5, 12.5, color="gray", alpha=0.15) # shaded seasonax.axhline(revenue.mean(), linestyle=":", color="0.4") # reference lineax.set(ylim=(0, 330), title="2024 revenue (k USD)")Path("output").mkdir(exist_ok=True)fig.savefig("output/annotated.png", dpi=200, bbox_inches="tight") # before showprint(Path("output/annotated.png").exists(), round(revenue.mean(), 1))plt.show()True 162.7
savefig option |
Effect |
|---|---|
.png, .svg, .pdf extension |
raster or vector format |
dpi=200 |
pixels per inch for PNG: 7 × 4 in → 1400 × 800 px |
bbox_inches="tight" |
crop to the content; keep labels that stick out |
transparent=True |
no background (for dark slides) |
facecolor="white" |
force a white background |
Seaborn functions
Section titled “Seaborn functions”| Kind | Axes-level (ax=) |
Figure-level (col=, row=) |
Key parameters |
|---|---|---|---|
| distribution | histplot, kdeplot, ecdfplot |
displot(kind="hist"/"kde"/"ecdf") |
bins, stat, common_norm, multiple, log_scale, bw_adjust, element |
| categorical | barplot, pointplot, countplot, violinplot, stripplot, swarmplot, boxenplot, boxplot |
catplot(kind=...) |
order, hue_order, errorbar, seed, split, inner, cut |
| relational | scatterplot, lineplot |
relplot(kind="scatter"/"line") |
hue, size, style, errorbar, estimator, markers |
| regression | regplot, residplot |
lmplot |
order, logistic, lowess, ci, scatter_kws, line_kws |
| matrix | heatmap |
clustermap |
annot, fmt, cmap, center, vmin, vmax, mask, linewidths |
| multi-variable | — | pairplot, jointplot |
vars, hue, corner, kind, diag_kind, height |
| Parameter | Values | Meaning |
|---|---|---|
stat (histplot) |
"count", "density", "percent", "probability" |
what the bar height means |
multiple |
"layer", "stack", "dodge", "fill" |
how hue groups combine; "fill" = 100% stacked |
errorbar |
("ci", 95), "sd", "se", ("pi", 50), None |
interval on bars, points and lines |
estimator |
"mean", "median", "sum" |
what a bar or line point aggregates |
height, aspect |
inches, width ÷ height | size of each facet (figure-level only) |
col_wrap |
int | panels per row with col= |
facet_kws |
{"sharey": False} |
options for the FacetGrid |
import pandas as pd
sns.set_theme(style="whitegrid", palette="colorblind")customers = pd.read_csv("data/customers.csv")g = sns.displot(data=customers, x="tenure_months", col="contract", hue="churned", col_order=["month-to-month", "one-year", "two-year"], stat="density", common_norm=False, element="step", bins=24, height=2.6, aspect=1.2) # figure-level: returns a FacetGridg.set_titles("{col_name}")print(type(g).__name__, g.axes.shape)plt.show()FacetGrid (1, 3)
| FacetGrid method | Does |
|---|---|
g.set_titles("{col_name}") |
short panel titles |
g.set_axis_labels("x", "y") |
labels on the outer panels |
g.figure.suptitle("...", y=1.03) |
one title above the grid |
g.axes.flat |
loop over the panels |
g.map_dataframe(func, x=..., y=...) |
draw any function in each panel |
sns.move_legend(g, "upper left", bbox_to_anchor=(1, 1)) |
move the legend |
g.savefig("output/x.png", dpi=150) |
save the whole grid |
Seaborn 0.13 changes
Section titled “Seaborn 0.13 changes”| Old or warning | Now |
|---|---|
ci=95 |
errorbar=("ci", 95) |
ci=None |
errorbar=None |
palette= without hue= |
hue=<x column>, legend=False, or color="C0" |
scale= in violinplot |
density_norm= |
g.fig |
g.figure |
sns.heatmap(center=0) with Matplotlib 3.11 (hidden PendingDeprecationWarning) |
symmetric vmin=-v, vmax=v |
sns.boxplot with Matplotlib 3.11 warns about vert |
ax.boxplot(..., orientation="vertical") or sns.violinplot(inner="box") |
Plotly Express
Section titled “Plotly Express”| Function | Chart | Typical call |
|---|---|---|
px.line |
line | px.line(df, x="date", y="visits", color="channel", markers=True) |
px.bar |
bars | px.bar(df, x="region", y="revenue", color="channel", barmode="group") |
px.scatter |
points | px.scatter(df, x="sqft", y="price", color="flag", log_y=True, hover_name="house_id") |
px.histogram |
histogram | px.histogram(df, x="price", nbins=50, color="neighborhood") |
px.box, px.violin |
distributions | px.box(df, x="plan", y="monthly_charges") |
px.imshow |
heatmap | px.imshow(corr, text_auto=".2f", color_continuous_scale="RdBu_r", zmin=-1, zmax=1) |
px.density_heatmap |
2-D histogram | for many points |
| Option | Effect |
|---|---|
hover_data=["col"] or {"col": ":.2f", "date": "|%Y-%m-%d"} |
extra columns in the tooltip, with formats |
hover_name="col" |
bold first line of the tooltip |
labels={"col": "Nice name"} |
axis and tooltip names |
facet_col="col", facet_col_wrap=3 |
small multiples |
category_orders={"col": [...]} |
fixed order of categories |
template="plotly_white" |
clean background |
color_discrete_sequence=px.colors.qualitative.Safe |
color-blind-friendly colors |
fig.update_traces(hovertemplate="%{x}: %{y:,.0f}") |
custom tooltip text |
fig.update_layout(hovermode="x unified") |
one tooltip for all series |
fig.add_scatter(x=..., y=..., mode="markers") |
add a series |
fig.write_html(path, include_plotlyjs="cdn") |
small shareable HTML file |
fig.write_image("x.png") |
static image (needs the kaleido package) |
import plotly.express as px
sales = pd.read_csv("data/sales.csv")totals = sales.groupby("category", as_index=False)["revenue"].sum()fig = px.bar(totals, x="category", y="revenue", template="plotly_white")print(type(fig).__name__, len(fig.data), fig.data[0].type) # one trace of type barFigure 1 barChoose a chart
Section titled “Choose a chart”| Question | Chart | Seaborn / Matplotlib | Avoid |
|---|---|---|---|
| shape of one numeric column | histogram, KDE, ECDF | histplot, kdeplot, ecdfplot |
a bar per unique value |
| skewed money or counts | histogram on a log axis | histplot(log_scale=True) |
a linear axis that hides the bulk |
| distributions across groups | box, violin, ECDF per group | ax.boxplot, violinplot, ecdfplot(hue=) |
overlapping count histograms |
| a number per category | sorted bar chart | ax.barh, barplot |
pie charts with many slices |
| a rate per group, honestly | bars or points with CIs | barplot(errorbar=("ci", 95)), pointplot |
bars without uncertainty |
| a trend over time | line chart | ax.plot, lineplot |
bars for 700 days |
| a trend per group | small multiples | relplot(kind="line", col=) |
8 colored lines on one Axes |
| two numeric columns | scatter with a fit | scatterplot, regplot, lmplot |
a line chart of unsorted x |
| many points | hexbin, 2-D histogram, sample | ax.hexbin, histplot(x=, y=) |
a solid blob of dots |
| two categorical dimensions | annotated heatmap | heatmap(pivot, annot=True) |
a 3-D bar chart |
| correlation of many columns | masked correlation heatmap | heatmap(corr, mask=, vmin=-1, vmax=1) |
a sequential colormap |
| parts of a whole over time | 100% stacked bars | pd.crosstab(..., normalize="index").plot.bar(stacked=True), ax.bar(..., bottom=), px.histogram(..., barnorm="percent") |
several pie charts |
| explore details in a browser | interactive chart | px.line, px.scatter |
a static PNG of 50,000 points |
Gotchas
Section titled “Gotchas”ax.title("...")raisesTypeError: 'Text' object is not callable. Useax.set_title.plt.subplots(1, 3)returns a 1-D array:axs[0, 1]raisesIndexError.plt.subplots()returns one Axes, not an array.plt.savefigafterplt.show()can save an empty image. Save first.- Every
plt.subplotscall keeps a figure in memory untilplt.close(fig). In loops, close each one. plt.style.useandsns.set_themechange global state for the rest of the program. Useplt.style.contextfor one chart.- Some Seaborn themes draw annotation arrows white. Pass a color:
arrowprops={"arrowstyle": "->", "color": "0.3"}. - A numeric
hue(such as a year) gets a light-to-dark scale. Convert it to text for distinct colors. - Seaborn keeps text categories in the order they first appear in the data and sorts numeric ones. Neither is the order you want for weekdays, months or ranked bars: pass
order=. - Figure-level functions (
relplot,displot,catplot,lmplot,pairplot) ignore your Axes. Size them withheight=andaspect=. sns.pairploton many columns and thousands of rows is slow and unreadable. Pick 3–5 columns and sample a few hundred rows.- A bar chart must start at zero. A line chart may zoom, but say so on the axis.
- A KDE can show density where no data can exist (below 0). Check with a histogram.
PercentFormatter()assumes 100 = 100%. For rates from 0 to 1, usePercentFormatter(xmax=1).- A Plotly HTML file contains all its data. Aggregate before you plot a million rows.
fig.show()in Plotly opens a browser tab; it does not save. Usefig.write_html.