svgbrushablehexbin
Hexbin
Where do many points concentrate in two dimensions, without the square-bin artefacts?
How to read it
- Find the darkest hexagons: the densest part of the data.
- Read the shape the hexagons trace for the relationship.
- Look for isolated light hexagons far from the main cloud: rare combinations worth checking.
- Callout 1: Darkest hexagons: the most rows.
- Callout 2: Isolated hexagons: rare combinations.
- Callout 3: Colour bar: rows per hexagon.
Watch out
- Without the log scale a few dense hexagons can wash out everything else.
Defaults
- Hexes across
- 30
- How many hexagons span the width: more gives finer detail and more noise.
- Range 8 to 80, step 1
- Log colour scale
- On
- Colour by the logarithm of the count, so sparse areas stay visible.
Pinned in the code
- Lattice of matplotlib `hexbin(gridsize = nx)`: ny = ⌊nx/√3⌋, two offset rectangular lattices; each point goes to the nearer centre under (Δx)² + 3(Δy)² in grid units; x padded by 1e−9 of the range.
- Pointy-top hexagons with vertices at (±sx/2, ±sy/6) and (0, ±sy/3) in data units; empty hexes are not drawn (mincnt = 1).
- Colour: sequential ramp on count or log(1 + count).
# Hexbin — Codesplash Chart Lab (recipe "hexbin")
# controls: gridsize=30, log=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("hexbin-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[["distance_km", "fare_usd"]].dropna()
fig, ax = plt.subplots(figsize=(7, 4.5))
# matplotlib's own hexbin lattice — the app reproduces it; empty hexes are not drawn (mincnt=1)
hb = ax.hexbin(d["distance_km"], d["fare_usd"], gridsize=30, mincnt=1, bins="log", cmap=CMAP,
linewidths=0.2, edgecolors=plt.rcParams["axes.facecolor"])
fig.colorbar(hb, ax=ax, label="count (log scale)")
ax.grid(False)
ax.set_xlabel("distance_km")
ax.set_ylabel("fare_usd")
plt.show()Needs pandas, numpy, matplotlib · reads hexbin-demo.csv · app theme from the optional codesplash helper
# Hexbin — Codesplash Chart Lab (recipe "hexbin")
# controls: gridsize=30, log=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("hexbin-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
def hexbin_cells(x, y, nx):
"""matplotlib's hexbin lattice (what the app reproduces): ny = ⌊nx/√3⌋, two offset rectangular
lattices, each point goes to the nearer centre under (Δx)² + 3(Δy)² in grid units."""
ny = max(1, int(nx / np.sqrt(3)))
xmin, xmax, ymin, ymax = x.min(), x.max(), y.min(), y.max()
pad = 1e-9 * (xmax - xmin)
xmin, xmax = xmin - pad, xmax + pad
sx, sy = (xmax - xmin) / nx, (ymax - ymin) / ny
ix, iy = (x - xmin) / sx, (y - ymin) / sy
ix1, iy1, ix2, iy2 = np.round(ix), np.round(iy), np.floor(ix), np.floor(iy)
first = (ix - ix1) ** 2 + 3 * (iy - iy1) ** 2 < (ix - ix2 - 0.5) ** 2 + 3 * (iy - iy2 - 0.5) ** 2
cx = np.where(first, xmin + ix1 * sx, xmin + (ix2 + 0.5) * sx)
cy = np.where(first, ymin + iy1 * sy, ymin + (iy2 + 0.5) * sy)
cells = pd.DataFrame({"x": cx, "y": cy}).value_counts().reset_index(name="count")
return cells, sx, sy
def ramp(t):
"""A colour on the sequential ramp, t in [0, 1] (interpolated in RGB)."""
a, b = np.array(px.colors.hex_to_rgb(SEQ[0])), np.array(px.colors.hex_to_rgb(SEQ[1]))
r, g, bl = (a + (b - a) * min(max(t, 0.0), 1.0)).round().astype(int)
return f"rgb({r}, {g}, {bl})"
SEQ = cs.palette(dark=False)["sequential"] if cs else ["#eff6fd", "#1a469d"] # the app's sequential ramp
d = df[["distance_km", "fare_usd"]].dropna()
cells, sx, sy = hexbin_cells(d["distance_km"].to_numpy(dtype=float), d["fare_usd"].to_numpy(dtype=float), 30)
z = np.log1p(cells["count"]) # log(1 + count)
# plotly has no hexbin trace: draw pointy-top hexagons, one filled trace per colour step of the ramp
hx = np.array([0.5, 0.5, 0, -0.5, -0.5, 0, 0.5]) * sx
hy = np.array([-1, 1, 2, 1, -1, -2, -1]) * sy / 6
steps = 9
level = np.minimum((z / z.max() * steps).astype(int), steps - 1)
fig = go.Figure()
for k in range(steps):
sel = cells[level == k]
if sel.empty:
continue
xs = np.concatenate([np.r_[cx + hx, np.nan] for cx in sel["x"]])
ys = np.concatenate([np.r_[cy + hy, np.nan] for cy in sel["y"]])
fig.add_scatter(x=xs, y=ys, mode="lines", fill="toself", fillcolor=ramp((k + 0.5) / steps), line=dict(width=0), hoverinfo="skip", showlegend=False)
fig.add_scatter(x=cells["x"], y=cells["y"], mode="markers", marker=dict(size=4, opacity=0, color=z, colorscale=[[0, SEQ[0]], [1, SEQ[1]]], showscale=True,
colorbar=dict(title="log(1 + count)")), customdata=cells["count"], hovertemplate="count %{customdata}<extra></extra>", showlegend=False)
fig.update_layout(xaxis_title="distance_km", yaxis_title="fare_usd")
fig.show()Needs pandas, numpy, plotly · reads hexbin-demo.csv · app theme from the optional codesplash helper
# Hexbin — Codesplash Chart Lab (recipe "hexbin")
# controls: gridsize=30, log=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("hexbin-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
hex_cells <- function(x, y, nx) {
# matplotlib's hexbin lattice (the app reproduces it): ny = floor(nx / sqrt(3)), two offset lattices,
# each point goes to the nearer centre under dx^2 + 3 dy^2 in grid units; round() is half-to-even like numpy
ny <- max(1, floor(nx / sqrt(3)))
xmin <- min(x); xmax <- max(x); ymin <- min(y); ymax <- max(y)
pad <- 1e-9 * (xmax - xmin); xmin <- xmin - pad; xmax <- xmax + pad
sx <- (xmax - xmin) / nx; sy <- (ymax - ymin) / ny
ix <- (x - xmin) / sx; iy <- (y - ymin) / sy
first <- (ix - round(ix))^2 + 3 * (iy - round(iy))^2 < (ix - floor(ix) - 0.5)^2 + 3 * (iy - floor(iy) - 0.5)^2
cx <- ifelse(first, xmin + round(ix) * sx, xmin + (floor(ix) + 0.5) * sx)
cy <- ifelse(first, ymin + round(iy) * sy, ymin + (floor(iy) + 0.5) * sy)
cells <- aggregate(list(count = rep(1, length(cx))), list(x = cx, y = cy), sum)
list(cells = cells, sx = sx, sy = sy)
}
d <- df[is.finite(df[["distance_km"]]) & is.finite(df[["fare_usd"]]), , drop = FALSE]
hb <- hex_cells(d[["distance_km"]], d[["fare_usd"]], 30)
cells <- hb$cells
# pointy-top hexagons: vertices at (+-sx/2, +-sy/6) and (0, +-sy/3)
hexes <- data.frame(id = rep(seq_len(nrow(cells)), each = 6), count = rep(cells$count, each = 6),
x = rep(cells$x, each = 6) + c(0.5, 0.5, 0, -0.5, -0.5, 0) * hb$sx,
y = rep(cells$y, each = 6) + c(-1, 1, 2, 1, -1, -2) * hb$sy / 6)
p <- ggplot(hexes, aes(x, y, group = id, fill = count)) +
geom_polygon() + # empty hexes are not drawn
scale_fill_gradient(low = seq_cols[1], high = seq_cols[2], transform = "log1p", name = "count (log scale)") +
labs(x = "distance_km", y = "fare_usd") + theme_cs
print(p)Needs ggplot2 · reads hexbin-demo.csv · app theme from the optional codesplashr helper
-- Hexbin — Codesplash Chart Lab (recipe "hexbin")
-- controls: gridsize=30, log=true
-- matplotlib hexbin lattice (gridsize 30): ny = ⌊nx/√3⌋, two offset rectangular lattices; each point goes to
-- the nearer centre under (Δx)² + 3(Δy)² in grid units (round_even = numpy's half-to-even rounding)
WITH v AS (
SELECT "distance_km"::DOUBLE AS x, "fare_usd"::DOUBLE AS y
FROM read_csv('hexbin-demo.csv')
WHERE "distance_km" IS NOT NULL AND "fare_usd" IS NOT NULL AND isfinite("distance_km"::DOUBLE) AND isfinite("fare_usd"::DOUBLE)
),
s AS (SELECT min(x) AS x0, max(x) AS x1, min(y) AS ymin, max(y) AS ymax FROM v),
g AS (
SELECT x0 - 1e-9 * (x1 - x0) AS xmin, ymin,
(x1 - x0) * (1 + 2e-9) / 30 AS sx,
(ymax - ymin) / greatest(1, floor(30 / sqrt(3))) AS sy
FROM s
),
p AS (SELECT (x - xmin) / sx AS ix, (y - ymin) / sy AS iy, xmin, ymin, sx, sy FROM v, g),
c AS (
SELECT *, pow(ix - round_even(ix, 0), 2) + 3 * pow(iy - round_even(iy, 0), 2)
< pow(ix - floor(ix) - 0.5, 2) + 3 * pow(iy - floor(iy) - 0.5, 2) AS first
FROM p
)
SELECT CASE WHEN first THEN xmin + round_even(ix, 0) * sx ELSE xmin + (floor(ix) + 0.5) * sx END AS cx,
CASE WHEN first THEN ymin + round_even(iy, 0) * sy ELSE ymin + (floor(iy) + 0.5) * sy END AS cy,
count(*) AS count, any_value(sx) AS sx, any_value(sy) AS sy
FROM c
GROUP BY ALL
ORDER BY cx, cy;Needs duckdb · reads hexbin-demo.csv
- matplotlib's hexbin is the reference the app reproduces. plotly has no hexbin trace, so hexagons are drawn as filled shapes in 9 colour steps; ggplot2 uses polygons (no hexbin package needed).
- Exact ties at a half-way grid position round half-to-even in numpy, R and the SQL (round_even), but half-up in the app — a point there can land in the neighbouring hex.