Skip to content
svgbrushablebox-violin

Box & violin

How does a numeric variable differ across groups?

Demo data · seed 20261101 · 240 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Compare the medians first: the line inside each box.
  2. Compare the box heights: each box holds the middle half of its group, so a taller box means more spread.
  3. Check the points beyond the whiskers, then the violin outline for a shape the box cannot show, such as two humps.
  1. Callout 1: Line in the box: the median. Dot: the mean.
  2. Callout 2: Beyond the whiskers: values flagged as unusual, not errors.
  3. 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