Skip to content
svgbrushablescatter-marginal

Scatter with marginals

How do two variables relate, and how is each distributed?

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

How to read it

  1. Read the scatter for the relationship.
  2. Read the top and right panels for each variable on its own.
  3. Check whether a hump in a marginal lines up with a cluster in the scatter.
  1. Callout 1: The scatter: the two variables together.
  2. Callout 2: Top panel: the x variable on its own.
  3. 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