Skip to content
svgbrushablemosaic

Mosaic plot

Are two categorical variables associated — and which cells drive it?

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

How to read it

  1. Read column width as the size of each column level.
  2. Read the heights inside a column as the row shares for that level.
  3. Use the colours: strong shades mark cells far from what independence predicts.
  1. Callout 1: A strongly shaded cell: many more rows than independence predicts.
  2. Callout 2: Same column, lower row: fewer than predicted.
  3. Callout 3: Pale cells: close to what independence predicts.

Watch out

  • Residual shading depends on sample size, so large tables shade strongly for small differences.

Defaults

Shading
Pearson residuals
Whether to shade cells by their standardized residual or by level.
Also: Standardized residuals · Row levels
Percent labels
On
Print each segment's share.
Column levels
8
How many column levels to show; the rest are grouped.
Range 2 to 12, step 1

Pinned in the code

  • Column widths ∝ the column variable's marginal counts; tile heights ∝ the conditional share of each row level within the column (Hartigan & Kleiner 1981).
  • Pearson residuals rᵢⱼ = (oᵢⱼ − eᵢⱼ)/√eᵢⱼ with eᵢⱼ = rowᵢ·colⱼ/n (R `chisq.test()$residuals`); standardized residuals divide by √(eᵢⱼ(1 − rowᵢ/n)(1 − colⱼ/n)) (`$stdres`).
  • Shading follows vcd's cut-offs: |r| < 2 neutral, 2–4 medium, ≥ 4 strong; blue = more than expected, orange-red = fewer. χ² is Pearson's without continuity correction.
  • Row-level labels sit at the marginal shares (spine-plot convention); percent labels are shares within the column.
# Mosaic plot — Codesplash Chart Lab (recipe "mosaic")
# controls: shading=pearson, labels=true, top=8
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

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("mosaic-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["class"] = pd.Categorical(df["class"].astype("string"), categories=["1st", "2nd", "3rd", "Crew"])
df["outcome"] = pd.Categorical(df["outcome"].astype("string"), categories=["Survived", "Died"])

def levels(s):
    """Level order like the app: declared order (categorical dtype), else by descending frequency, ties alphabetical."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(c) for c in s.cat.categories]
    counts = s.dropna().astype(str).value_counts()
    return sorted(counts.index, key=lambda k: (-counts[k], k))

def crosstab(frame, a, b, max_a, max_b):
    """a × b counts (rows with a missing value dropped); levels beyond the caps pool into "Other", kept last."""
    d = frame[[a, b]].dropna()
    pooled, cats = {}, []
    for col, cap in ((a, max_a), (b, max_b)):
        lv = levels(frame[col])
        keep = lv[:cap]
        v = d[col].astype(str)
        pooled[col] = v.where(v.isin(keep), "Other")
        cats.append(keep + (["Other"] if len(lv) > cap else []))
    tab = pd.crosstab(pd.Categorical(pooled[a], categories=cats[0]), pd.Categorical(pooled[b], categories=cats[1]), dropna=False)
    tab.index, tab.columns = pd.Index(cats[0], name=a), pd.Index(cats[1], name=b)
    return tab

tab = crosstab(df, "class", "outcome", 8, 6)  # columns of the mosaic × rows within them
o = tab.to_numpy(dtype=float)
n, rt, ct = o.sum(), o.sum(axis=1), o.sum(axis=0)
e = np.outer(rt, ct) / n  # expected counts under independence
with np.errstate(divide="ignore", invalid="ignore"):
    resid = np.where(e > 0, (o - e) / np.sqrt(e), 0)  # Pearson residuals, chisq.test()$residuals
    pearson = np.where(e > 0, (o - e) / np.sqrt(e), 0)
chi2 = (pearson ** 2).sum()  # Pearson χ², no continuity correction
dof = max(0, (np.count_nonzero(rt) - 1) * (np.count_nonzero(ct) - 1))
SHADES = ["#c13e2e", "#df9489", "#f3f5f8", "#799fd1", "#0859ac"]  # r ≤ −4, −4…−2, |r| < 2, 2…4, ≥ 4 (vcd cut-offs)
def shade(r):
    s = 2 if abs(r) >= 4 else 1 if abs(r) >= 2 else 0
    return SHADES[2 + int(np.sign(r)) * s]
GAP = 0.012
widths = rt / n * (1 - GAP * (len(rt) - 1))  # column widths ∝ the column variable's margins
lefts = np.concatenate([[0], np.cumsum(widths + GAP)[:-1]])
tiles = []  # (i, j, x, y, w, h) with y measured from the top
for i in range(len(rt)):
    usable = 1 - GAP * (len(ct) - 1)
    top = 0.0
    for j in range(len(ct)):
        h = o[i, j] / rt[i] * usable if rt[i] else 0  # heights ∝ the share within the column
        tiles.append((i, j, lefts[i], top, widths[i], h))
        top += h + GAP

from matplotlib.patches import Patch, Rectangle
fig, ax = plt.subplots(figsize=(8, 5))
for i, j, x0, y0, w, h in tiles:
    color = shade(resid[i, j])
    ax.add_patch(Rectangle((x0, 1 - y0 - h), w, h, facecolor=color, edgecolor="white", linewidth=0.5))
    if w > 0.05 and h > 0.05:
        ax.text(x0 + w / 2, 1 - y0 - h / 2, f"{o[i, j] / rt[i]:.0%}", ha="center", va="center", fontsize=7)
ax.set_xticks(lefts + widths / 2, list(tab.index))
marg = ct / n  # row-level labels at the marginal shares (spine-plot convention)
ax.set_yticks(1 - (np.cumsum(marg) - marg / 2), list(tab.columns))
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.grid(False)
ax.set_xlabel("class")
ax.set_ylabel("outcome")
ax.legend(handles=[Patch(color=s, label=l) for s, l in zip(SHADES, ["r ≤ −4", "−4 < r ≤ −2", "|r| < 2", "2 ≤ r < 4", "r ≥ 4"])],
          title=f"χ²({dof}) = {chi2:.1f}", loc="upper left", bbox_to_anchor=(1.01, 1))
plt.show()

Needs pandas, numpy, matplotlib · reads mosaic-demo.csv · app theme from the optional codesplash helper