Mosaic plot with Pearson residuals
Tile areas proportional to cell counts, shaded by Pearson residuals from independence.

A mosaic plot draws a two-way table as a square cut into tiles. Column widths
are the marginal shares of the first variable, tile heights the conditional
shares of the second, so every tile's area is proportional to its count. As in
vcd::mosaic(shade = TRUE), the colour is the Pearson residual
(observed − expected) / √expected: blue tiles hold more tweets than independence
predicts, red tiles fewer, and residuals beyond ±2 or ±4 flag the cells that drive χ².
The setting is Stojkov & Warin (2023, Discourse & Communication) on Twitter
discourse about the refugee crisis in Europe. The data are simulated for
illustration and are not the paper's data or results: 3,000 refugee-related
tweets, each with a country of origin and one dominant discourse frame
(humanitarian, security, economic, political). The tiles are drawn by hand with ax.bar;
expected counts come from scipy.stats.chi2_contingency.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.colors import TwoSlopeNorm
from scipy import stats
# Simulated data, set in the context of Stojkov & Warin (2023) [stojkov2023refugee]
# Simulated tweets: country of origin × dominant discourse frame, frame shares vary by country
rng = np.random.default_rng(2015)
frames = ["Humanitarian", "Security", "Economic", "Political"]
mix = {"Germany": ([0.46, 0.18, 0.18, 0.18], 1000), "UK": ([0.30, 0.26, 0.26, 0.18], 700),
"France": ([0.36, 0.26, 0.14, 0.24], 550), "Italy": ([0.32, 0.22, 0.16, 0.30], 450),
"Hungary": ([0.16, 0.44, 0.10, 0.30], 300)}
df = pd.DataFrame([(c, f) for c, (pr, n) in mix.items() for f in rng.choice(frames, n, p=pr)],
columns=["country", "frame"])
table = pd.crosstab(pd.Categorical(df.country, list(mix)), pd.Categorical(df.frame, frames))
obs = table.to_numpy()
# Chi-squared test and Pearson residuals
chi2, p, dof, expected = stats.chi2_contingency(obs, correction=False)
resid = (obs - expected) / np.sqrt(expected)
fig, ax = plt.subplots(figsize=(8.5, 5.6))
cmap = plt.get_cmap("RdBu") # red = fewer than expected, blue = more
norm = TwoSlopeNorm(0, vmin=-8, vmax=8)
gap = 0.012
widths = obs.sum(axis=1) / obs.sum()
x0 = 0
for i, w in enumerate(widths):
heights = obs[i] / obs[i].sum()
y0 = 0
for j, h in enumerate(heights):
ax.bar(x0, h - gap, width=w - gap, bottom=y0, align="edge",
color=cmap(norm(resid[i, j])), edgecolor="none")
sep = " " if h < 0.12 else "\n" # thin tiles get a one-line label
ax.text(x0 + (w - gap) / 2, y0 + (h - gap) / 2, f"{obs[i, j]}{sep}{resid[i, j].round(1) + 0:+.1f}", ha="center", va="center",
fontsize=9, linespacing=1.3, color="white" if abs(resid[i, j]) > 5 else "#1D1D1F")
y0 += h
ax.text(x0 + (w - gap) / 2, -0.03, f"{table.index[i]}\n(n = {obs[i].sum()})", ha="center", va="top",
fontsize=10, color="#3A3A3C")
x0 += w
# Row labels on the left, placed at the heights of the first column
y0 = 0
for j, h in enumerate(obs[0] / obs[0].sum()):
ax.text(-0.015, y0 + (h - gap) / 2, table.columns[j], ha="right", va="center", fontsize=10, color="#3A3A3C")
y0 += h
sm_ = plt.cm.ScalarMappable(norm=norm, cmap=cmap)
cb = fig.colorbar(sm_, ax=ax, shrink=0.8, pad=0.02, ticks=[-8, -4, 0, 4, 8])
cb.set_label("Pearson residual", color="#3A3A3C")
cb.outline.set_visible(False)
ax.set_xlim(0, 1 - gap); ax.set_ylim(0, 1 - gap)
ax.axis("off")
ax.text(0.5, -0.15, "Country of the tweet", transform=ax.transAxes, ha="center", fontsize=11)
ax.text(-0.19, 0.5, "Discourse frame", transform=ax.transAxes, rotation=90, va="center", fontsize=11)
ax.set_title("The mix of refugee frames changes from one country to the next", pad=26)
ax.text(0, 1.02, f"Pearson χ²({dof}) = {chi2:.0f}, p < .001 · n = {obs.sum():,} tweets (simulated) · "
"tile labels: count and residual", transform=ax.transAxes, fontsize=9.5, color="#6E6E73")
plt.show()
# Mosaic plot with Pearson residuals: the R equivalent of plot.py
# Simulated data, set in the context of Stojkov & Warin (2023) [stojkov2023refugee]
# R and NumPy draw different random numbers, so the values differ slightly from the Python figure.
library(ggplot2)
set.seed(2015)
# Simulated tweets: country of origin × dominant discourse frame, frame shares vary by country
frames <- c("Humanitarian", "Security", "Economic", "Political")
mix <- list(Germany = c(0.46, 0.18, 0.18, 0.18), UK = c(0.30, 0.26, 0.26, 0.18),
France = c(0.36, 0.26, 0.14, 0.24), Italy = c(0.32, 0.22, 0.16, 0.30),
Hungary = c(0.16, 0.44, 0.10, 0.30))
sizes <- c(Germany = 1000, UK = 700, France = 550, Italy = 450, Hungary = 300)
d <- do.call(rbind, lapply(names(mix), function(country)
data.frame(country = country, frame = sample(frames, sizes[[country]], replace = TRUE,
prob = mix[[country]]))))
obs <- table(factor(d$country, names(mix)), factor(d$frame, frames))
# Chi-squared test and Pearson residuals: (observed − expected) / √expected
chi <- chisq.test(obs, correct = FALSE)
resid <- chi$residuals
# One tile per cell: column widths are the country shares, heights the frame shares within a country
gap <- 0.012
width <- rowSums(obs) / sum(obs)
left <- cumsum(width) - width
height <- prop.table(obs, 1)
bottom <- t(apply(height, 1, cumsum)) - height
tiles <- data.frame(country = rownames(obs)[row(obs)], frame = colnames(obs)[col(obs)],
count = as.vector(obs), resid = as.vector(resid),
xmin = left[row(obs)], xmax = left[row(obs)] + width[row(obs)] - gap,
ymin = as.vector(bottom), ymax = as.vector(bottom + height) - gap)
# Thin tiles get a one-line label
tiles$label <- sprintf(ifelse(as.vector(height) < 0.12, "%d %+.1f", "%d\n%+.1f"), tiles$count,
round(tiles$resid, 1) + 0)
columns <- data.frame(x = left + (width - gap) / 2,
label = sprintf("%s\n(n = %d)", rownames(obs), rowSums(obs)))
rows <- tiles[tiles$country == rownames(obs)[1], ] # row labels at the heights of the first column
p <- ggplot(tiles) +
geom_rect(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = resid)) +
geom_text(aes((xmin + xmax) / 2, (ymin + ymax) / 2, label = label,
colour = abs(resid) > 5), size = 3.1, lineheight = 1, show.legend = FALSE) +
scale_colour_manual(values = c(`TRUE` = "white", `FALSE` = "#1D1D1F")) +
geom_text(data = columns, aes(x, -0.03, label = label), vjust = 1, size = 3.5, colour = "#3A3A3C",
lineheight = 1) +
geom_text(data = rows, aes(-0.015, (ymin + ymax) / 2, label = frame), hjust = 1, size = 3.5,
colour = "#3A3A3C") +
# red = fewer than expected, blue = more
scale_fill_gradient2("Pearson\nresidual", low = "#B2182B", mid = "#F7F7F7", high = "#2166AC",
midpoint = 0, limits = c(-8, 8), breaks = seq(-8, 8, 4), oob = scales::squish) +
scale_x_continuous(limits = c(-0.17, 1), expand = c(0, 0)) +
scale_y_continuous(limits = c(-0.13, 1), expand = c(0, 0)) +
labs(title = "The mix of refugee frames changes from one country to the next",
subtitle = sprintf("Pearson χ²(%d) = %.0f, %s · n = %s tweets (simulated) · tile labels: count and residual",
chi$parameter, chi$statistic,
if (chi$p.value < .001) "p < .001" else sprintf("p = %.3f", chi$p.value),
format(sum(obs), big.mark = ",")),
x = "Country of the tweet", y = "Discourse frame") +
theme_void(base_size = 11) +
theme(plot.title = element_text(face = "bold", margin = margin(b = 4)),
plot.subtitle = element_text(size = 8.5, colour = "#6E6E73", margin = margin(b = 6)),
axis.title.x = element_text(size = 11, hjust = 0.58),
axis.title.y = element_text(size = 11, angle = 90, hjust = 0.56),
legend.title = element_text(size = 9.5, colour = "#3A3A3C"),
legend.key.height = unit(2.2, "lines"),
plot.margin = margin(8, 8, 8, 8))
print(p)
Figures use the optional PyStatlas style: add plt.style.use("pystatlas.mplstyle") to match the look exactly.
Data source
- Simulated data. Simulated data with a fixed random seed, created for this example.
No real respondents, documents or measurements: the numbers only illustrate how the chart and its statistics work. - Stojkov & Warin (2023), the refugee crisis on Twitter. Stojkov, A., & Warin, T. (2023). Discursive dynamics and local contexts on Twitter: The refugee crisis in Europe. Discourse & Communication, 17(3), 354–380. https://doi.org/10.1177/17504813231155739
The example is set in the context of this paper; unless its description says otherwise, the numbers are simulated and are not the paper's data or results.
The examples illustrate statistical methods. Their numbers are simulated unless an entry says otherwise, and their titles describe what each figure shows in these simulated data — not findings of the cited papers, nor the author's position on the substantive question. For results, context and data, rely on the papers cited here.
How to cite
PyStatlas is created and maintained by Thierry Warin. If it helped your work, please cite it.
Warin, T. (2026). Mosaic plot with Pearson residuals. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/proportions-surveys/mosaic-plot/
@misc{warin2026statlas,
author = {Warin, Thierry},
title = {PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences},
year = {2026},
version = {1.1.0},
howpublished = {\url{https://warin.ca/pystatlas/}},
note = {Source code: https://github.com/warint/pystatlas}
}More in Proportions & surveys
Diverging Likert chart
Five-point Likert items as diverging stacked bars centred on the neutral answer.
ggstats::gglikert()Stacked proportions by group
100% stacked bars with percentage labels, n per bar, chi-squared test and Cramér's V.
ggstatsplot::ggbarstats()Proportions with confidence intervals
A sorted dot plot of proportions with Wilson 95% confidence intervals.
ggstats::stat_prop() + geom_errorbar()