svgestimation-plot
Estimation plot (Gardner–Altman)
How big is the difference between two groups, and how precisely is it estimated?
How to read it
- Read the left of the chart: every observation by group, with the group means.
- Read the floating axis at the right: the difference between groups.
- Read its interval: how large the difference could plausibly be.
- Callout 1: The observations and mean of the first group.
- Callout 2: The mean difference with its interval.
- Callout 3: The floating axis, anchored at the first group's mean.
Watch out
- If the interval crosses zero, the data are compatible with no difference, but also with others in the interval.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Points are jittered deterministically by row; group lines are the means; the right axis is the left axis shifted so 0 sits at the first group's mean.
- The difference and its interval come from the engine (Welch t, bootstrap or another estimator); without them the plain mean difference is shown with no interval.
- Estimation first: read the size and the interval, not only whether it excludes 0.
# Estimation plot (Gardner–Altman) — Codesplash Chart Lab (recipe "estimation-plot")
# 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("estimation-plot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["supplement"] = pd.Categorical(df["supplement"].astype("string"), categories=["VC", "OJ"])
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
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)))
def first(col):
"""The first finite value of a column the engine repeats on every row (None if absent)."""
if col is None:
return None
v = pd.to_numeric(df[col], errors="coerce").dropna()
return float(v.iloc[0]) if len(v) else None
V = "length"
G = "supplement"
E = "difference"
EL = "diff low"
EH = "diff high"
d = df.dropna(subset=[V, G])
g1, g2 = levels_of(d[G])[:2]
a, b = d.loc[d[G].astype(str) == str(g1), V], d.loc[d[G].astype(str) == str(g2), V]
m1, m2 = a.mean(), b.mean()
eff = first(E) if first(E) is not None else m2 - m1
lo, hi = first(EL), first(EH)
rng = np.random.default_rng(1)
fig, (ax, axd) = plt.subplots(1, 2, figsize=(8, 4.5), sharey=True, gridspec_kw={"width_ratios": [2, 1]})
for i, (s, m) in enumerate([(a, m1), (b, m2)]):
ax.scatter(i + rng.uniform(-0.15, 0.15, len(s)), s, s=14, alpha=0.6, color=PALETTE[i])
ax.hlines(m, i - 0.3, i + 0.3, color=plt.rcParams["text.color"], linewidth=2)
ax.set_xticks([0, 1], [str(g1), str(g2)])
ax.set_ylabel(V)
# Floating difference axis: 0 sits at the first group's mean (Gardner & Altman 1986).
axd.axhline(m1, color=REF, linestyle=":", linewidth=1)
axd.errorbar(0, m1 + eff, yerr=[[eff - lo], [hi - eff]] if lo is not None and hi is not None else None, fmt="o", color=PALETTE[1], capsize=4, markersize=8)
axd.set_xticks([0], [f"{g2} − {g1}"])
axd.set_xlim(-0.6, 0.6)
sec = axd.secondary_yaxis("right", functions=(lambda v: v - m1, lambda v: v + m1))
sec.set_ylabel("difference")
plt.show()Needs pandas, numpy, matplotlib · reads estimation-plot-demo.csv · app theme from the optional codesplash helper
# Estimation plot (Gardner–Altman) — Codesplash Chart Lab (recipe "estimation-plot")
# 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("estimation-plot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["supplement"] = pd.Categorical(df["supplement"].astype("string"), categories=["VC", "OJ"])
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
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)))
def first(col):
"""The first finite value of a column the engine repeats on every row (None if absent)."""
if col is None:
return None
v = pd.to_numeric(df[col], errors="coerce").dropna()
return float(v.iloc[0]) if len(v) else None
V = "length"
G = "supplement"
E = "difference"
EL = "diff low"
EH = "diff high"
d = df.dropna(subset=[V, G])
g1, g2 = levels_of(d[G])[:2]
a, b = d.loc[d[G].astype(str) == str(g1), V], d.loc[d[G].astype(str) == str(g2), V]
m1, m2 = a.mean(), b.mean()
eff = first(E) if first(E) is not None else m2 - m1
lo, hi = first(EL), first(EH)
fig = go.Figure()
for i, (s, m, g) in enumerate([(a, m1, g1), (b, m2, g2)]):
fig.add_box(y=s, x=[str(g)] * len(s), boxpoints="all", jitter=0.4, pointpos=0, fillcolor="rgba(0,0,0,0)", line_color="rgba(0,0,0,0)", marker=dict(color=PALETTE[i], size=5, opacity=0.6), showlegend=False)
fig.add_scatter(x=[str(g)], y=[m], mode="markers", marker=dict(symbol="line-ew-open", size=40, color=REF), showlegend=False)
diff_label = f"{g2} − {g1}"
err = dict(type="data", symmetric=False, array=[hi - eff], arrayminus=[eff - lo]) if lo is not None and hi is not None else None
fig.add_scatter(x=[diff_label], y=[m1 + eff], error_y=err, mode="markers", marker=dict(size=11, color=PALETTE[1]), name="mean difference (anchored at the first mean)")
fig.add_hline(y=m1, line_dash="dot", line_color=REF)
fig.update_layout(yaxis_title=V, title="difference shown on the value axis, anchored at the first group's mean")
fig.show()Needs pandas, numpy, plotly · reads estimation-plot-demo.csv · app theme from the optional codesplash helper
# Estimation plot (Gardner–Altman) — Codesplash Chart Lab (recipe "estimation-plot")
# 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("estimation-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["supplement"]] <- factor(df[["supplement"]], levels = c("VC", "OJ"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
first_num <- function(col) { if (is.null(col)) return(NA_real_); v <- suppressWarnings(as.numeric(df[[col]])); v <- v[is.finite(v)]; if (length(v)) v[1] else NA_real_ }
v_col <- "length"
g_col <- "supplement"
e_col <- "difference"
el_col <- "diff low"
eh_col <- "diff high"
d <- df[!is.na(df[[v_col]]) & !is.na(df[[g_col]]), ]
lv <- levels_of(d[[g_col]])[1:2]
d <- data.frame(y = d[[v_col]], g = factor(as.character(d[[g_col]]), levels = c(lv, "difference")))
d <- d[!is.na(d$g), ]
m <- tapply(d$y, d$g, mean)[lv]
eff <- first_num(e_col); if (is.na(eff)) eff <- unname(m[2] - m[1])
lo <- first_num(el_col); hi <- first_num(eh_col)
means <- data.frame(g = factor(lv, levels = levels(d$g)), m = unname(m))
est <- data.frame(g = factor("difference", levels = levels(d$g)), y = m[1] + eff, lo = m[1] + lo, hi = m[1] + hi)
p <- ggplot(d, aes(g, y)) + geom_point(aes(colour = g), position = position_jitter(width = 0.12, height = 0, seed = 1), alpha = 0.6, show.legend = FALSE) +
geom_crossbar(data = means, aes(g, m, ymin = m, ymax = m), width = 0.5, inherit.aes = FALSE) +
geom_hline(yintercept = m[1], linetype = "dotted", colour = ref_col) +
geom_pointrange(data = est, aes(g, y, ymin = lo, ymax = hi), colour = cs_cat[2], inherit.aes = FALSE) +
scale_x_discrete(drop = FALSE, labels = c(lv, paste(lv[2], "-", lv[1]))) +
scale_colour_manual(values = cs_cat) +
scale_y_continuous(sec.axis = sec_axis(~ . - m[1], name = "difference")) + # 0 at the first group's mean
labs(x = NULL, y = v_col) + theme_cs
print(p)Needs ggplot2 · reads estimation-plot-demo.csv · app theme from the optional codesplashr helper