svgbrushabledensity
Density curve
What is the smooth shape of a distribution, and how much does it depend on the bandwidth?
How to read it
- Read the height as relative concentration: higher means more values nearby, and the total area under the curve is 1.
- Compare the curves at half and twice the bandwidth: trust the features that appear in all three.
- Use the rug along the axis to see where the real values are, and whether the curve runs past them.
- Callout 1: The peak: where values concentrate.
- Callout 2: The same data at half and twice the bandwidth: wiggles that vanish were noise.
- 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
# 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 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("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
INK = cs.palette(dark=False)["foreground"] if cs else "#131922"
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 = go.Figure()
for i, (label, v, h) in enumerate(curves):
fill = "tozeroy" if i == 1 else None
fig.add_scatter(x=grid, y=kde(v, h, grid), mode="lines", name=label, fill=fill, line=dict(color=PALETTE[i], width=2 if i == 1 else 1.5, dash="dash" if i == 0 else "solid"))
if pooled.size <= 5000:
fig.add_scatter(x=pooled, y=np.zeros_like(pooled), mode="markers", marker=dict(symbol="line-ns-open", size=10, color=INK, opacity=0.3), showlegend=False)
fig.update_layout(xaxis_title="income_k", yaxis_title="Density", showlegend=len(curves) > 1)
fig.show()Needs pandas, numpy, plotly · reads density-demo.csv · app theme from the optional codesplash helper
# Density curve — Codesplash Chart Lab (recipe "density")
# controls: bandwidth=nrd0, adjust=1, compare=true, fill=true, rug=true
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("density-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
bandwidth <- function(v, rule = "nrd0") {
switch(rule, nrd0 = bw.nrd0(v), nrd = bw.nrd(v), scott = sd(v) * length(v)^(-1 / 5))
}
kde <- function(v, h, grid) {
# Gaussian kernel density by direct summation on `grid` (the app's method; density() uses an FFT)
vapply(grid, function(g) sum(dnorm((g - v) / h)), numeric(1)) / (length(v) * h)
}
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]
}
parts <- groups_of(df, "income_k", NULL, max_levels = 6)
pooled <- unlist(parts, use.names = FALSE)
base <- bandwidth(pooled, "nrd0") * 1
curves <- lapply(c(0.5, 1, 2), function(k) list(label = sprintf("bw %.3g (×%g)", base * k, k), v = pooled, h = base * k)) # compare bandwidths
pad <- 3 * max(vapply(curves, function(cv) cv$h, numeric(1))) # R density(cut = 3)
grid <- seq(min(pooled) - pad, max(pooled) + pad, length.out = 160)
dens <- do.call(rbind, lapply(curves, function(cv) data.frame(curve = cv$label, x = grid, y = kde(cv$v, cv$h, grid))))
labels <- vapply(curves, function(cv) cv$label, "")
dens$curve <- factor(dens$curve, levels = labels)
cols <- setNames(rep(cs_cat, length.out = length(labels)), labels)
p <- ggplot(dens, aes(x, y, colour = curve))
p <- p + geom_area(data = dens[dens$curve == labels[2], ], aes(fill = curve), alpha = 0.22, colour = NA, show.legend = FALSE)
p <- p + geom_line(aes(linetype = curve), linewidth = 0.9) +
scale_linetype_manual(values = c("dashed", "solid", "solid")) +
scale_colour_manual(values = cols) + scale_fill_manual(values = cols) +
labs(x = "income_k", y = "Density", colour = NULL, linetype = NULL) + theme_cs
if (length(labels) == 1) p <- p + theme(legend.position = "none")
if (length(pooled) <= 5000) p <- p + geom_rug(data = data.frame(x = pooled), aes(x = x), inherit.aes = FALSE, alpha = 0.3)
print(p)Needs ggplot2 · reads density-demo.csv · app theme from the optional codesplashr helper
-- Density curve — Codesplash Chart Lab (recipe "density")
-- controls: bandwidth=nrd0, adjust=1, compare=true, fill=true, rug=true
-- Gaussian KDE by direct summation on a 160-point grid over [min − 3·bw, max + 3·bw] (R density(cut = 3));
-- bandwidth = nrd0 × 1 per group; type-7 median per group
WITH v0 AS (
SELECT 'income_k' AS grp, "income_k"::DOUBLE AS x
FROM read_csv('density-demo.csv')
WHERE "income_k" IS NOT NULL AND isfinite("income_k"::DOUBLE)
),
lv AS ( -- level order by frequency; at most 6 groups
SELECT grp, row_number() OVER (ORDER BY n DESC, 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 <= 6),
s AS (
SELECT grp, rk, count(*) AS n, stddev_samp(x) AS sd,
quantile_cont(x, 0.75) - quantile_cont(x, 0.25) AS iqr,
min(x) AS lo, max(x) AS hi, quantile_cont(x, 0.5) AS median
FROM v
GROUP BY grp, rk
HAVING count(*) >= 1
),
b AS (SELECT *, 1 * 0.9 * coalesce(nullif(least(sd, iqr / 1.34), 0), nullif(sd, 0), 1) * pow(n, -0.2) AS h FROM s),
r AS (SELECT min(lo) - 3 * max(h) AS lo, max(hi) + 3 * max(h) AS hi FROM b),
grid AS (SELECT r.lo + (r.hi - r.lo) * i / 159 AS gx FROM r, range(160) t(i))
SELECT b.grp AS "group", grid.gx AS x,
sum(exp(-0.5 * pow((grid.gx - v.x) / b.h, 2))) / (b.n * b.h * sqrt(2 * pi())) AS density,
b.h AS bandwidth, b.median
FROM b JOIN v USING (grp) CROSS JOIN grid
GROUP BY b.grp, b.rk, grid.gx, b.n, b.h, b.median
ORDER BY b.rk, x;Needs duckdb · reads density-demo.csv