svgbrushablebox-violin
Box & violin
How does a numeric variable differ across groups?
How to read it
- Compare the medians first: the line inside each box.
- Compare the box heights: each box holds the middle half of its group, so a taller box means more spread.
- Check the points beyond the whiskers, then the violin outline for a shape the box cannot show, such as two humps.
- Callout 1: Line in the box: the median. Dot: the mean.
- Callout 2: Beyond the whiskers: values flagged as unusual, not errors.
- Callout 3: Violin width: how many values sit at that level.
Watch out
- A box plot hides two-humped data. Turn on the violin or look at the raw points.
- Violins are smoothed, so they can suggest values beyond the data's range, especially in small groups.
Defaults
- Violin (KDE)
- On
- Add a smoothed outline of each group's shape.
- Notches (median CI)
- Off
- Add notches around each median. Notches that don't overlap suggest different medians.
- Mean marker
- On
- Mark the mean as well as the median. A gap between them signals skew.
- Whisker × IQR
- 1.5
- How far whiskers reach, in multiples of the box's height; 1.5 is Tukey's rule.
- Range 0.5 to 3, step 0.5
Pinned in the code
- Quartiles are type 7 (R default; not base `boxplot.stats` hinges).
- Whiskers reach the most extreme points within k × IQR of the box (k = 1.5); points beyond are drawn as outliers.
- Notches: median ± 1.58·IQR/√n (McGill, Tukey & Larsen 1978).
- Violins: Gaussian KDE with bw.nrd0, truncated to the data range, scaled to the widest group.
# Box & violin — Codesplash Chart Lab (recipe "box-violin")
# controls: violin=true, notch=false, mean=true, whisker=1.5
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import cbook
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("box-violin-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["arm"] = pd.Categorical(df["arm"].astype("string"), categories=["Control", "Treatment A", "Treatment B"])
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
def bandwidth(v, rule="nrd0"):
"""R bw.nrd0 / bw.nrd, or scipy's Scott rule — as the app computes it."""
v = np.asarray(v, dtype=float)
n, sd = v.size, v.std(ddof=1)
iqr = np.subtract(*np.percentile(v, [75, 25]))
if rule == "scott":
return sd * n ** (-1 / 5)
lo = min(sd, iqr / 1.34) or sd or abs(v[0]) or 1.0
return (0.9 if rule == "nrd0" else 1.06) * lo * n ** (-1 / 5)
def kde(v, h, grid):
"""Gaussian kernel density by direct summation on `grid` (the app's method)."""
v = np.asarray(v, dtype=float)
grid = np.asarray(grid, dtype=float)
out = np.empty(grid.size)
for i in range(0, grid.size, 32): # chunks keep memory small for large samples
z = (grid[i:i + 32, None] - v[None, :]) / h
out[i:i + 32] = np.exp(-0.5 * z * z).sum(axis=1)
return out / (v.size * h * np.sqrt(2 * np.pi))
parts = groups(df, "outcome", "arm", max_levels=12)
stats = []
for label, v in parts:
s = cbook.boxplot_stats(v, whis=1.5, labels=[label])[0] # type-7 quartiles; whiskers within 1.5 × IQR
half = 1.58 * s["iqr"] / np.sqrt(v.size) # notch: McGill et al. 1.58·IQR/√n (matplotlib's default is 1.57)
s.update(cilo=s["med"] - half, cihi=s["med"] + half)
stats.append(s)
fig, ax = plt.subplots(figsize=(7, 4))
pos = np.arange(len(parts))
# violins: Gaussian KDE with bw.nrd0 per group, truncated to the data range, one density scale
curves = []
for label, v in parts:
grid = np.linspace(v.min(), v.max(), 64)
curves.append((grid, kde(v, bandwidth(v, "nrd0"), grid) if v.size > 1 else np.zeros(64)))
top = max(d.max() for _, d in curves) or 1.0
for i, (grid, d) in enumerate(curves):
half = 0.42 * d / top
ax.fill_betweenx(grid, i - half, i + half, color=PALETTE[i % len(PALETTE)], alpha=0.25, linewidth=0)
ax.bxp(stats, positions=pos, widths=0.18, shownotches=False, showmeans=True, patch_artist=True,
boxprops=dict(facecolor=plt.rcParams["axes.facecolor"], edgecolor=plt.rcParams["text.color"]),
medianprops=dict(color=plt.rcParams["text.color"], linewidth=1.5),
meanprops=dict(marker="D", markerfacecolor=PALETTE[1], markeredgecolor="white"),
flierprops=dict(marker="o", markerfacecolor="none", markeredgecolor=PALETTE[0]))
ax.set_xticks(pos, [label for label, _ in parts])
ax.set_xlabel("arm")
ax.set_ylabel("outcome")
plt.show()Needs pandas, numpy, matplotlib · reads box-violin-demo.csv · app theme from the optional codesplash helper
# Box & violin — Codesplash Chart Lab (recipe "box-violin")
# controls: violin=true, notch=false, mean=true, whisker=1.5
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("box-violin-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["arm"] = pd.Categorical(df["arm"].astype("string"), categories=["Control", "Treatment A", "Treatment B"])
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
def box_stats(v, k=1.5):
"""Tukey box: type-7 quartiles (np.quantile default), whiskers at the most extreme points within k × IQR."""
q1, med, q3 = np.quantile(v, [0.25, 0.5, 0.75])
iqr = q3 - q1
inside = v[(v >= q1 - k * iqr) & (v <= q3 + k * iqr)]
out = v[(v < q1 - k * iqr) | (v > q3 + k * iqr)]
return dict(q1=q1, med=med, q3=q3, lo=inside.min(), hi=inside.max(), mean=v.mean(),
notch=1.58 * iqr / np.sqrt(v.size), outliers=out)
def bandwidth(v, rule="nrd0"):
"""R bw.nrd0 / bw.nrd, or scipy's Scott rule — as the app computes it."""
v = np.asarray(v, dtype=float)
n, sd = v.size, v.std(ddof=1)
iqr = np.subtract(*np.percentile(v, [75, 25]))
if rule == "scott":
return sd * n ** (-1 / 5)
lo = min(sd, iqr / 1.34) or sd or abs(v[0]) or 1.0
return (0.9 if rule == "nrd0" else 1.06) * lo * n ** (-1 / 5)
parts = groups(df, "outcome", "arm", max_levels=12)
fig = go.Figure()
for i, (label, v) in enumerate(parts):
color = PALETTE[i % len(PALETTE)]
# bw.nrd0 per group, truncated to the data range; one scale group = one density scale
fig.add_violin(x=[label] * v.size, y=v, name=label, bandwidth=bandwidth(v, "nrd0"), spanmode="hard",
scalegroup="all", scalemode="width", points=False, box_visible=False,
line_color=color, fillcolor=color, opacity=0.35, showlegend=False)
s = box_stats(v, 1.5) # precomputed so plotly draws the app's type-7 box, not its own quartile method
fig.add_box(x=[label], q1=[s["q1"]], median=[s["med"]], q3=[s["q3"]], lowerfence=[s["lo"]], upperfence=[s["hi"]],
mean=[s["mean"]], boxmean=True,
width=0.18, line_color=color, fillcolor="rgba(0,0,0,0)", name=label, showlegend=False)
fig.add_scatter(x=[label] * s["outliers"].size, y=s["outliers"], mode="markers", marker=dict(color=color, symbol="circle-open"), showlegend=False)
fig.update_layout(violinmode="overlay", boxmode="overlay", xaxis_title="arm", yaxis_title="outcome")
fig.show()Needs pandas, numpy, plotly · reads box-violin-demo.csv · app theme from the optional codesplash helper
# Box & violin — Codesplash Chart Lab (recipe "box-violin")
# controls: violin=true, notch=false, mean=true, whisker=1.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("box-violin-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["arm"]] <- factor(df[["arm"]], levels = c("Control", "Treatment A", "Treatment B"))
d <- df[is.finite(df[["outcome"]]) & !is.na(df[["arm"]]), , drop = FALSE]
d <- d[d[["arm"]] %in% head(levels(d[["arm"]]), 12), , drop = FALSE] # at most 12 groups
d[["arm"]] <- droplevels(d[["arm"]])
p <- ggplot(d, aes(x = .data[["arm"]], y = .data[["outcome"]]))
# violins: bw.nrd0 per group, truncated to the data range, one density scale (scale = "area")
p <- p + geom_violin(aes(fill = .data[["arm"]]), bw = "nrd0", trim = TRUE, scale = "area", alpha = 0.3, colour = NA, show.legend = FALSE) +
scale_fill_manual(values = rep(cs_cat, length.out = nlevels(d[["arm"]])))
# box: quantile type 7, whiskers within 1.5 × IQR, notches 1.58·IQR/√n — ggplot2's own conventions match the app
p <- p + geom_boxplot(width = 0.18, coef = 1.5, notch = FALSE, fill = NA, outlier.shape = 1, outlier.colour = cs_cat[1])
p <- p + stat_summary(fun = mean, geom = "point", shape = 23, size = 2.5, fill = cs_cat[2], colour = "white")
p <- p + labs(x = "arm", y = "outcome") + theme_cs
print(p)Needs ggplot2 · reads box-violin-demo.csv · app theme from the optional codesplashr helper
-- Box & violin — Codesplash Chart Lab (recipe "box-violin")
-- controls: violin=true, notch=false, mean=true, whisker=1.5
-- Tukey box statistics: type-7 quartiles (quantile_cont), whiskers at the most extreme values
-- within 1.5 × IQR of the box, notch half-width 1.58·IQR/√n (McGill, Tukey & Larsen 1978)
WITH v0 AS (
SELECT "arm"::VARCHAR AS grp, "outcome"::DOUBLE AS x
FROM read_csv('box-violin-demo.csv')
WHERE "outcome" IS NOT NULL AND isfinite("outcome"::DOUBLE) AND "arm" 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(['Control', 'Treatment A', 'Treatment B'], 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),
q AS (
SELECT grp, rk, count(*) AS n, avg(x) AS mean,
quantile_cont(x, 0.25) AS q1, quantile_cont(x, 0.5) AS median, quantile_cont(x, 0.75) AS q3,
min(x) AS vmin, max(x) AS vmax
FROM v
GROUP BY grp, rk
)
SELECT q.grp AS "group", q.n, q.vmin AS min, q.q1, q.median, q.q3, q.vmax AS max, q.mean,
min(v.x) FILTER (WHERE v.x >= q.q1 - 1.5 * (q.q3 - q.q1)) AS whisker_lo,
max(v.x) FILTER (WHERE v.x <= q.q3 + 1.5 * (q.q3 - q.q1)) AS whisker_hi,
count(*) FILTER (WHERE v.x < q.q1 - 1.5 * (q.q3 - q.q1) OR v.x > q.q3 + 1.5 * (q.q3 - q.q1)) AS outliers,
1.58 * (q.q3 - q.q1) / sqrt(q.n) AS notch_half_width
FROM q JOIN v USING (grp)
GROUP BY q.grp, q.rk, q.n, q.vmin, q.q1, q.median, q.q3, q.vmax, q.mean
ORDER BY q.rk;Needs duckdb · reads box-violin-demo.csv