svgpair-plot
Pair plot
How do several numeric variables relate to each other at once?
How to read it
- Read the diagonal for each variable's distribution.
- Read the lower triangle for pairs as scatter plots.
- Read the upper triangle for correlations, overall and within each group.
- Callout 1: Diagonal: one variable's distribution.
- Callout 2: Lower triangle: one pair as a scatter.
- Callout 3: Upper triangle: the correlation for that pair.
Watch out
- A pair plot hides relationships among three or more variables, and many panels invite false patterns.
Defaults
- Diagonal bin rule
- Sturges
- How the histograms on the diagonal choose their bin width.
- Also: Freedman–Diaconis · Scott · Rice · Square root · Doane
Pinned in the code
- Lower panels: var(column) on x against var(row) on y, each axis min–max scaled within the panel; rows thinned by a deterministic stride to a 4,000-point budget.
- Upper panels: Pearson r over pairwise-complete rows (all rows, not the thinned sample), and per colour group when a colour is set (GGally `ggpairs` style); cells tinted on the diverging ramp.
- Diagonal: equal-width histograms ([a, b), last bin closed); per-group outlines share the overall bin edges.
# Pair plot — Codesplash Chart Lab (recipe "pair-plot")
# controls: bins=sturges
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
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("pair-plot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["species"] = pd.Categorical(df["species"].astype("string"), categories=["Adelie", "Chinstrap", "Gentoo"])
def freq_levels(s, k=8):
"""Declared level order when the column is categorical, else by descending count (ties A→Z)."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [str(v) for v in s.cat.categories][:k]
vc = s.dropna().astype(str).value_counts()
return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
def stride(frame, k):
if len(frame) <= k:
return frame
return frame.iloc[np.floor(np.arange(k) * len(frame) / k).astype(int)]
VARS = ["bill_length_mm", "bill_depth_mm", "flipper_length_mm", "body_mass_g"]
LEVELS = freq_levels(df["species"])
per_panel = int(np.ceil(4000 / max(1, len(VARS) * (len(VARS) - 1) // 2))) # the app's 4,000-point budget
def lower(x, y, **kw):
pts = stride(pd.DataFrame({"x": x, "y": y}).dropna(), per_panel) # deterministic stride
g = stride(df.loc[pd.DataFrame({"x": x, "y": y}).dropna().index, "species"].astype(str), per_panel)
plt.scatter(pts["x"], pts["y"], s=8, alpha=0.7, c=[PALETTE[LEVELS.index(v) % len(PALETTE)] if v in LEVELS else PALETTE[7] for v in g], edgecolors="none")
def upper(x, y, **kw):
ax = plt.gca()
both = pd.DataFrame({"x": x, "y": y}).dropna() # Pearson r over pairwise-complete rows (all rows)
lines = [f"r = {both['x'].corr(both['y']):.2f}"]
g = df.loc[both.index, "species"].astype(str)
for lv in LEVELS:
sub = both[g == lv]
if len(sub) > 2:
lines.append(f"{lv}: {sub['x'].corr(sub['y']):.2f}")
ax.text(0.5, 0.5, "\n".join(lines), transform=ax.transAxes, ha="center", va="center", fontsize=9)
ax.grid(False)
def diag(x, **kw):
v = x.dropna().to_numpy(dtype=float)
plt.hist(v, bins=np.histogram_bin_edges(v, bins="sturges"), color=PALETTE[0], alpha=0.8, edgecolor="white", linewidth=0.5)
grid = sns.PairGrid(df[VARS], height=1.8, diag_sharey=False)
grid.map_lower(lower)
grid.map_upper(upper)
grid.map_diag(diag)
plt.show()Needs pandas, numpy, matplotlib, seaborn · reads pair-plot-demo.csv · app theme from the optional codesplash helper
# Pair plot — Codesplash Chart Lab (recipe "pair-plot")
# controls: bins=sturges
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
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("pair-plot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["species"] = pd.Categorical(df["species"].astype("string"), categories=["Adelie", "Chinstrap", "Gentoo"])
def freq_levels(s, k=8):
"""Declared level order when the column is categorical, else by descending count (ties A→Z)."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [str(v) for v in s.cat.categories][:k]
vc = s.dropna().astype(str).value_counts()
return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
def stride(frame, k):
if len(frame) <= k:
return frame
return frame.iloc[np.floor(np.arange(k) * len(frame) / k).astype(int)]
VARS = ["bill_length_mm", "bill_depth_mm", "flipper_length_mm", "body_mass_g"]
k = len(VARS)
per_panel = int(np.ceil(4000 / max(1, k * (k - 1) // 2)))
fig = make_subplots(rows=k, cols=k, horizontal_spacing=0.02, vertical_spacing=0.02)
LEVELS = freq_levels(df["species"])
for i, vy in enumerate(VARS):
for j, vx in enumerate(VARS):
if i == j:
v = df[vx].dropna().to_numpy(dtype=float)
edges = np.histogram_bin_edges(v, bins="sturges")
counts, _ = np.histogram(v, edges)
fig.add_bar(x=(edges[:-1] + edges[1:]) / 2, y=counts, width=np.diff(edges), marker_color=PALETTE[0], showlegend=False, row=i + 1, col=j + 1)
elif i > j:
pts = stride(df[[vx, vy, "species"]].dropna(subset=[vx, vy]), per_panel)
fig.add_scatter(x=pts[vx], y=pts[vy], mode="markers", marker=dict(size=4, opacity=0.7, color=[PALETTE[LEVELS.index(v) % 8] if v in LEVELS else PALETTE[7] for v in pts["species"].astype(str)]), showlegend=False, row=i + 1, col=j + 1)
else:
both = df[[vx, vy]].dropna()
text = [f"r = {both[vx].corr(both[vy]):.2f}"]
g = df.loc[both.index, "species"].astype(str)
text += [f"{lv}: {both[g == lv][vx].corr(both[g == lv][vy]):.2f}" for lv in LEVELS if (g == lv).sum() > 2]
fig.add_annotation(text="<br>".join(text), showarrow=False, font_size=11, xref=f"x{i * k + j + 1} domain", yref=f"y{i * k + j + 1} domain", x=0.5, y=0.5)
if i == k - 1:
fig.update_xaxes(title_text=vx, row=i + 1, col=j + 1)
if j == 0:
fig.update_yaxes(title_text=vy, row=i + 1, col=j + 1)
fig.update_layout(bargap=0, height=180 * k, width=180 * k)
fig.show()Needs pandas, numpy, plotly · reads pair-plot-demo.csv · app theme from the optional codesplash helper
# Pair plot — Codesplash Chart Lab (recipe "pair-plot")
# controls: bins=sturges
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("pair-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["species"]] <- factor(df[["species"]], levels = c("Adelie", "Chinstrap", "Gentoo"))
np_edges <- function(x, rule = "fd", k = NULL) {
# numpy.histogram_bin_edges: equal-width edges from min to max (the app's convention)
n <- length(x); lo <- min(x); hi <- max(x); ptp <- hi - lo
if (is.null(k)) {
width <- switch(rule,
fd = 2 * IQR(x, type = 7) * n^(-1 / 3),
sturges = ptp / (log2(n) + 1),
scott = (24 * sqrt(pi) / n)^(1 / 3) * sqrt(mean((x - mean(x))^2)),
rice = ptp / (2 * n^(1 / 3)),
sqrt = ptp / sqrt(n),
doane = {
sg1 <- sqrt(6 * (n - 2) / ((n + 1) * (n + 3)))
g1 <- mean(((x - mean(x)) / sqrt(mean((x - mean(x))^2)))^3)
ptp / (1 + log2(n) + log2(1 + abs(g1) / sg1))
})
k <- if (is.finite(width) && width > 0) max(1, ceiling(ptp / width)) else 1
}
if (ptp == 0) return(c(lo - 0.5, hi + 0.5))
seq(lo, hi, length.out = k + 1)
}
stride <- function(frame, k) {
if (nrow(frame) <= k) return(frame)
frame[floor((seq_len(k) - 1) * nrow(frame) / k) + 1, , drop = FALSE]
}
freq_levels <- function(v, k = 8) {
# declared level order for factors with stored levels, else descending count (ties A→Z)
if (is.factor(v) && !is.null(attr(v, "cs_declared"))) return(utils::head(levels(v), k))
v <- as.character(v[!is.na(v)])
tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
attr(df[["species"]], "cs_declared") <- TRUE # stored level order
vars <- c("bill_length_mm", "bill_depth_mm", "flipper_length_mm", "body_mass_g")
k <- length(vars)
per_panel <- ceiling(4000 / max(1, k * (k - 1) / 2)) # the app's 4,000-point budget
fac <- function(v) factor(v, levels = vars)
# Lower panels: scatters; diagonal: histograms rescaled into the panel's y range; upper: Pearson r
pts <- do.call(rbind, lapply(seq_len(k), function(i) do.call(rbind, lapply(seq_len(k), function(j) {
if (i <= j) return(NULL)
s <- stride(df[stats::complete.cases(df[c(vars[j], vars[i])]), , drop = FALSE], per_panel)
data.frame(col = vars[j], row = vars[i], x = s[[vars[j]]], y = s[[vars[i]]], g = as.character(s[["species"]]))
}))))
bars <- do.call(rbind, lapply(vars, function(v) {
x <- df[[v]][is.finite(df[[v]])]
e <- np_edges(x, "sturges")
n <- as.vector(table(cut(x, e, right = FALSE, include.lowest = TRUE)))
data.frame(col = v, row = v, xmin = utils::head(e, -1), xmax = e[-1], ymin = min(x), ymax = min(x) + n / max(n) * diff(range(x)))
}))
rs <- do.call(rbind, lapply(seq_len(k), function(i) do.call(rbind, lapply(seq_len(k), function(j) {
if (i >= j) return(NULL)
r <- stats::cor(df[[vars[j]]], df[[vars[i]]], use = "pairwise.complete.obs")
by <- sapply(freq_levels(df[["species"]]), function(lv) { m <- as.character(df[["species"]]) %in% lv
sprintf("%s: %.2f", lv, stats::cor(df[[vars[j]]][m], df[[vars[i]]][m], use = "pairwise.complete.obs")) })
data.frame(col = vars[j], row = vars[i], x = mean(range(df[[vars[j]]], na.rm = TRUE)), y = mean(range(df[[vars[i]]], na.rm = TRUE)), label = paste(c(sprintf("r = %.2f", r), by), collapse = "\n"))
}))))
pts$col <- fac(pts$col); pts$row <- fac(pts$row); bars$col <- fac(bars$col); bars$row <- fac(bars$row)
rs$col <- fac(rs$col); rs$row <- fac(rs$row)
p <- ggplot() +
geom_point(data = pts, aes(x, y, colour = g), size = 0.8, alpha = 0.7) +
scale_colour_manual(values = cs_cat, name = "species") +
geom_rect(data = bars, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax), fill = cs_cat[1], colour = "white", linewidth = 0.2) +
geom_text(data = rs, aes(x, y, label = label), size = 3.5) +
facet_grid(row ~ col, scales = "free", switch = "both") +
labs(x = NULL, y = NULL) +
theme_cs + theme(strip.placement = "outside")
print(p)Needs ggplot2 · reads pair-plot-demo.csv · app theme from the optional codesplashr helper
-- Pair plot — Codesplash Chart Lab (recipe "pair-plot")
-- controls: bins=sturges
-- Pearson r for every pair over pairwise-complete rows (the upper panels); "group" NULL = all rows, else per species
SELECT 'bill_length_mm' AS a, 'bill_depth_mm' AS b, "species"::VARCHAR AS "group", corr("bill_length_mm", "bill_depth_mm") AS r, regr_count("bill_length_mm", "bill_depth_mm") AS n FROM read_csv('pair-plot-demo.csv') GROUP BY GROUPING SETS ((), ("species"))
UNION ALL
SELECT 'bill_length_mm' AS a, 'flipper_length_mm' AS b, "species"::VARCHAR AS "group", corr("bill_length_mm", "flipper_length_mm") AS r, regr_count("bill_length_mm", "flipper_length_mm") AS n FROM read_csv('pair-plot-demo.csv') GROUP BY GROUPING SETS ((), ("species"))
UNION ALL
SELECT 'bill_length_mm' AS a, 'body_mass_g' AS b, "species"::VARCHAR AS "group", corr("bill_length_mm", "body_mass_g") AS r, regr_count("bill_length_mm", "body_mass_g") AS n FROM read_csv('pair-plot-demo.csv') GROUP BY GROUPING SETS ((), ("species"))
UNION ALL
SELECT 'bill_depth_mm' AS a, 'flipper_length_mm' AS b, "species"::VARCHAR AS "group", corr("bill_depth_mm", "flipper_length_mm") AS r, regr_count("bill_depth_mm", "flipper_length_mm") AS n FROM read_csv('pair-plot-demo.csv') GROUP BY GROUPING SETS ((), ("species"))
UNION ALL
SELECT 'bill_depth_mm' AS a, 'body_mass_g' AS b, "species"::VARCHAR AS "group", corr("bill_depth_mm", "body_mass_g") AS r, regr_count("bill_depth_mm", "body_mass_g") AS n FROM read_csv('pair-plot-demo.csv') GROUP BY GROUPING SETS ((), ("species"))
UNION ALL
SELECT 'flipper_length_mm' AS a, 'body_mass_g' AS b, "species"::VARCHAR AS "group", corr("flipper_length_mm", "body_mass_g") AS r, regr_count("flipper_length_mm", "body_mass_g") AS n FROM read_csv('pair-plot-demo.csv') GROUP BY GROUPING SETS ((), ("species"));Needs duckdb · reads pair-plot-demo.csv