Skip to content

Which chart

Start from the question, not from the chart type. This guide maps each kind of question to a chart, gives the call in Matplotlib, Seaborn and Plotly Express, and lists the traps that make a chart lie. The examples use data/customers.csv, data/ab_test.csv and data/sales.csv.

flowchart TD
    Q{"What is the question?"} -->|"shape of one variable"| D{"Fewer than<br/>50 values?"}
    D -->|yes| D1["strip plot"]
    D -->|no| D2["histogram / ECDF"]
    Q -->|"compare groups"| G{"A number or a<br/>distribution per group?"}
    G -->|number| G1["sorted bar,<br/>CI for a rate"]
    G -->|distribution| G2["box / violin /<br/>ECDF per group"]
    Q -->|"two numbers"| R{"More than<br/>5,000 points?"}
    R -->|yes| R1["hexbin / 2-D histogram"]
    R -->|no| R2["scatter + trend line"]
    Q -->|"change over time"| T{"More than<br/>about 5 series?"}
    T -->|yes| T1["small multiples"]
    T -->|no| T2["line chart"]
    Q -->|"parts of a whole"| P["sorted bar of shares,<br/>100% stacked bar"]
    Q -->|"many variables"| M["correlation heatmap,<br/>pairplot of 3–5 columns"]
I want to… Use… Call
show the shape of one numeric column histogram sns.histplot(data=df, x="price")
show a skewed column (money, counts) histogram on a log axis sns.histplot(data=df, x="price", log_scale=True)
show percentiles you can read off ECDF sns.ecdfplot(data=df, x="time_on_page_s")
show a smooth density KDE (check with a histogram) sns.kdeplot(data=df, x="price", cut=0)
show the few values of a small sample strip or swarm plot sns.stripplot(data=df, x="group", y="score")
show distributions of several groups box, violin or ECDF with hue sns.boxplot(data=df, x="plan", y="charges")
show group histograms of different sizes density per group sns.histplot(..., hue="g", stat="density", common_norm=False)
show a number per category sorted horizontal bars ax.barh(s.index, s.values) after s.sort_values()
show a rate per group with uncertainty bars or points with a CI sns.barplot(..., errorbar=("ci", 95), seed=42)
show a change between two moments slope chart or dumbbell ax.plot([0, 1], [before, after]) per item
show two numeric columns scatter plot sns.scatterplot(data=df, x="sqft", y="price", alpha=0.4)
show a trend through a scatter regression or LOWESS line sns.regplot(..., lowess=True)
show thousands of points hexbin or 2-D histogram ax.hexbin(x, y, gridsize=40, mincnt=1)
show a third variable on a scatter color or size sns.scatterplot(..., hue="neighborhood")
show a trend over time line chart sns.lineplot(data=df, x="date", y="visits")
show a noisy daily series raw line + rolling mean s.rolling(7).mean().plot(ax=ax)
show the trend of many groups small multiples sns.relplot(..., kind="line", col="category", col_wrap=3)
show seasonality one line per year, or a month × weekday heatmap sns.lineplot(..., hue="year")
show shares of one whole sorted bars of percentages s.div(s.sum()).sort_values().plot.barh()
show shares across groups 100% stacked bars pd.crosstab(a, b, normalize="index").plot.barh(stacked=True)
show a table of two categories annotated heatmap sns.heatmap(pivot, annot=True, fmt=".0f")
show correlations of many columns heatmap with a diverging map sns.heatmap(corr, vmin=-1, vmax=1, cmap="vlag")
show all pairs of a few columns pair plot sns.pairplot(df[cols].sample(400, random_state=42))
show a model’s errors residuals vs fitted values ax.scatter(pred, y - pred)
show a classifier’s errors confusion matrix ConfusionMatrixDisplay.from_predictions(y, pred)
show an interactive chart with tooltips Plotly Express px.scatter(df, x=..., y=..., hover_name="id")
show a chart for a report Matplotlib or Seaborn, saved as PNG/SVG fig.savefig("output/x.png", dpi=200, bbox_inches="tight")
Question Chart Matplotlib Seaborn Plotly Express Pitfall
how is one variable spread? histogram, ECDF ax.hist(x, bins=30), ax.ecdf(x) histplot, ecdfplot px.histogram, px.ecdf the bin width changes the story; try 2–3
do the groups differ? box, violin, ECDF per group ax.boxplot(groups) boxplot, violinplot, ecdfplot(hue=) px.box, px.violin a box hides two peaks; a violin of 8 points invents a shape
which category is largest? sorted bar ax.barh barplot(estimator="sum") px.bar unsorted bars; an axis that does not start at 0
which group has the highest rate? point or bar + CI ax.errorbar pointplot, barplot(errorbar=) px.bar(error_x=) a bar of a mean with no n or interval
how are two numbers related? scatter ax.scatter(x, y, alpha=0.3) scatterplot, regplot px.scatter(trendline="ols") overplotting; a trend line read as causation
how does it change over time? line ax.plot(dates, y) lineplot px.line bars for hundreds of dates; uneven time gaps drawn as even
how do many series change? small multiples plt.subplots(r, c, sharey=True) relplot(col=) px.line(facet_col=) spaghetti: more than about 5 colored lines on one Axes
what share does each part have? sorted bars, 100% stacked bars ax.barh(..., left=) histplot(multiple="fill") px.bar(barnorm="percent"), px.histogram(barnorm="percent") a pie with many slices; 3-D pies
how do two categories combine? heatmap ax.imshow(m) heatmap(annot=True) px.imshow(text_auto=True) a rainbow colormap
which variables move together? correlation heatmap ax.imshow(corr, vmin=-1, vmax=1) heatmap(corr, mask=) px.imshow(corr, zmin=-1, zmax=1) a sequential map for signed values
where does a model fail? residual plot, confusion matrix ax.scatter(pred, resid) residplot px.scatter residuals against the true values always slope
Library Choose it when Strength Weakness
Matplotlib full control, publication figures, custom layouts every detail is adjustable verbose; you aggregate and label by hand
Seaborn statistical charts from a long DataFrame hue, col, CIs and facets in one call fewer chart types; facets ignore ax=
Plotly Express exploring in a notebook, dashboards, sharing HTML tooltips, zoom, one-call facets large HTML files; static export needs kaleido
pandas .plot a quick look at a Series or a wide frame one line from the data basic styling; it is Matplotlib underneath

Seaborn and pandas draw on Matplotlib Axes, so you can mix them: draw with Seaborn, then fix labels with ax.set(...).

Rule Why How
bars start at 0 bar length encodes the value ax.set_ylim(0, None); lines and dots may zoom
sort categories by value the eye finds the ranking at once order= in Seaborn, sort_values() first
at most about 5 colors more cannot be told apart gray for the rest, highlight one series
same scale across panels panels are compared by eye sharey=True; say so when you free the axis
show the uncertainty of rates small groups look extreme errorbar=("ci", 95) and the n per group
show the data, not only the mean a mean hides skew and outliers strip plot over a box, or an ECDF
log axis for skewed or multiplicative data the bulk of the data is not squeezed into one corner log_scale=True, ax.set_xscale("log")
one message per chart the reader knows what to look at a title that states the finding
label directly a legend forces the eye to jump ax.text at the line ends
color-blind safe palettes about 1 in 12 men has a color-vision deficiency palette="colorblind", viridis, cividis
Data Palette kind Examples
unordered categories qualitative palette="colorblind" (Seaborn), plt.style.use("petroff10") or "tableau-colorblind10" (Matplotlib styles), px.colors.qualitative.Safe; tab10 is not color-blind safe
magnitudes, counts, rates sequential viridis, cividis, rocket, mako
signed values around a midpoint diverging, symmetric limits vlag, RdBu with vmin=-v, vmax=v
anything avoid rainbow maps jet, rainbow add false edges
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
sns.set_theme(style="whitegrid", palette="colorblind")
customers = pd.read_csv("data/customers.csv")
ab = pd.read_csv("data/ab_test.csv")
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])

A rate per group → sorted bars or points with a confidence interval. Aggregate first, so you know the rates and the group sizes:

rates = customers.groupby("contract")["churned"].agg(rate="mean", n="size")
print(rates.sort_values("rate", ascending=False))
Output
rate n
contract
month-to-month 0.296 2784
one-year 0.088 1225
two-year 0.032 991

Chart: sns.barplot(data=customers, x="churned", y="contract", order=rates.sort_values("rate", ascending=False).index, errorbar=("ci", 95), seed=42). The bar is the rate, the line its interval. Write the n per group in the labels when the groups differ in size.

“Did the treatment change time on page?”

Section titled ““Did the treatment change time on page?””

Two distributions → an ECDF per group. Each curve shows the share of users at or below each time. A curve to the right means longer visits, at every percentile:

fig, ax = plt.subplots(figsize=(6, 3.2))
sns.ecdfplot(data=ab, x="time_on_page_s", hue="group", ax=ax)
ax.set(xlabel="time on page (s)", ylabel="share of users", xlim=(0, 400),
title="Treatment users stay longer at every percentile")
print(ab.groupby("group")["time_on_page_s"].median().round(1).to_dict())
plt.show()
Output
{'control': 72.8, 'treatment': 80.8}
Two ECDF curves of time on page: the treatment curve lies a little to the right of the control curve over the whole range, so treatment users stay longer at every percentile.
ECDF per group: compare whole distributions, not only the means.

“How did each category’s revenue move?”

Section titled ““How did each category’s revenue move?””

Six series over 24 months → small multiples with a shared y-axis, not six lines on one Axes:

month = sales["order_date"].dt.to_period("M").dt.to_timestamp()
monthly = (
sales.assign(month=month)
.groupby(["category", "month"], as_index=False)["revenue"].sum()
)
print(monthly.shape, sorted(monthly["category"].unique()))
g = sns.relplot(data=monthly, x="month", y="revenue", col="category", col_wrap=3,
kind="line", height=2.2, aspect=1.5) # one panel per category
g.set_titles("{col_name}")
g.set_axis_labels("", "revenue (k USD)")
for ax in g.axes.flat:
ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=[1, 7])) # Jan and Jul
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %y"))
ax.yaxis.set_major_formatter(lambda v, pos: f"{v / 1000:,.0f}")
plt.show()
Output
(144, 3) ['Beauty', 'Books', 'Clothing', 'Electronics', 'Home', 'Sports']
Six small line charts of monthly revenue on a shared y-axis: Electronics earns far more than the rest and jumps in November and December of both years; the other five categories stay low and nearly flat.
Small multiples: one panel per series, one shared scale.

The shared scale shows the true sizes: Electronics dominates. To compare the shapes of the small series, pass facet_kws={"sharey": False} and say so in the title.

“What share of each region’s lines are online?”

Section titled ““What share of each region’s lines are online?””

Parts of a whole across groups → 100% stacked bars. The table behind the chart:

share = pd.crosstab(sales["region"], sales["channel"], normalize="index")
print(share.round(3))
Output
channel online store
region
East 0.422 0.578
North 0.432 0.568
South 0.413 0.587
West 0.413 0.587

Chart: share.plot.barh(stacked=True). Put the share you discuss (online) next to the axis, where all its bars start at 0.

Section titled ““Is price related to size for 3,000 houses?””

Two numbers → a scatter plot. With 3,000 points, use alpha=0.3 or ax.hexbin. Prices are skewed, so log axes show the bulk: sns.scatterplot(data=houses, x="sqft", y="price", alpha=0.3) then ax.set(xscale="log", yscale="log"). Add a trend with sns.regplot(..., scatter=False), and color by neighborhood only if there are at most about 5.

Trap Symptom Fix
a bar axis that starts above 0 a 2% difference looks like 2× start bars at 0, or use dots
a pie with many slices nobody can rank the slices sorted bars of percentages
two y-axes (twinx) the crossing point depends on the scales you chose two panels with a shared x-axis, or index both to 100
unsorted categories the ranking is hard to see order= or sort_values()
alphabetical months or weekdays Apr, Aug, Dec… order=[...] or a categorical dtype
a mean bar per group no hint of n, spread or outliers add a CI, the n, or the points
a KDE near a hard limit density below 0 or above 100% cut=0, or a histogram
overplotting a solid blob of points alpha, smaller markers, hexbin, a sample
a line through unordered x a scribble sort by x, or use a scatter
a numeric hue such as a year a light-to-dark scale, not distinct colors convert it to str
a rainbow colormap false edges, not color-blind safe viridis, cividis, vlag
a sequential map for correlations −0.8 and 0 look alike a diverging map with vmin=-1, vmax=1
free y-axes on small multiples small panels look as big as large ones sharey=True, or say “independent axes”
a raw count compared across groups of different size the bigger group always wins rates, or stat="density", common_norm=False
a Plotly chart of a million rows a huge, slow HTML file aggregate or sample first
plt.savefig after plt.show() an empty image save before you show