Skip to content
svgbrushabledensity-2d

2-D density contours

What is the smooth joint shape of two variables — how many modes, which direction?

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

How to read it

  1. Read the bands like a contour map: each inner band is denser than the one around it.
  2. Count the separate peaks: each may be a distinct group.
  3. Read each band's orientation for how the two variables move together inside that group.
  1. Callout 1: The innermost band: the top of this hill.
  2. Callout 2: A second hill: a second cluster of rows.
  3. 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

  • R uses MASS::kde2d (ships with R); Python ports it so both grids and contour levels match the app.