Skip to content
svgbrushableridgeline

Ridgeline

How do the distributions of many groups compare and shift?

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

How to read it

  1. Read each row as one group's distribution, on a shared x axis.
  2. Follow the peaks from row to row to see the level shift.
  3. Compare widths to see whether spread changes along with the level.
  1. Callout 1: A peak: where this group's values concentrate.
  2. Callout 2: The short vertical line: this group's median.
  3. Callout 3: Rows are in this order; choose an order that means something.

Watch out

  • Overlap hides part of each curve, so compare peaks and medians rather than areas.
  • Each curve is smoothed separately: a small group's bump may be noise.

Defaults

Overlap
1.6
How much neighbouring curves overlap.
Range 0.5 to 3, step 0.1
Order
As in data / dictionary
How rows or groups are ordered.
Also: By median
Median line
On
Mark each group's median.
Bandwidth rule
nrd0 (Silverman, R default)
The rule that sets how much the curve is smoothed. Scott and Silverman suit one-humped data.
Also: nrd (Scott variant) · Scott (scipy default)
Bandwidth × adjust
1
Multiply the bandwidth: below 1 shows more detail and noise, above 1 gives a smoother curve.
Range 0.25 to 4, step 0.25

Pinned in the code

  • Each ridge is a Gaussian KDE with its own bandwidth (rule × adjust) on a shared grid over [min − 3·bw, max + 3·bw].
  • All ridges share one height scale (global maximum density), as `ggridges::geom_density_ridges(scale = overlap)`.
  • Median: type-7 quantile.
# Ridgeline — Codesplash Chart Lab (recipe "ridgeline")
# controls: overlap=1.6, order=data, median=true, bandwidth=nrd0, adjust=1
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

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("ridgeline-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["month"] = pd.Categorical(df["month"].astype("string"), categories=["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"])

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))

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

SEQ = cs.palette(dark=False)["sequential"] if cs else ["#eff6fd", "#1a469d"]  # the app's sequential ramp
CMAP = LinearSegmentedColormap.from_list("codesplash", SEQ)
parts = [(label, v) for label, v in groups(df, "temp_c", "month", max_levels=24) if v.size > 1]
hs = [bandwidth(v, "nrd0") * 1 for _, v in parts]  # each ridge its own bandwidth
pooled = np.concatenate([v for _, v in parts])
pad = 3 * max(hs)
grid = np.linspace(pooled.min() - pad, pooled.max() + pad, 140)
dens = [kde(v, h, grid) for (_, v), h in zip(parts, hs)]
top = max(d.max() for d in dens)  # one height scale for all ridges (ggridges scale = overlap)
overlap = 1.6
k = len(parts)
colors = PALETTE if k <= 8 else [CMAP(0.25 + 0.7 * i / max(1, k - 1)) for i in range(k)]

fig, ax = plt.subplots(figsize=(7, 1.5 + 0.45 * k))
for i, ((label, v), d) in enumerate(zip(parts, dens)):
    base = k - 1 - i  # first group on top; lower ridges overlap the ones above
    ridge = base + overlap * d / top
    color = colors[i % len(colors)]
    ax.fill_between(grid, base, ridge, color=color, alpha=0.55, linewidth=0, zorder=i)
    ax.plot(grid, ridge, color=color, linewidth=1.2, zorder=i + 0.5)
    m = np.median(v)
    ax.vlines(m, base, base + overlap * np.interp(m, grid, d) / top, color=plt.rcParams["text.color"], alpha=0.6, linewidth=1.2, zorder=i + 0.6)
ax.set_yticks([k - 1 - i for i in range(k)], [label for label, _ in parts])
ax.grid(axis="y", visible=False)
ax.set_xlabel("temp_c")
plt.show()

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

  • ggridges::geom_density_ridges(scale = overlap) draws the same picture; the code builds the ridges with base ggplot2 so no extension package is needed.