svgbrushabledensity-2d
2-D density contours
What is the smooth joint shape of two variables — how many modes, which direction?
How to read it
- Read the bands like a contour map: each inner band is denser than the one around it.
- Count the separate peaks: each may be a distinct group.
- Read each band's orientation for how the two variables move together inside that group.
- Callout 1: The innermost band: the top of this hill.
- Callout 2: A second hill: a second cluster of rows.
- Callout 3: Colour bar: estimated density.
Watch out
- Smoothing can join separate groups or draw density where there are no rows. Turn on the points to check.
Defaults
- Contour levels
- 7
- How many contour bands to draw.
- Range 3 to 14, step 1
- Grid points per axis
- 60
- How finely the density is computed; more is slower and smoother.
- Range 25 to 120, step 5
- Filled bands
- On
- Fill between contours rather than drawing lines only.
- Points
- On
- Show the individual points as well.
Pinned in the code
- MASS `kde2d`: product Gaussian kernel with SDs h/4 where h = `bandwidth.nrd` = 4·1.06·min(s, IQR/1.34)·n^(−1/5) per axis (type-7 quartiles).
- Grid: n × n points over the data range expanded by 15 % per side so outer contours close (kde2d's default lims are the bare range).
- Bands: marching squares (d3-contour) at k equally spaced levels max·i/(k + 1), i = 1…k, linear interpolation between grid points.
# 2-D density contours — Codesplash Chart Lab (recipe "density-2d")
# controls: levels=7, grid=60, fill=true, points=true
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("density-2d-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
SEQ = cs.palette(dark=False)["sequential"] if cs else ["#eff6fd", "#1a469d"] # the app's sequential ramp
CMAP = LinearSegmentedColormap.from_list("codesplash", SEQ)
def bandwidth_nrd(v):
"""MASS::bandwidth.nrd: 4 · 1.06 · min(sd, IQR/1.34) · n^(−1/5), quartiles type 7."""
q1, q3 = np.quantile(v, [0.25, 0.75])
sd = v.std(ddof=1)
return 4 * 1.06 * min(sd, (q3 - q1) / 1.34 or sd) * v.size ** (-1 / 5)
def kde2d(x, y, n, lims):
"""MASS::kde2d: product Gaussian kernel with standard deviations h/4 on an n × n grid."""
hx, hy = bandwidth_nrd(x) / 4, bandwidth_nrd(y) / 4
gx, gy = np.linspace(lims[0], lims[1], n), np.linspace(lims[2], lims[3], n)
ax_ = np.exp(-0.5 * ((gx[:, None] - x[None, :]) / hx) ** 2) / np.sqrt(2 * np.pi)
ay_ = np.exp(-0.5 * ((gy[:, None] - y[None, :]) / hy) ** 2) / np.sqrt(2 * np.pi)
return gx, gy, ax_ @ ay_.T / (x.size * hx * hy) # z[i, j] at (gx[i], gy[j])
d = df[["duration_min", "waiting_min"]].dropna()
xs, ys = d["duration_min"].to_numpy(dtype=float), d["waiting_min"].to_numpy(dtype=float)
ex, ey = 0.15 * np.ptp(xs), 0.15 * np.ptp(ys) # grid over the range expanded by 15 % per side so contours close
gx, gy, z = kde2d(xs, ys, 60, (xs.min() - ex, xs.max() + ex, ys.min() - ey, ys.max() + ey))
levels = z.max() * np.arange(1, 7 + 1) / (7 + 1) # equally spaced levels max·i/(k + 1)
fig, ax = plt.subplots(figsize=(7, 4.5))
ax.contourf(gx, gy, z.T, levels=[*levels, z.max()], cmap=CMAP, alpha=0.9)
ax.contour(gx, gy, z.T, levels=levels, colors=plt.rcParams["text.color"], linewidths=0.6, alpha=0.6)
ax.scatter(xs, ys, s=4, color=PALETTE[0], alpha=0.35, linewidths=0)
ax.set_xlabel("duration_min")
ax.set_ylabel("waiting_min")
plt.show()Needs pandas, numpy, matplotlib · reads density-2d-demo.csv · app theme from the optional codesplash helper
# 2-D density contours — Codesplash Chart Lab (recipe "density-2d")
# controls: levels=7, grid=60, fill=true, points=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-2d-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
SEQ = cs.palette(dark=False)["sequential"] if cs else ["#eff6fd", "#1a469d"] # the app's sequential ramp
def bandwidth_nrd(v):
"""MASS::bandwidth.nrd: 4 · 1.06 · min(sd, IQR/1.34) · n^(−1/5), quartiles type 7."""
q1, q3 = np.quantile(v, [0.25, 0.75])
sd = v.std(ddof=1)
return 4 * 1.06 * min(sd, (q3 - q1) / 1.34 or sd) * v.size ** (-1 / 5)
def kde2d(x, y, n, lims):
"""MASS::kde2d: product Gaussian kernel with standard deviations h/4 on an n × n grid."""
hx, hy = bandwidth_nrd(x) / 4, bandwidth_nrd(y) / 4
gx, gy = np.linspace(lims[0], lims[1], n), np.linspace(lims[2], lims[3], n)
ax_ = np.exp(-0.5 * ((gx[:, None] - x[None, :]) / hx) ** 2) / np.sqrt(2 * np.pi)
ay_ = np.exp(-0.5 * ((gy[:, None] - y[None, :]) / hy) ** 2) / np.sqrt(2 * np.pi)
return gx, gy, ax_ @ ay_.T / (x.size * hx * hy) # z[i, j] at (gx[i], gy[j])
d = df[["duration_min", "waiting_min"]].dropna()
xs, ys = d["duration_min"].to_numpy(dtype=float), d["waiting_min"].to_numpy(dtype=float)
ex, ey = 0.15 * np.ptp(xs), 0.15 * np.ptp(ys) # grid over the range expanded by 15 % per side so contours close
gx, gy, z = kde2d(xs, ys, 60, (xs.min() - ex, xs.max() + ex, ys.min() - ey, ys.max() + ey))
levels = z.max() * np.arange(1, 7 + 1) / (7 + 1) # equally spaced levels max·i/(k + 1)
fig = go.Figure(go.Contour(x=gx, y=gy, z=z.T, colorscale=[[0, SEQ[0]], [1, SEQ[1]]], showscale=False, line_width=0.8,
contours=dict(start=levels[0], end=levels[-1], size=levels[1] - levels[0] if levels.size > 1 else 1, coloring="fill")))
fig.add_scatter(x=xs, y=ys, mode="markers", marker=dict(color=PALETTE[0], size=3, opacity=0.35), showlegend=False)
fig.update_layout(xaxis_title="duration_min", yaxis_title="waiting_min")
fig.show()Needs pandas, numpy, plotly · reads density-2d-demo.csv · app theme from the optional codesplash helper
# 2-D density contours — Codesplash Chart Lab (recipe "density-2d")
# controls: levels=7, grid=60, fill=true, points=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-2d-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
seq_cols <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$sequential else c("#eff6fd", "#1a469d") # the app's sequential ramp
ink <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$foreground else "#131922"
d <- df[is.finite(df[["duration_min"]]) & is.finite(df[["waiting_min"]]), , drop = FALSE]
x <- d[["duration_min"]]; y <- d[["waiting_min"]]
lims <- c(range(x) + c(-1, 1) * 0.15 * diff(range(x)), range(y) + c(-1, 1) * 0.15 * diff(range(y))) # expanded 15 % per side
k2 <- MASS::kde2d(x, y, n = 60, lims = lims) # product Gaussian kernel, h = bandwidth.nrd (SDs h/4)
grid <- expand.grid(x = k2$x, y = k2$y)
grid$z <- as.vector(k2$z)
levels <- max(grid$z) * seq_len(7) / (7 + 1) # equally spaced levels max·i/(k + 1)
p <- ggplot(grid, aes(x, y, z = z))
p <- p + geom_contour_filled(breaks = c(levels, Inf), show.legend = FALSE) +
scale_fill_manual(values = colorRampPalette(seq_cols)(length(levels)), drop = FALSE)
p <- p + geom_contour(breaks = levels, colour = ink, linewidth = 0.3, alpha = 0.6)
p <- p + geom_point(data = data.frame(x = x, y = y), aes(x, y), inherit.aes = FALSE, colour = cs_cat[1], size = 0.6, alpha = 0.35)
p <- p + labs(x = "duration_min", y = "waiting_min") + theme_cs
print(p)Needs ggplot2 · reads density-2d-demo.csv · app theme from the optional codesplashr helper
-- 2-D density contours — Codesplash Chart Lab (recipe "density-2d")
-- controls: levels=7, grid=60, fill=true, points=true
-- MASS::kde2d on a 60 × 60 grid over the range expanded by 15 % per side: product Gaussian kernel with
-- standard deviations h/4, h = bandwidth.nrd = 4·1.06·min(sd, IQR/1.34)·n^(−1/5). Cost is grid² × rows.
WITH v AS (
SELECT "duration_min"::DOUBLE AS x, "waiting_min"::DOUBLE AS y
FROM read_csv('density-2d-demo.csv')
WHERE "duration_min" IS NOT NULL AND "waiting_min" IS NOT NULL AND isfinite("duration_min"::DOUBLE) AND isfinite("waiting_min"::DOUBLE)
),
s AS (
SELECT count(*) AS n, min(x) AS x0, max(x) AS x1, min(y) AS y0, max(y) AS y1,
stddev_samp(x) AS sdx, stddev_samp(y) AS sdy,
quantile_cont(x, 0.75) - quantile_cont(x, 0.25) AS iqrx,
quantile_cont(y, 0.75) - quantile_cont(y, 0.25) AS iqry
FROM v
),
h AS (
SELECT n, 1.06 * least(sdx, coalesce(nullif(iqrx / 1.34, 0), sdx)) * pow(n, -0.2) AS hx,
1.06 * least(sdy, coalesce(nullif(iqry / 1.34, 0), sdy)) * pow(n, -0.2) AS hy,
x0 - 0.15 * (x1 - x0) AS gx0, x1 + 0.15 * (x1 - x0) AS gx1,
y0 - 0.15 * (y1 - y0) AS gy0, y1 + 0.15 * (y1 - y0) AS gy1
FROM s
),
gx AS (SELECT gx0 + (gx1 - gx0) * i / 59 AS gx FROM h, range(60) t(i)),
gy AS (SELECT gy0 + (gy1 - gy0) * j / 59 AS gy FROM h, range(60) t(j))
SELECT gx.gx AS x, gy.gy AS y,
sum(exp(-0.5 * pow((gx.gx - v.x) / h.hx, 2)) * exp(-0.5 * pow((gy.gy - v.y) / h.hy, 2)))
/ (2 * pi() * h.n * h.hx * h.hy) AS density
FROM gx, gy, v, h
GROUP BY gx.gx, gy.gy, h.n, h.hx, h.hy
ORDER BY y, x;Needs duckdb · reads density-2d-demo.csv
- R uses MASS::kde2d (ships with R); Python ports it so both grids and contour levels match the app.