Skip to content
svgpair-plot

Pair plot

How do several numeric variables relate to each other at once?

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

How to read it

  1. Read the diagonal for each variable's distribution.
  2. Read the lower triangle for pairs as scatter plots.
  3. Read the upper triangle for correlations, overall and within each group.
  1. Callout 1: Diagonal: one variable's distribution.
  2. Callout 2: Lower triangle: one pair as a scatter.
  3. 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