Skip to content
svgbrushableboxen

Letter-value (boxen) plot

How do the tails of large samples compare across groups?

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

How to read it

  1. Find the median line, then the widest box: it holds the middle half.
  2. Each narrower box halves the tail again, so the stack shows how the tails behave.
  3. Compare how quickly boxes shrink across groups: slow shrinking means a long tail.
  1. Callout 1: Widest box: the middle half.
  2. Callout 2: Each narrower box covers half of what remains in the tail.
  3. Callout 3: Dots: values beyond the last box.

Watch out

  • It needs large samples. With a few hundred rows the outer boxes rest on a handful of values.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Letter values at tail probabilities 2^−(d+1), d = 1…k (fourths, eighths, sixteenths…), type-7 quantiles.
  • Depth k = ⌊log₂ n − log₂(0.007·n)⌋ + 1 so about 0.7 % of points remain beyond the deepest box and are drawn as outliers (Hofmann et al. "tail" stopping rule).
  • Box width and opacity shrink with depth; the line is the median.
# Letter-value (boxen) plot — Codesplash Chart Lab (recipe "boxen")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgb

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("boxen-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["region"] = pd.Categorical(df["region"].astype("string"), categories=["North", "South", "West"])

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 letter_values(v, outlier_share=0.007):
    """Letter values (Hofmann, Wickham & Kafadar 2017): tail probabilities 2^−(d+1), d = 1…k, type 7;
    k = ⌊log₂ n − log₂ max(1, 0.007·n)⌋ + 1 leaves about 0.7 % of points beyond the deepest box."""
    n = v.size
    k = max(1, int(np.floor(np.log2(n) - np.log2(max(1.0, n * outlier_share)))) + 1)
    return [(d, *np.quantile(v, [2.0 ** -(d + 1), 1 - 2.0 ** -(d + 1)])) for d in range(1, k + 1)]

parts = [(label, v) for label, v in groups(df, "order_value", "region", max_levels=8) if v.size > 3]
bg = np.array(to_rgb(plt.rcParams["axes.facecolor"]))
fig, ax = plt.subplots(figsize=(7, 4))
for i, (label, v) in enumerate(parts):
    color = np.array(to_rgb(PALETTE[i % len(PALETTE)]))
    boxes = letter_values(v)
    k = len(boxes)
    for d, lo, hi in reversed(boxes):  # deepest first, so the wider, darker central boxes sit on top (as the app draws)
        half = 0.4 * (1 - 0.7 * (d - 1) / k)
        share = (92 - 72 * (d - 1) / max(1, k - 1)) / 100
        ax.add_patch(plt.Rectangle((i - half, lo), 2 * half, hi - lo, color=color * share + bg * (1 - share), linewidth=0))
    ax.hlines(np.median(v), i - 0.4, i + 0.4, color=plt.rcParams["text.color"], linewidth=2)
    _, lo, hi = boxes[-1]
    out = v[(v < lo) | (v > hi)]  # beyond the deepest box
    ax.scatter(np.full(out.size, i), out, s=8, color=color, alpha=0.6, linewidths=0)
ax.autoscale_view()
ax.set_xlim(-0.6, len(parts) - 0.4)
ax.set_xticks(range(len(parts)), [label for label, _ in parts])
ax.set_xlabel("region")
ax.set_ylabel("order_value")
plt.show()

Needs pandas, numpy, matplotlib · reads boxen-demo.csv · app theme from the optional codesplash helper

  • seaborn's boxenplot(k_depth="proportion") rounds the depth slightly differently, so the code draws the letter values itself.