svgsmall-multiples
Small multiples
How do many series compare without tangling into spaghetti?
How to read it
- Compare shapes across panels, all with the same time axis.
- With a shared y scale, compare levels too; with free scales, compare only shapes.
- Read the change in each panel's corner.
- Callout 1: Panel title and its overall change.
- Callout 2: Same scale: this series sits higher than its neighbours.
- 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
# Small multiples — Codesplash Chart Lab (recipe "small-multiples")
# controls: free=false, period=none, color=panel
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from scipy import stats
from plotly.subplots import make_subplots
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 px.colors.qualitative.Plotly
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)]
frames = [(name, resample(d, "month", "revenue_k", PERIOD)) for name, d in series]
rows, cols = grid_shape(len(frames))
titles = [f"{name} ({s['mean'].iloc[-1] - s['mean'].iloc[0]:+.3g})" for name, s in frames]
fig = make_subplots(rows=rows, cols=cols, shared_xaxes=True, shared_yaxes="all", subplot_titles=titles, vertical_spacing=0.12)
for i, (name, s) in enumerate(frames):
fig.add_scatter(x=s["t"], y=s["mean"], mode="lines", name=name, line_color=PALETTE[i % len(PALETTE)], showlegend=False, row=i // cols + 1, col=i % cols + 1)
fig.update_layout(height=220 * rows, title_text="revenue_k by product_line")
fig.show()Needs pandas, numpy, plotly, scipy · reads small-multiples-demo.csv · app theme from the optional codesplash helper
# Small multiples — Codesplash Chart Lab (recipe "small-multiples")
# controls: free=false, period=none, color=panel
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("small-multiples-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["month"]] <- as.POSIXct(df[["month"]], tz = "UTC")
df[["product_line"]] <- factor(df[["product_line"]], levels = c("Analytics", "Compute", "Storage", "Security", "Networking", "Support"))
freq_levels <- function(v, k = 8) {
# declared level order for factors with stored levels, else descending count (ties A→Z)
if (is.factor(v) && !is.null(attr(v, "cs_declared"))) return(utils::head(levels(v), k))
v <- as.character(v[!is.na(v)])
tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
attr(df[["product_line"]], "cs_declared") <- TRUE # stored level order
period_start <- function(t, period) {
# UTC period start: day, ISO week (Monday), month, quarter or year; "none" keeps the timestamp
t <- as.POSIXct(t, tz = "UTC")
if (period == "none") return(t)
lt <- as.POSIXlt(t, tz = "UTC")
day <- as.POSIXct(format(t, "%Y-%m-%d", tz = "UTC"), tz = "UTC")
switch(period,
day = day,
week = day - ((lt$wday + 6) %% 7) * 86400,
month = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon + 1), tz = "UTC"),
quarter = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon - lt$mon %% 3 + 1), tz = "UTC"),
year = as.POSIXct(sprintf("%d-01-01", lt$year + 1900), tz = "UTC"))
}
resample_stats <- function(t, v, 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)
ok <- !is.na(t) & is.finite(v)
k <- as.numeric(period_start(t[ok], period))
out <- do.call(rbind, lapply(split(v[ok], k), function(s) {
n <- length(s); sdv <- if (n > 1) stats::sd(s) else 0
half <- if (n > 1) stats::qt(1 - (1 - level) / 2, n - 1) * sdv / sqrt(n) else 0
data.frame(n = n, mean = mean(s), sd = sdv, min = min(s), max = max(s), lo = mean(s) - half, hi = mean(s) + half)
}))
out$t <- as.POSIXct(as.numeric(names(split(v[ok], k))), origin = "1970-01-01", tz = "UTC")
out[order(out$t), , drop = FALSE]
}
period <- "none"
series <- lapply(stats::setNames(nm = freq_levels(df[["product_line"]], 12)), function(lv) df[as.character(df[["product_line"]]) %in% lv, , drop = FALSE])
panels <- do.call(rbind, lapply(names(series), function(nm) cbind(panel = nm, resample_stats(series[[nm]][["month"]], series[[nm]][["revenue_k"]], period))))
change <- tapply(panels$mean, panels$panel, function(v) utils::tail(v, 1) - v[1]) # first → last plotted value
labels <- stats::setNames(sprintf("%s (%+.3g)", names(series), change[names(series)]), names(series))
panels$panel <- factor(panels$panel, levels = names(series), labels = labels[names(series)])
k <- length(series)
cols <- if (k <= 3) max(1, k) else if (k == 4) 2 else if (k <= 6) 3 else 4 # the app's panel grid
p <- ggplot(panels, aes(t, mean, colour = panel)) +
geom_line(linewidth = 0.6, show.legend = FALSE) +
scale_colour_manual(values = rep(cs_cat, length.out = k)) +
facet_wrap(~panel, ncol = cols, scales = "fixed") + # shared y scale
labs(x = NULL, y = "revenue_k", title = "revenue_k by product_line") +
theme_cs
print(p)Needs ggplot2 · reads small-multiples-demo.csv · app theme from the optional codesplashr helper
-- Small multiples — Codesplash Chart Lab (recipe "small-multiples")
-- controls: free=false, period=none, color=panel
-- per panel: the plotted (period-mean) series, with the first → last change for the header
WITH s AS (
SELECT "product_line" AS panel, "month" AS t, avg("revenue_k") AS mean
FROM read_csv('small-multiples-demo.csv')
WHERE "month" IS NOT NULL AND "revenue_k" IS NOT NULL AND "product_line" IS NOT NULL
GROUP BY ALL
)
SELECT panel, t, mean,
last_value(mean) OVER w - first_value(mean) OVER w AS change
FROM s
WINDOW w AS (PARTITION BY panel ORDER BY t ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
ORDER BY panel, t;Needs duckdb · reads small-multiples-demo.csv