svgbrushablemosaic
Mosaic plot
Are two categorical variables associated — and which cells drive it?
How to read it
- Read column width as the size of each column level.
- Read the heights inside a column as the row shares for that level.
- Use the colours: strong shades mark cells far from what independence predicts.
- Callout 1: A strongly shaded cell: many more rows than independence predicts.
- Callout 2: Same column, lower row: fewer than predicted.
- 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
# Mosaic plot — Codesplash Chart Lab (recipe "mosaic")
# controls: shading=pearson, labels=true, top=8
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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("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
fig = go.Figure()
for j, level in enumerate(tab.columns):
sel = [t for t in tiles if t[1] == j]
fig.add_bar(
x=[t[2] + t[4] / 2 for t in sel], width=[t[4] for t in sel],
y=[t[5] for t in sel], base=[1 - t[3] - t[5] for t in sel],
marker_color=[shade(resid[t[0], j]) for t in sel], marker_line=dict(color="white", width=0.5),
name=str(level), text=[f"{o[t[0], j] / rt[t[0]]:.0%}" for t in sel], textposition="inside", showlegend=False,
customdata=[resid[t[0], j] for t in sel], hovertemplate=f"{level}<br>residual %{{customdata:.2f}}<extra></extra>")
fig.update_layout(barmode="overlay", bargap=0, title=f"χ²({dof}) = {chi2:.1f}",
xaxis=dict(tickvals=list(lefts + widths / 2), ticktext=list(tab.index), title="class", range=[0, 1]),
yaxis=dict(range=[0, 1], title="outcome", showticklabels=False))
fig.show()Needs pandas, numpy, plotly · reads mosaic-demo.csv · app theme from the optional codesplash helper
# Mosaic plot — Codesplash Chart Lab (recipe "mosaic")
# controls: shading=pearson, labels=true, top=8
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("mosaic-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["class"]] <- factor(df[["class"]], levels = c("1st", "2nd", "3rd", "Crew"))
df[["outcome"]] <- factor(df[["outcome"]], levels = c("Survived", "Died"))
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
crosstab <- function(a, b, la, lb, max_a, max_b) {
# a × b counts (rows with a missing value dropped); levels beyond the caps pool into "Other", kept last
ok <- !is.na(a) & !is.na(b)
pool <- function(v, lv, cap) {
keep <- head(lv, cap)
v <- as.character(v)
factor(ifelse(v %in% keep, v, "Other"), levels = c(keep, if (length(lv) > cap) "Other"))
}
table(category = pool(a[ok], la, max_a), group = pool(b[ok], lb, max_b))
}
tab <- crosstab(df[["class"]], df[["outcome"]], levels(df[["class"]]), levels(df[["outcome"]]), 8, 6)
o <- unclass(tab)
n <- sum(o); rt <- rowSums(o); ct <- colSums(o)
e <- outer(rt, ct) / n # expected counts under independence
resid <- ifelse(e > 0, (o - e) / sqrt(e), 0) # chisq.test()$residuals
chi2 <- sum(ifelse(e > 0, (o - e)^2 / e, 0)) # Pearson χ², no continuity correction
dof <- max(0, (sum(rt > 0) - 1) * (sum(ct > 0) - 1))
SHADES <- c("#c13e2e", "#df9489", "#f3f5f8", "#799fd1", "#0859ac")
CLASSES <- c("r ≤ −4", "−4 < r ≤ −2", "|r| < 2", "2 ≤ r < 4", "r ≥ 4") # vcd cut-offs
gap <- 0.012
widths <- rt / n * (1 - gap * (length(rt) - 1)) # column widths ∝ the column variable's margins
lefts <- c(0, cumsum(widths + gap))[seq_along(rt)]
tiles <- do.call(rbind, lapply(seq_along(rt), function(i) {
h <- if (rt[i] > 0) o[i, ] / rt[i] * (1 - gap * (length(ct) - 1)) else rep(0, length(ct))
top <- c(0, cumsum(h + gap))[seq_along(ct)] # heights ∝ the share within the column
r <- resid[i, ]
cls <- 3 + sign(r) * ifelse(abs(r) >= 4, 2, ifelse(abs(r) >= 2, 1, 0))
data.frame(col = names(rt)[i], row = colnames(o), xmin = lefts[i], xmax = lefts[i] + widths[i],
ymin = 1 - top - h, ymax = 1 - top, share = if (rt[i] > 0) o[i, ] / rt[i] else 0,
class = factor(CLASSES[cls], levels = CLASSES))
}))
tiles$row <- factor(tiles$row, levels = colnames(o))
marg <- ct / n # row-level labels at the marginal shares (spine-plot convention)
p <- ggplot(tiles) +
geom_rect(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = class), colour = "white", linewidth = 0.3) +
geom_text(aes(x = (xmin + xmax) / 2, y = (ymin + ymax) / 2, label = ifelse(xmax - xmin > 0.05 & ymax - ymin > 0.05, sprintf("%.0f%%", 100 * share), "")), size = 2.5) +
scale_fill_manual(values = setNames(SHADES, CLASSES), drop = FALSE, name = sprintf("χ²(%d) = %.1f", dof, chi2)) +
scale_x_continuous(breaks = lefts + widths / 2, labels = names(rt), expand = c(0, 0)) +
scale_y_continuous(breaks = 1 - (cumsum(marg) - marg / 2), labels = names(ct), expand = c(0, 0)) +
labs(x = "class", y = "outcome") +
theme_cs +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())
print(p)Needs ggplot2 · reads mosaic-demo.csv · app theme from the optional codesplashr helper
-- Mosaic plot — Codesplash Chart Lab (recipe "mosaic")
-- controls: shading=pearson, labels=true, top=8
-- contingency table with expected counts and Pearson / standardized residuals (R chisq.test conventions)
WITH
la(level, rk) AS (VALUES ('1st', 1), ('2nd', 2), ('3rd', 3), ('Crew', 4)),
lb(level, rk) AS (VALUES ('Survived', 1), ('Died', 2)),
t AS (
SELECT CASE WHEN la.rk <= 8 THEN la.level ELSE 'Other' END AS a,
CASE WHEN lb.rk <= 6 THEN lb.level ELSE 'Other' END AS b,
count(*) AS n, min(la.rk) AS ra, min(lb.rk) AS rb
FROM read_csv('mosaic-demo.csv') s
JOIN la ON la.level = s."class"::VARCHAR
JOIN lb ON lb.level = s."outcome"::VARCHAR
GROUP BY 1, 2
),
m AS (
SELECT a, b, n, ra, rb,
sum(n) OVER (PARTITION BY a) AS row_total,
sum(n) OVER (PARTITION BY b) AS col_total,
sum(n) OVER () AS total
FROM t
)
SELECT a AS "class", b AS "outcome", n,
row_total * col_total / total AS expected,
(n - row_total * col_total / total) / sqrt(row_total * col_total / total) AS pearson_residual,
(n - row_total * col_total / total)
/ sqrt(row_total * col_total / total * (1 - row_total / total) * (1 - col_total / total)) AS std_residual,
n / row_total AS share_within_column
FROM m
ORDER BY ra, rb;Needs duckdb · reads mosaic-demo.csv