svgcaterpillar
Caterpillar plot
How much do groups differ in a mixed model, and which deviate clearly from the average?
How to read it
- Read each row as one group's estimated deviation from average.
- Rows are sorted by size.
- Intervals that stay away from zero mark groups that differ from average.
- Callout 1: A group above average.
- Callout 2: A group below average.
- Callout 3: Reference: the average group.
Watch out
- These are shrunken estimates: small groups get pulled towards the average.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
- Groups are sorted by estimate within each term (largest at the top); with many groups, labels are hidden and marks shrink. Intervals are the engine's conditional (posterior) intervals.
# Caterpillar plot — Codesplash Chart Lab (recipe "caterpillar")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
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("caterpillar-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["term"] = pd.Categorical(df["term"].astype("string"), categories=["(Intercept)", "Days"])
def levels_of(s):
"""Declared level order (categoricals), else order of first appearance."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [v for v in s.cat.categories if (s == v).any()]
return list(dict.fromkeys(s.dropna().astype(str)))
G = "subject"
E = "random effect (ms)"
LO = "ci_low"
HI = "ci_high"
TERM = "term"
terms = levels_of(df[TERM]) if TERM else [None]
fig, axes = plt.subplots(1, len(terms), figsize=(4 * len(terms) + 1, 5), squeeze=False)
for ax, term in zip(axes[0], terms):
d = (df if term is None else df[df[TERM].astype(str) == str(term)]).sort_values(E)
y = np.arange(len(d))
out = (d[LO] > 0) | (d[HI] < 0) if LO and HI else pd.Series(False, index=d.index)
col = np.where(out, PALETTE[0], "grey")
if LO and HI: ax.hlines(y, d[LO], d[HI], colors=col)
ax.scatter(d[E], y, c=col, s=14, zorder=3)
ax.axvline(0, color="grey", linewidth=0.8)
ax.set_yticks(y, d[G].astype(str), fontsize=7)
ax.set_title(str(term) if term is not None else "", fontsize=10, loc="left")
ax.set_xlabel(E)
plt.show()Needs pandas, numpy, matplotlib · reads caterpillar-demo.csv · app theme from the optional codesplash helper
# Caterpillar plot — Codesplash Chart Lab (recipe "caterpillar")
# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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("caterpillar-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["term"] = pd.Categorical(df["term"].astype("string"), categories=["(Intercept)", "Days"])
G = "subject"
E = "random effect (ms)"
LO = "ci_low"
HI = "ci_high"
TERM = "term"
d = df.dropna(subset=[G, E]).sort_values(E)
kw = dict(error_x=d[HI] - d[E], error_x_minus=d[E] - d[LO]) if LO and HI else {}
fig = px.scatter(d, x=E, y=G, facet_col=TERM, color_discrete_sequence=PALETTE, **kw)
fig.update_yaxes(matches=None, showticklabels=True)
fig.add_vline(x=0, line=dict(color="grey", width=1))
fig.show()Needs pandas, numpy, plotly · reads caterpillar-demo.csv · app theme from the optional codesplash helper
# Caterpillar plot — Codesplash Chart Lab (recipe "caterpillar")
# controls: defaults
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("caterpillar-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["subject"]] <- factor(df[["subject"]])
df[["term"]] <- factor(df[["term"]], levels = c("(Intercept)", "Days"))
g_col <- "subject"
e_col <- "random effect (ms)"
lo_col <- "ci_low"
hi_col <- "ci_high"
term_col <- "term"
d <- data.frame(g = as.character(df[[g_col]]), e = df[[e_col]], term = if (is.null(term_col)) "" else as.character(df[[term_col]]),
lo = if (is.null(lo_col)) NA_real_ else df[[lo_col]], hi = if (is.null(hi_col)) NA_real_ else df[[hi_col]])
d$out <- !is.na(d$lo) & (d$lo > 0 | d$hi < 0)
d$key <- paste(d$term, d$g, sep = "\r")
d$key <- factor(d$key, levels = d$key[order(d$term, d$e)])
p <- ggplot(d, aes(e, key, colour = out)) + geom_vline(xintercept = 0, colour = "grey50") +
geom_errorbar(aes(xmin = lo, xmax = hi), orientation = "y", width = 0, na.rm = TRUE) + geom_point(size = 1.6) +
facet_wrap(~term, scales = "free_y") + scale_y_discrete(labels = function(k) sub(".*\r", "", k)) +
scale_colour_manual(values = c("FALSE" = "grey55", "TRUE" = cs_cat[1]), guide = "none") + labs(x = e_col, y = NULL) + theme_cs
print(p)Needs ggplot2 · reads caterpillar-demo.csv · app theme from the optional codesplashr helper