Skip to content
svgsmall-multiples

Small multiples

How do many series compare without tangling into spaghetti?

Demo data · seed 20261101 · 288 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Compare shapes across panels, all with the same time axis.
  2. With a shared y scale, compare levels too; with free scales, compare only shapes.
  3. Read the change in each panel's corner.
  1. Callout 1: Panel title and its overall change.
  2. Callout 2: Same scale: this series sits higher than its neighbours.
  3. Callout 3: A flat panel on a shared scale: its own movement may be hidden.

Watch out

  • Free y scales make every series look equally large. Check the axes before you compare levels.

Defaults

Free y scales
Off
Each panel gets its own y range (compare shapes, not levels)
Resample
None (raw)
Combine values into days, weeks or months before plotting, to reduce noise.
Also: Day · ISO week · Month · Quarter
Colour
By panel
How bars or lines are coloured.
Also: Single

Pinned in the code

  • Panels share the x axis; the y scale is shared unless “Free y scales” is on (then compare shapes only).
  • Panel header: group name and the change from the first to the last plotted value.
  • Panels follow the group's level order (declared order, else descending frequency).
  • All calendar arithmetic is in UTC; timestamps are epoch milliseconds.
# Small multiples — Codesplash Chart Lab (recipe "small-multiples")
# controls: free=false, period=none, color=panel
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

try:
    import codesplash as cs  # optional: the app's chart theme
except ImportError:
    cs = None
if cs:
    cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]

df = pd.read_csv("small-multiples-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["month"] = pd.to_datetime(df["month"])
df["product_line"] = pd.Categorical(df["product_line"].astype("string"), categories=["Analytics", "Compute", "Storage", "Security", "Networking", "Support"])

def freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
def period_start(t, period):
    """UTC period start: day, ISO week (Monday), month, quarter or year; "none" keeps the timestamp."""
    if period == "none":
        return t
    day = t.dt.floor("D")
    if period == "day":
        return day
    if period == "week":
        return day - pd.to_timedelta(day.dt.day_of_week, unit="D")
    return t.dt.to_period({"month": "M", "quarter": "Q", "year": "Y"}[period]).dt.start_time

def resample(d, time, value, period, level=0.95):
    """Per period: n, mean, SD (n − 1), min, max and mean ± t(0.975, n − 1)·SD/√n (no band when n = 1)."""
    d = d.dropna(subset=[time, value])
    s = d.groupby(period_start(d[time], period))[value].agg(["count", "mean", "std", "min", "max"])
    s = s.rename(columns={"count": "n"}).rename_axis("t").reset_index()
    half = (stats.t.ppf(1 - (1 - level) / 2, s["n"] - 1) * s["std"] / np.sqrt(s["n"])).fillna(0)
    return s.assign(lo=s["mean"] - half, hi=s["mean"] + half)
def grid_shape(k):
    """The app's panel grid: 1–3 panels in a row, 4 as 2 × 2, up to 6 in 3 columns, else 4 columns."""
    cols = max(1, k) if k <= 3 else 2 if k == 4 else 3 if k <= 6 else 4
    return int(np.ceil(k / cols)), cols

PERIOD = "none"
series = [(lv, df[df["product_line"].astype(str) == lv]) for lv in freq_levels(df["product_line"], 12)]
rows, cols = grid_shape(len(series))
fig, axes = plt.subplots(rows, cols, figsize=(3.2 * cols, 2.2 * rows), sharex=True, sharey=True, squeeze=False)  # shared y scale
for i, (ax, (name, d)) in enumerate(zip(axes.flat, series)):
    s = resample(d, "month", "revenue_k", PERIOD)
    ax.plot(s["t"], s["mean"], color=PALETTE[i % len(PALETTE)], linewidth=1.4)
    change = s["mean"].iloc[-1] - s["mean"].iloc[0]  # first → last plotted value
    ax.set_title(f"{name}  ({change:+.3g})", fontsize=9, loc="left")
    ax.tick_params(labelsize=7)
for ax in list(axes.flat)[len(series):]:
    ax.set_visible(False)
fig.supylabel("revenue_k")
fig.autofmt_xdate()
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads small-multiples-demo.csv · app theme from the optional codesplash helper