svgbrushableboxen
Letter-value (boxen) plot
How do the tails of large samples compare across groups?
How to read it
- Find the median line, then the widest box: it holds the middle half.
- Each narrower box halves the tail again, so the stack shows how the tails behave.
- Compare how quickly boxes shrink across groups: slow shrinking means a long tail.
- Callout 1: Widest box: the middle half.
- Callout 2: Each narrower box covers half of what remains in the tail.
- 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
# Letter-value (boxen) plot — Codesplash Chart Lab (recipe "boxen")
# 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("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)]
INK = cs.palette(dark=False)["foreground"] if cs else "#131922"
BG = cs.palette(dark=False)["background"] if cs else "#ffffff"
parts = [(label, v) for label, v in groups(df, "order_value", "region", max_levels=8) if v.size > 3]
bg = np.array(px.colors.hex_to_rgb(BG))
fig = go.Figure()
for i, (label, v) in enumerate(parts):
color = np.array(px.colors.hex_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
r, g_, b = (color * share + bg * (1 - share)).round().astype(int)
fig.add_shape(type="rect", x0=i - half, x1=i + half, y0=lo, y1=hi, fillcolor=f"rgb({r}, {g_}, {b})", line_width=0, layer="below")
fig.add_shape(type="line", x0=i - 0.4, x1=i + 0.4, y0=np.median(v), y1=np.median(v), line=dict(color=INK, width=2))
_, lo, hi = boxes[-1]
out = v[(v < lo) | (v > hi)] # beyond the deepest box
fig.add_scatter(x=np.full(out.size, i), y=out, mode="markers", marker=dict(color=PALETTE[i % len(PALETTE)], size=5, opacity=0.6), name=label, showlegend=False)
fig.add_scatter(x=[i, i], y=[v.min(), v.max()], mode="markers", marker_opacity=0, showlegend=False, hoverinfo="skip") # keeps the axis range
fig.update_layout(xaxis=dict(tickvals=list(range(len(parts))), ticktext=[label for label, _ in parts], title="region", range=[-0.6, len(parts) - 0.4]), yaxis_title="order_value")
fig.show()Needs pandas, numpy, plotly · reads boxen-demo.csv · app theme from the optional codesplash helper
# Letter-value (boxen) plot — Codesplash Chart Lab (recipe "boxen")
# 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("boxen-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["region"]] <- factor(df[["region"]], levels = c("North", "South", "West"))
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]
}
letter_values <- function(v, outlier_share = 0.007) {
# tail probabilities 2^-(d+1), d = 1..k (type 7); about 0.7 % of points stay beyond the deepest box
n <- length(v)
k <- max(1, floor(log2(n) - log2(max(1, n * outlier_share))) + 1)
p <- 2^-(seq_len(k) + 1)
data.frame(depth = seq_len(k), lo = quantile(v, p, type = 7, names = FALSE), hi = quantile(v, 1 - p, type = 7, names = FALSE))
}
bg <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$background else "#ffffff"
ink <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$foreground else "#131922"
parts <- groups_of(df, "order_value", "region", max_levels = 8)
parts <- parts[lengths(parts) > 3]
mix <- function(col, share) vapply(share, function(s) grDevices::rgb(t(grDevices::col2rgb(col) * s + grDevices::col2rgb(bg) * (1 - s)) / 255), "")
boxes <- do.call(rbind, lapply(seq_along(parts), function(i) {
lv <- letter_values(parts[[i]])
k <- nrow(lv)
half <- 0.4 * (1 - 0.7 * (lv$depth - 1) / k) # deeper boxes are narrower …
share <- (92 - 72 * (lv$depth - 1) / max(1, k - 1)) / 100 # … and fade toward the background
data.frame(i = i - 1, depth = lv$depth, xmin = i - 1 - half, xmax = i - 1 + half, lo = lv$lo, hi = lv$hi,
fill = mix(cs_cat[(i - 1) %% length(cs_cat) + 1], share))
}))
outs <- do.call(rbind, lapply(seq_along(parts), function(i) {
v <- parts[[i]]; deepest <- boxes[boxes$i == i - 1, ][which.max(boxes$depth[boxes$i == i - 1]), ]
o <- v[v < deepest$lo | v > deepest$hi] # beyond the deepest box
if (length(o)) data.frame(i = i - 1, value = o, group = names(parts)[i]) else NULL
}))
boxes <- boxes[order(boxes$i, -boxes$depth), ] # deepest first, so wider, darker central boxes sit on top
med <- data.frame(i = seq_along(parts) - 1, m = vapply(parts, median, 0))
p <- ggplot() +
geom_rect(data = boxes, aes(xmin = xmin, xmax = xmax, ymin = lo, ymax = hi, fill = I(fill))) +
geom_segment(data = med, aes(x = i - 0.4, xend = i + 0.4, y = m, yend = m), colour = ink, linewidth = 0.9) +
scale_x_continuous(breaks = seq_along(parts) - 1, labels = names(parts)) +
labs(x = "region", y = "order_value") + theme_cs
if (!is.null(outs)) p <- p + geom_point(data = outs, aes(i, value), colour = cs_cat[1], alpha = 0.6, size = 1)
print(p)Needs ggplot2 · reads boxen-demo.csv · app theme from the optional codesplashr helper
-- Letter-value (boxen) plot — Codesplash Chart Lab (recipe "boxen")
-- controls: defaults
-- letter values per group: tail probabilities 2^−(d+1), d = 1…k with
-- k = ⌊log₂ n − log₂ max(1, 0.007·n)⌋ + 1 (never more than 8), type-7 quantiles (quantile_cont)
WITH v0 AS (
SELECT "region"::VARCHAR AS grp, "order_value"::DOUBLE AS x
FROM read_csv('boxen-demo.csv')
WHERE "order_value" IS NOT NULL AND isfinite("order_value"::DOUBLE) AND "region" IS NOT NULL
),
lv AS ( -- level order as stored in the data dictionary; at most 8 groups
SELECT grp, row_number() OVER (ORDER BY list_position(['North', 'South', 'West'], 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 <= 8),
q AS (
SELECT grp, rk, count(*) AS n, quantile_cont(x, 0.5) AS median,
quantile_cont(x, [0.25, 0.125, 0.0625, 0.03125, 0.015625, 0.0078125, 0.00390625, 0.001953125]) AS lo,
quantile_cont(x, [0.75, 0.875, 0.9375, 0.96875, 0.984375, 0.9921875, 0.99609375, 0.998046875]) AS hi
FROM v
GROUP BY grp, rk
HAVING count(*) > 3
)
SELECT grp AS "group", d AS depth, lo[d] AS lo, hi[d] AS hi, median, n
FROM q, range(1, 9) t(d)
WHERE d <= floor(log2(n) - log2(greatest(1, 0.007 * n))) + 1
ORDER BY rk, d;Needs duckdb · reads boxen-demo.csv
- seaborn's boxenplot(k_depth="proportion") rounds the depth slightly differently, so the code draws the letter values itself.