svgbrushablescatter-marginal
Scatter with marginals
How do two variables relate, and how is each distributed?
How to read it
- Read the scatter for the relationship.
- Read the top and right panels for each variable on its own.
- Check whether a hump in a marginal lines up with a cluster in the scatter.
- Callout 1: The scatter: the two variables together.
- Callout 2: Top panel: the x variable on its own.
- Callout 3: Right panel: the y variable on its own.
Watch out
- A marginal cannot show what happens jointly: two clusters can share the same marginal shape.
Defaults
- Marginals
- Histogram
- What to draw on the top and right edges.
- Also: Density (by colour)
- Bin rule
- Freedman–Diaconis
- How the bin width is chosen. Freedman–Diaconis resists outliers; Sturges suits small, near-normal data.
- Also: Sturges · Scott · Rice · Square root · Doane
- Bandwidth rule
- nrd0 (Silverman, R default)
- The rule that sets how much the curve is smoothed. Scott and Silverman suit one-humped data.
- Also: nrd (Scott variant) · Scott (scipy default)
- Fit
- None
- Add a straight-line (OLS) or flexible (LOESS) trend line.
- Also: OLS + 95% CI
- Point radius
- 2.5
- The size of each point.
- Range 1 to 5, step 0.5
Pinned in the code
- Marginal histograms use numpy-style equal-width bins over each variable's [min, max] ([a, b), last bin closed) with the chosen rule.
- Density marginals: Gaussian KDE per colour group (bandwidth rule as chosen), each scaled by its group share so the curves add up to the overall density (seaborn `jointplot(kind="kde", common_norm=True)`).
- Marginals share the scatter's axes; rows missing x or y are dropped everywhere.
# Scatter with marginals — Codesplash Chart Lab (recipe "scatter-marginal")
# controls: marginal=histogram, bins=fd, bandwidth=nrd0, fit=none, size=2.5
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]
df = pd.read_csv("scatter-marginal-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"])
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
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 bandwidth(v, rule="nrd0"):
"""R bw.nrd0 / bw.nrd, or scipy's Scott rule — as the app computes it."""
v = np.asarray(v, dtype=float)
n, sd = v.size, v.std(ddof=1)
iqr = np.subtract(*np.percentile(v, [75, 25]))
if rule == "scott":
return sd * n ** (-1 / 5)
lo = min(sd, iqr / 1.34) or sd or abs(v[0]) or 1.0
return (0.9 if rule == "nrd0" else 1.06) * lo * n ** (-1 / 5)
d = df.dropna(subset=["bill_length_mm", "flipper_length_mm"]) # rows missing x or y are dropped everywhere
xv = d["bill_length_mm"].to_numpy(dtype=float)
yv = d["flipper_length_mm"].to_numpy(dtype=float)
groups = [(lv, (d["species"].astype(str) == lv).to_numpy(), PALETTE[i % len(PALETTE)]) for i, lv in enumerate(freq_levels(d["species"]))]
fig = plt.figure(figsize=(7, 6))
gs = fig.add_gridspec(2, 2, width_ratios=(4, 1), height_ratios=(1, 4), hspace=0.05, wspace=0.05)
ax = fig.add_subplot(gs[1, 0])
top = fig.add_subplot(gs[0, 0], sharex=ax)
right = fig.add_subplot(gs[1, 1], sharey=ax)
for i, (lv, m, col) in enumerate(groups): # marker shape per group, as in the app
ax.scatter(xv[m], yv[m], s=14.0625, color=col, marker=SERIES_MARKERS[i % 8], alpha=0.75, edgecolors="none", label=lv)
# numpy-style equal-width bins over each variable's [min, max] ([a, b), last bin closed)
top.hist(xv, bins=np.histogram_bin_edges(xv, bins="fd"), color=PALETTE[0], alpha=0.8, edgecolor="white", linewidth=0.5)
right.hist(yv, bins=np.histogram_bin_edges(yv, bins="fd"), color=PALETTE[0], alpha=0.8, edgecolor="white", linewidth=0.5, orientation="horizontal")
top.axis("off")
right.axis("off")
ax.set_xlabel("bill_length_mm")
ax.set_ylabel("flipper_length_mm")
ax.legend(title="species", fontsize=8)
plt.show()Needs pandas, numpy, matplotlib, scipy · reads scatter-marginal-demo.csv · app theme from the optional codesplash helper
# Scatter with marginals — Codesplash Chart Lab (recipe "scatter-marginal")
# controls: marginal=histogram, bins=fd, bandwidth=nrd0, fit=none, size=2.5
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from scipy import stats
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
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
df = pd.read_csv("scatter-marginal-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 bandwidth(v, rule="nrd0"):
"""R bw.nrd0 / bw.nrd, or scipy's Scott rule — as the app computes it."""
v = np.asarray(v, dtype=float)
n, sd = v.size, v.std(ddof=1)
iqr = np.subtract(*np.percentile(v, [75, 25]))
if rule == "scott":
return sd * n ** (-1 / 5)
lo = min(sd, iqr / 1.34) or sd or abs(v[0]) or 1.0
return (0.9 if rule == "nrd0" else 1.06) * lo * n ** (-1 / 5)
d = df.dropna(subset=["bill_length_mm", "flipper_length_mm"])
xv = d["bill_length_mm"].to_numpy(dtype=float)
yv = d["flipper_length_mm"].to_numpy(dtype=float)
groups = [(lv, (d["species"].astype(str) == lv).to_numpy(), PALETTE[i % len(PALETTE)]) for i, lv in enumerate(freq_levels(d["species"]))]
fig = make_subplots(rows=2, cols=2, column_widths=[0.8, 0.2], row_heights=[0.2, 0.8], shared_xaxes=True, shared_yaxes=True, horizontal_spacing=0.01, vertical_spacing=0.01)
for i, (lv, m, col) in enumerate(groups): # marker shape per group, as in the app
fig.add_scatter(x=xv[m], y=yv[m], mode="markers", name=lv, marker=dict(color=col, symbol=SERIES_MARKERS[i % 8], size=5, opacity=0.75), row=2, col=1)
ex, ey = np.histogram_bin_edges(xv, bins="fd"), np.histogram_bin_edges(yv, bins="fd") # numpy edges, [a, b)
cx, _ = np.histogram(xv, ex)
cy, _ = np.histogram(yv, ey)
fig.add_bar(x=(ex[:-1] + ex[1:]) / 2, y=cx, width=np.diff(ex), marker_color=PALETTE[0], showlegend=False, row=1, col=1)
fig.add_bar(y=(ey[:-1] + ey[1:]) / 2, x=cy, width=np.diff(ey), orientation="h", marker_color=PALETTE[0], showlegend=False, row=2, col=2)
fig.update_layout(bargap=0, xaxis3_title="bill_length_mm", yaxis3_title="flipper_length_mm")
fig.show()Needs pandas, numpy, plotly, scipy · reads scatter-marginal-demo.csv · app theme from the optional codesplash helper
# Scatter with marginals — Codesplash Chart Lab (recipe "scatter-marginal")
# controls: marginal=histogram, bins=fd, bandwidth=nrd0, fit=none, size=2.5
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))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("scatter-marginal-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"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
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)
}
bandwidth <- function(v, rule = "nrd0") {
switch(rule, nrd0 = bw.nrd0(v), nrd = bw.nrd(v), scott = sd(v) * length(v)^(-1 / 5))
}
arrange <- function(plots, layout, widths = NULL, heights = NULL) {
# layout: matrix of plot indices (NA = empty cell). patchwork aligns the panels when it is
# installed; otherwise base grid viewports place the plots (axes may not line up exactly).
widths <- if (is.null(widths)) rep(1, ncol(layout)) else widths
heights <- if (is.null(heights)) rep(1, nrow(layout)) else heights
if (requireNamespace("patchwork", quietly = TRUE)) {
design <- paste(apply(layout, 1, function(r) paste(ifelse(is.na(r), "#", LETTERS[r]), collapse = "")), collapse = "\n")
print(patchwork::wrap_plots(plots, design = design, widths = widths, heights = heights, guides = "collect"))
return(invisible())
}
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(nrow(layout), ncol(layout),
widths = grid::unit(widths, "null"), heights = grid::unit(heights, "null"))))
for (i in seq_along(plots)) {
at <- which(layout == i, arr.ind = TRUE)
print(plots[[i]], vp = grid::viewport(layout.pos.row = unique(at[, 1]), layout.pos.col = unique(at[, 2])))
}
}
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
d <- df[!is.na(df[["bill_length_mm"]]) & !is.na(df[["flipper_length_mm"]]), , drop = FALSE] # rows missing x or y are dropped everywhere
xr <- range(d[["bill_length_mm"]]); yr <- range(d[["flipper_length_mm"]])
main <- ggplot(d, aes(x = .data[["bill_length_mm"]], y = .data[["flipper_length_mm"]])) +
geom_point(aes(colour = .data[["species"]], shape = .data[["species"]]), size = 1.5, alpha = 0.75) + # shape per group, as in the app
scale_colour_manual(values = cs_cat, name = "species") + scale_shape_manual(values = cs_shapes, name = "species") +
coord_cartesian(xlim = xr, ylim = yr) +
labs(x = "bill_length_mm", y = "flipper_length_mm") + theme_cs
bx <- np_edges(d[["bill_length_mm"]], "fd"); by <- np_edges(d[["flipper_length_mm"]], "fd") # numpy edges, [a, b)
top <- ggplot(d, aes(.data[["bill_length_mm"]])) + geom_histogram(breaks = bx, closed = "left", fill = cs_cat[1], colour = "white") +
coord_cartesian(xlim = xr) + theme_void()
right <- ggplot(d, aes(.data[["flipper_length_mm"]])) + geom_histogram(breaks = by, closed = "left", fill = cs_cat[1], colour = "white") +
coord_flip(xlim = yr) + theme_void()
arrange(list(top, main, right), layout = matrix(c(1, NA, 2, 3), 2, byrow = TRUE), widths = c(4, 1), heights = c(1, 4))Needs ggplot2 · reads scatter-marginal-demo.csv · app theme from the optional codesplashr helper
-- Scatter with marginals — Codesplash Chart Lab (recipe "scatter-marginal")
-- controls: marginal=histogram, bins=fd, bandwidth=nrd0, fit=none, size=2.5
-- marginal histograms: numpy-style equal-width bins over each variable's [min, max]
-- "group" NULL = all rows; per-species counts share the overall edges
(
WITH v AS (SELECT "bill_length_mm"::DOUBLE AS x, "species"::VARCHAR AS grp FROM read_csv('scatter-marginal-demo.csv') WHERE "bill_length_mm" IS NOT NULL AND isfinite("bill_length_mm"::DOUBLE)),
s AS (SELECT min(x) AS lo, max(x) AS hi, count(*) AS n, quantile_cont(x, 0.75) - quantile_cont(x, 0.25) AS iqr,
stddev_pop(x) AS sd0, skewness(x) AS g1 FROM v),
k AS (SELECT lo, hi, n, coalesce(greatest(1, ceil((hi - lo) / NULLIF(2 * iqr * pow(n, -1.0 / 3), 0)))::INTEGER, 1) AS k FROM s),
b AS (SELECT least(floor((x - lo) / NULLIF((hi - lo) / k, 0)), k - 1)::INTEGER AS bin, grp FROM v, k)
SELECT 'bill_length_mm' AS variable, grp AS "group", coalesce(bin, 0) AS bin,
lo + coalesce(bin, 0) * (hi - lo) / k AS x0, lo + (coalesce(bin, 0) + 1) * (hi - lo) / k AS x1, count(*) AS count
FROM b, k GROUP BY GROUPING SETS ((bin, lo, hi, k), (grp, bin, lo, hi, k))
)
UNION ALL
(
WITH v AS (SELECT "flipper_length_mm"::DOUBLE AS x, "species"::VARCHAR AS grp FROM read_csv('scatter-marginal-demo.csv') WHERE "flipper_length_mm" IS NOT NULL AND isfinite("flipper_length_mm"::DOUBLE)),
s AS (SELECT min(x) AS lo, max(x) AS hi, count(*) AS n, quantile_cont(x, 0.75) - quantile_cont(x, 0.25) AS iqr,
stddev_pop(x) AS sd0, skewness(x) AS g1 FROM v),
k AS (SELECT lo, hi, n, coalesce(greatest(1, ceil((hi - lo) / NULLIF(2 * iqr * pow(n, -1.0 / 3), 0)))::INTEGER, 1) AS k FROM s),
b AS (SELECT least(floor((x - lo) / NULLIF((hi - lo) / k, 0)), k - 1)::INTEGER AS bin, grp FROM v, k)
SELECT 'flipper_length_mm' AS variable, grp AS "group", coalesce(bin, 0) AS bin,
lo + coalesce(bin, 0) * (hi - lo) / k AS x0, lo + (coalesce(bin, 0) + 1) * (hi - lo) / k AS x1, count(*) AS count
FROM b, k GROUP BY GROUPING SETS ((bin, lo, hi, k), (grp, bin, lo, hi, k))
)
ORDER BY variable, "group" NULLS FIRST, bin;Needs duckdb · reads scatter-marginal-demo.csv