Skip to content
svgbrushabledensity

Density curve

What is the smooth shape of a distribution, and how much does it depend on the bandwidth?

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

How to read it

  1. Read the height as relative concentration: higher means more values nearby, and the total area under the curve is 1.
  2. Compare the curves at half and twice the bandwidth: trust the features that appear in all three.
  3. Use the rug along the axis to see where the real values are, and whether the curve runs past them.
  1. Callout 1: The peak: where values concentrate.
  2. Callout 2: The same data at half and twice the bandwidth: wiggles that vanish were noise.
  3. Callout 3: Rug: one tick per value.

Watch out

  • The curve's height is not a probability; only areas under it are.
  • Smoothing spills past natural limits: a density of ages or prices can show mass below zero.

Defaults

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
Compare bandwidths ×0.5 / ×1 / ×2
On
Only without a group.
Fill under curve
On
Shade the area under each curve.
Rug (≤ 5,000 points)
On
Add one tick per value along the axis.

Pinned in the code

  • Gaussian kernel; bandwidth = rule × adjust (R `density(bw = "nrd0", adjust)`; scipy `gaussian_kde` uses Scott).
  • Evaluated on 160 points over [min − 3·bw, max + 3·bw] (R's default cut = 3), direct summation.
  • Per-group curves each use their own bandwidth and integrate to 1; the selected-rows curve is scaled by its share of rows.
# Density curve — Codesplash Chart Lab (recipe "density")
# controls: bandwidth=nrd0, adjust=1, compare=true, fill=true, rug=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

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("density-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

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

parts = groups(df, "income_k", None, max_levels=6)
pooled = np.concatenate([v for _, v in parts])
base = bandwidth(pooled, "nrd0") * 1
curves = [(f"bw {base * k:.3g} (×{k:g})", pooled, base * k) for k in (0.5, 1, 2)]  # compare bandwidths
pad = 3 * max(h for _, _, h in curves)  # R density(cut = 3)
grid = np.linspace(pooled.min() - pad, pooled.max() + pad, 160)

fig, ax = plt.subplots(figsize=(7, 4))
for i, (label, v, h) in enumerate(curves):
    y = kde(v, h, grid)
    ax.plot(grid, y, color=PALETTE[i], linewidth=2 if i == 1 else 1.5, linestyle="--" if i == 0 else "-", label=label)
    if i == 1:
        ax.fill_between(grid, y, color=PALETTE[i], alpha=0.22, linewidth=0)
if pooled.size <= 5000:
    ax.plot(pooled, np.zeros_like(pooled), "|", color=plt.rcParams["text.color"], alpha=0.3, markersize=10)
ax.set_xlabel("income_k")
ax.set_ylabel("Density")
if len(curves) > 1:
    ax.legend()
plt.show()

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