svgbrushablehist2d
2-D histogram
Where are two numeric variables jointly concentrated when there are too many points to plot?
How to read it
- Find the darkest cells: that is where most rows sit.
- Read the overall tilt of the dark area for the direction of the relationship.
- Check the colour bar: it tells you how many rows each shade means.
- Callout 1: Darkest cells: where most rows fall.
- Callout 2: Colour bar: rows per cell.
Watch out
- A linear colour scale hides sparse cells; try the log scale to see outliers.
- Cell size changes the picture. Try other bin counts before describing a pattern.
Defaults
- Bins (x)
- 30
- How many cells along the x axis.
- Range 5 to 200, step 1
- Bins (y)
- 20
- How many cells along the y axis.
- Range 5 to 200, step 1
- Colour scale
- Linear
- Linear shows the dense cells; log or square root reveals the sparse ones too.
- Also: log(1 + count)
Pinned in the code
- numpy `histogram2d(x, y, bins=[kx, ky])`: equal-width edges over [min, max] per axis, bins [a, b) with the last bin closed; rows with a missing coordinate are dropped.
- Colour: sequential ramp on count (or log(1 + count)); empty cells show the ramp's low end.
# 2-D histogram — Codesplash Chart Lab (recipe "hist2d")
# controls: binsX=30, binsY=20, scale=linear
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("hist2d-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)
d = df[["height_cm", "weight_kg"]].dropna()
H, xe, ye = np.histogram2d(d["height_cm"], d["weight_kg"], bins=[30, 20]) # equal-width edges over [min, max], [a, b) with the last closed
Z = H
fig, ax = plt.subplots(figsize=(7, 4.5))
mesh = ax.pcolormesh(xe, ye, Z.T, cmap=CMAP) # empty cells show the ramp's low end
fig.colorbar(mesh, ax=ax, label="count")
ax.grid(False)
ax.set_xlabel("height_cm")
ax.set_ylabel("weight_kg")
plt.show()Needs pandas, numpy, matplotlib · reads hist2d-demo.csv · app theme from the optional codesplash helper
# 2-D histogram — Codesplash Chart Lab (recipe "hist2d")
# controls: binsX=30, binsY=20, scale=linear
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("hist2d-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
d = df[["height_cm", "weight_kg"]].dropna()
H, xe, ye = np.histogram2d(d["height_cm"], d["weight_kg"], bins=[30, 20]) # equal-width edges over [min, max], [a, b) with the last closed
Z = H
fig = go.Figure(go.Heatmap(x=(xe[:-1] + xe[1:]) / 2, y=(ye[:-1] + ye[1:]) / 2, z=Z.T, colorscale=[[0, SEQ[0]], [1, SEQ[1]]],
customdata=H.T, hovertemplate="count %{customdata}<extra></extra>", colorbar=dict(title="count")))
fig.update_layout(xaxis_title="height_cm", yaxis_title="weight_kg")
fig.show()Needs pandas, numpy, plotly · reads hist2d-demo.csv · app theme from the optional codesplash helper
# 2-D histogram — Codesplash Chart Lab (recipe "hist2d")
# controls: binsX=30, binsY=20, scale=linear
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("hist2d-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
d <- df[is.finite(df[["height_cm"]]) & is.finite(df[["weight_kg"]]), , drop = FALSE]
edges <- function(v, k) { r <- range(v); if (r[1] == r[2]) r <- r + c(-0.5, 0.5); seq(r[1], r[2], length.out = k + 1) } # numpy histogram2d edges
xe <- edges(d[["height_cm"]], 30); ye <- edges(d[["weight_kg"]], 20)
ix <- findInterval(d[["height_cm"]], xe, rightmost.closed = TRUE, all.inside = TRUE) # [a, b), last bin closed
iy <- findInterval(d[["weight_kg"]], ye, rightmost.closed = TRUE, all.inside = TRUE)
cells <- as.data.frame(table(ix = factor(ix, levels = seq_len(30)), iy = factor(iy, levels = seq_len(20))), responseName = "count")
cells$ix <- as.integer(cells$ix); cells$iy <- as.integer(cells$iy)
cells <- transform(cells, x0 = xe[ix], x1 = xe[ix + 1], y0 = ye[iy], y1 = ye[iy + 1])
p <- ggplot(cells, aes(xmin = x0, xmax = x1, ymin = y0, ymax = y1, fill = count)) +
geom_rect() + # empty cells show the ramp's low end
scale_fill_gradient(low = seq_cols[1], high = seq_cols[2], name = "count") +
labs(x = "height_cm", y = "weight_kg") + theme_cs
print(p)Needs ggplot2 · reads hist2d-demo.csv · app theme from the optional codesplashr helper
-- 2-D histogram — Codesplash Chart Lab (recipe "hist2d")
-- controls: binsX=30, binsY=20, scale=linear
-- numpy histogram2d(x, y, bins=[30, 20]): equal-width edges over [min, max] per axis, bins [a, b) with the
-- last one closed; rows with a missing coordinate are dropped; empty cells have no row
WITH v AS (
SELECT "height_cm"::DOUBLE AS x, "weight_kg"::DOUBLE AS y
FROM read_csv('hist2d-demo.csv')
WHERE "height_cm" IS NOT NULL AND "weight_kg" IS NOT NULL AND isfinite("height_cm"::DOUBLE) AND isfinite("weight_kg"::DOUBLE)
),
s AS (SELECT min(x) AS x0, max(x) AS x1, min(y) AS y0, max(y) AS y1 FROM v),
b AS (
SELECT least(floor((x - x0) / (x1 - x0) * 30), 29)::INTEGER AS ix,
least(floor((y - y0) / (y1 - y0) * 20), 19)::INTEGER AS iy
FROM v, s
)
SELECT ix, iy,
x0 + ix * (x1 - x0) / 30 AS x_lo, x0 + (ix + 1) * (x1 - x0) / 30 AS x_hi,
y0 + iy * (y1 - y0) / 20 AS y_lo, y0 + (iy + 1) * (y1 - y0) / 20 AS y_hi,
count(*) AS count
FROM b, s
GROUP BY ix, iy, x0, x1, y0, y1
ORDER BY ix, iy;Needs duckdb · reads hist2d-demo.csv