svgbrushablestrip
Strip plot with mean ± CI
What do all the observations look like per group, next to the group mean and its uncertainty?
How to read it
- Look at the dots first: each one is an observation, spread sideways only so they don't overlap.
- Read the bar beside them: the group mean with its interval.
- Compare intervals with the spread of the dots: a narrow interval is about the mean, not about individual values.
- Callout 1: Each dot is one observation.
- Callout 2: The bar: mean and its interval.
- Callout 3: A wide spread in one group: does the mean describe it well?
Watch out
- Check which interval is shown: a standard deviation, a standard error and a confidence interval have very different widths.
Defaults
- Interval
- 95% CI (t)
- What the interval shows: a confidence interval, a standard error or a standard deviation.
- Also: ± 1 SE · ± 1 SD · None
- Jitter width
- 0.5
- How far points spread sideways, so they don't overlap; the spread has no meaning.
- Range 0 to 1, step 0.1
- Point radius
- 2.5
- The size of each point.
- Range 1 to 5, step 0.5
Pinned in the code
- Interval: x̄ ± t(0.975, n−1)·s/√n (s with n − 1); SE = s/√n; SD = s. Say which one in captions — they are not interchangeable.
- Jitter is deterministic (seeded per group) and only horizontal; values are never moved.
# Strip plot with mean ± CI — Codesplash Chart Lab (recipe "strip")
# controls: interval=ci, jitter=0.5, size=2.5
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("strip-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["fertilizer"] = pd.Categorical(df["fertilizer"].astype("string"), categories=["None", "Nitrogen", "Phosphate", "Both"])
def groups(frame, value, group=None, max_levels=12):
"""(label, values) per group in level order; rows missing the value or the group are dropped."""
if group is None:
return [(value, frame[value].dropna().to_numpy(dtype=float))]
d = frame[[value, group]].dropna()
out = []
for level in list(d[group].cat.categories)[:max_levels]:
v = d.loc[d[group] == level, value].to_numpy(dtype=float)
if v.size:
out.append((str(level), v))
return out
parts = groups(df, "yield_t_ha", "fertilizer", max_levels=12)
rng = np.random.default_rng(23) # horizontal jitter only (cosmetic); values are never moved
fig, ax = plt.subplots(figsize=(7, 4))
for i, (label, v) in enumerate(parts):
ax.scatter(i + rng.uniform(-0.5 / 2, 0.5 / 2, v.size), v, s=(2 * 2.5) ** 2, color=PALETTE[i % len(PALETTE)], alpha=0.55, linewidths=0)
n, m, s = v.size, v.mean(), v.std(ddof=1)
if n > 1:
half = stats.t.ppf(0.975, n - 1) * s / np.sqrt(n) # 95% CI: t(0.975, n − 1) · s/√n
ax.errorbar(i, m, yerr=half, fmt="o", color=plt.rcParams["text.color"], capsize=4, markersize=5, zorder=3)
ax.set_xticks(range(len(parts)), [label for label, _ in parts])
ax.set_xlabel("fertilizer")
ax.set_ylabel("yield_t_ha")
ax.set_title("mean ± 95% CI (t)", loc="left", fontsize=9)
plt.show()Needs pandas, numpy, matplotlib, scipy · reads strip-demo.csv · app theme from the optional codesplash helper
# Strip plot with mean ± CI — Codesplash Chart Lab (recipe "strip")
# controls: interval=ci, jitter=0.5, size=2.5
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
df = pd.read_csv("strip-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["fertilizer"] = pd.Categorical(df["fertilizer"].astype("string"), categories=["None", "Nitrogen", "Phosphate", "Both"])
def groups(frame, value, group=None, max_levels=12):
"""(label, values) per group in level order; rows missing the value or the group are dropped."""
if group is None:
return [(value, frame[value].dropna().to_numpy(dtype=float))]
d = frame[[value, group]].dropna()
out = []
for level in list(d[group].cat.categories)[:max_levels]:
v = d.loc[d[group] == level, value].to_numpy(dtype=float)
if v.size:
out.append((str(level), v))
return out
INK = cs.palette(dark=False)["foreground"] if cs else "#131922"
parts = groups(df, "yield_t_ha", "fertilizer", max_levels=12)
rng = np.random.default_rng(23) # horizontal jitter only (cosmetic); values are never moved
fig = go.Figure()
for i, (label, v) in enumerate(parts):
fig.add_scatter(x=i + rng.uniform(-0.5 / 2, 0.5 / 2, v.size), y=v, mode="markers", marker=dict(color=PALETTE[i % len(PALETTE)], size=2 * 2.5, opacity=0.55), name=label, showlegend=False)
n, m, s = v.size, v.mean(), v.std(ddof=1)
if n > 1:
half = stats.t.ppf(0.975, n - 1) * s / np.sqrt(n) # 95% CI: t(0.975, n − 1) · s/√n
fig.add_scatter(x=[i], y=[m], mode="markers", marker=dict(color=INK, size=8), error_y=dict(type="data", array=[half], color=INK, width=6), showlegend=False)
fig.update_layout(xaxis=dict(tickvals=list(range(len(parts))), ticktext=[label for label, _ in parts], title="fertilizer"), yaxis_title="yield_t_ha", title="mean ± 95% CI (t)")
fig.show()Needs pandas, numpy, plotly, scipy · reads strip-demo.csv · app theme from the optional codesplash helper
# Strip plot with mean ± CI — Codesplash Chart Lab (recipe "strip")
# controls: interval=ci, jitter=0.5, size=2.5
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("strip-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["fertilizer"]] <- factor(df[["fertilizer"]], levels = c("None", "Nitrogen", "Phosphate", "Both"))
groups_of <- function(df, value, group = NULL, max_levels = 12) {
# values per group in level order; rows missing the value or the group are dropped
v <- df[[value]]
if (is.null(group)) return(stats::setNames(list(v[is.finite(v)]), value))
g <- df[[group]]
keep <- is.finite(v) & !is.na(g)
out <- split(v[keep], factor(g[keep], levels = utils::head(levels(g), max_levels)))
out[lengths(out) > 0]
}
ink <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$foreground else "#131922"
parts <- groups_of(df, "yield_t_ha", "fertilizer", max_levels = 12)
pts <- data.frame(group = factor(rep(names(parts), lengths(parts)), levels = names(parts)), value = unlist(parts, use.names = FALSE))
summ <- do.call(rbind, lapply(names(parts), function(k) {
v <- parts[[k]]; n <- length(v); s <- sd(v)
half <- qt(0.975, n - 1) * s / sqrt(n) # 95% CI: t(0.975, n − 1) · s/√n
data.frame(group = k, mean = mean(v), lo = mean(v) - if (n > 1) half else 0, hi = mean(v) + if (n > 1) half else 0)
}))
summ$group <- factor(summ$group, levels = names(parts))
p <- ggplot(pts, aes(group, value)) +
geom_point(aes(colour = group), position = position_jitter(width = 0.5 / 2, height = 0, seed = 23), size = 2.5 * 0.6, alpha = 0.55, show.legend = FALSE) +
scale_colour_manual(values = rep(cs_cat, length.out = length(parts)))
p <- p + geom_errorbar(data = summ, aes(x = group, ymin = lo, ymax = hi), inherit.aes = FALSE, width = 0.15, colour = ink) +
geom_point(data = summ, aes(x = group, y = mean), inherit.aes = FALSE, size = 2.4, colour = ink)
p <- p + labs(x = "fertilizer", y = "yield_t_ha", subtitle = "mean ± 95% CI (t)") + theme_cs
print(p)Needs ggplot2 · reads strip-demo.csv · app theme from the optional codesplashr helper
-- Strip plot with mean ± CI — Codesplash Chart Lab (recipe "strip")
-- controls: interval=ci, jitter=0.5, size=2.5
-- per-group mean, SD (n − 1) and SE; the 95% CI half-width is qt(0.975, n − 1) · se
-- (DuckDB has no t quantile function — multiply in Python/R, or use 1.96 for large n)
WITH v0 AS (
SELECT "fertilizer"::VARCHAR AS grp, "yield_t_ha"::DOUBLE AS x
FROM read_csv('strip-demo.csv')
WHERE "yield_t_ha" IS NOT NULL AND isfinite("yield_t_ha"::DOUBLE) AND "fertilizer" IS NOT NULL
),
lv AS ( -- level order as stored in the data dictionary; at most 12 groups
SELECT grp, row_number() OVER (ORDER BY list_position(['None', 'Nitrogen', 'Phosphate', 'Both'], grp)) AS rk
FROM (SELECT grp, count(*) AS n FROM v0 GROUP BY grp)
),
v AS (SELECT v0.grp, v0.x, lv.rk FROM v0 JOIN lv USING (grp) WHERE lv.rk <= 12)
SELECT grp AS "group", count(*) AS n, avg(x) AS mean, stddev_samp(x) AS sd, stddev_samp(x) / sqrt(count(*)) AS se
FROM v
GROUP BY grp, rk
ORDER BY rk;Needs duckdb · reads strip-demo.csv
- Jitter comes from a seeded generator in each language, so dot positions differ from the app; values, means and intervals are identical.