带标准化残差的交叉表
以热图呈现的列联表,按相对于独立性的标准化残差着色。

ggstats::ggtable() 的 Python 版本:熟悉的交叉表,但每个单元格按其标准化(调整)残差着色——即观测频数高于或低于独立假设预测值多少个标准误。在独立假设下,这些残差近似服从标准正态分布,因此超过 ±2 的单元格(以粗体标出)正是使 χ² 检验显著的那些。每个单元格显示频数及其行百分比;边际给出合计。
背景设定为 Kouloukoui、de Marcellis-Warin、Gomes 与 Warin(2023,Journal of Cleaner Production)关于 Twitter 上 ESG 话题讨论的研究。数据为用于说明的模拟数据,并非论文的数据或结果:4,000 条推文,每条对应一个 ESG 子话题及作者所在的世界区域。期望频数由 scipy.stats.chi2_contingency 计算;残差为 (O − E) / √(E · (1 − 行占比) · (1 − 列占比))。
代码及图中文字均为英文。
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 Kouloukoui et al. (2023) [kouloukoui2023esg]
# Simulated tweets: ESG sub-topic (rows) × world region (columns), topic mix varies by region
rng = np.random.default_rng(2023)
topics = ["E · Climate change", "E · Pollution & waste", "S · Labour & human rights",
"S · Diversity & inclusion", "G · Board & executive pay", "G · Corruption & ethics"]
mix = {"North America": ([.30, .10, .12, .22, .18, .08], 1400), "Europe": ([.38, .14, .12, .14, .14, .08], 1200),
"Asia-Pacific": ([.28, .24, .14, .10, .14, .10], 800), "Latin America": ([.24, .16, .20, .10, .08, .22], 350),
"Africa": ([.22, .14, .24, .10, .08, .22], 250)}
df = pd.DataFrame([(t, r) for r, (pr, n) in mix.items() for t in rng.choice(topics, n, p=pr)],
columns=["topic", "region"])
table = pd.crosstab(pd.Categorical(df.topic, topics), pd.Categorical(df.region, list(mix)))
obs = table.to_numpy()
n = obs.sum()
# Chi-squared test and adjusted (standardized) residuals
chi2, p, dof, exp = stats.chi2_contingency(obs, correction=False)
row_share, col_share = obs.sum(1, keepdims=True) / n, obs.sum(0, keepdims=True) / n
std_resid = (obs - exp) / np.sqrt(exp * (1 - row_share) * (1 - col_share))
row_pct = obs / obs.sum(1, keepdims=True) * 100
v = np.sqrt(chi2 / (n * (min(obs.shape) - 1)))
fig, ax = plt.subplots(figsize=(9, 5))
norm = TwoSlopeNorm(0, vmin=-6, vmax=6)
im = ax.imshow(std_resid, cmap="RdBu", norm=norm, aspect="auto")
for i in range(obs.shape[0]):
for j in range(obs.shape[1]):
strong = abs(std_resid[i, j]) >= 2
ax.text(j, i - 0.12, f"{obs[i, j]:,}", ha="center", va="center", fontsize=11,
fontweight="bold" if strong else "normal",
color="white" if abs(std_resid[i, j]) > 3 else "#1D1D1F")
ax.text(j, i + 0.2, f"{row_pct[i, j]:.0f}%", ha="center", va="center", fontsize=8.5,
color="white" if abs(std_resid[i, j]) > 3 else "#3A3A3C")
# White gutters between cells and totals in the margins
ax.set_xticks(np.arange(-0.5, obs.shape[1]), minor=True)
ax.set_yticks(np.arange(-0.5, obs.shape[0]), minor=True)
ax.grid(which="minor", color="white", lw=3)
ax.grid(which="major", visible=False)
ax.tick_params(which="minor", length=0)
regions = [c.replace(" ", "\n") for c in table.columns] # two-word regions on two lines
ax.set_xticks(range(obs.shape[1]), [f"{c}\n(n = {t:,})" for c, t in zip(regions, obs.sum(0))])
ax.set_yticks(range(obs.shape[0]), [f"{r} (n = {t:,})" for r, t in zip(table.index, obs.sum(1))])
for s in ax.spines.values():
s.set_visible(False)
ax.set_xlabel("World region of the tweet")
ax.set_ylabel("ESG sub-topic")
cb = fig.colorbar(im, ax=ax, shrink=0.85, pad=0.02, ticks=[-6, -4, -2, 0, 2, 4, 6])
cb.set_label("Standardized residual", color="#3A3A3C")
cb.outline.set_visible(False)
ax.set_title("Each region tweets about a different side of ESG", pad=26)
ax.text(0, 1.02, f"Pearson χ²({dof}) = {chi2:.0f}, p < .001, V = {v:.2f} · n = {n:,} tweets (simulated) · "
"count & row % · bold: |resid.| ≥ 2", transform=ax.transAxes,
fontsize=9.5, color="#6E6E73")
plt.show()
# Cross-table with standardized residuals: the R equivalent of plot.py
# Simulated data, set in the context of Kouloukoui et al. (2023) [kouloukoui2023esg]
# R and NumPy draw different random numbers, so the values differ slightly from the Python figure.
library(ggplot2)
set.seed(2023)
# Simulated tweets: ESG sub-topic (rows) × world region (columns), topic mix varies by region
topics <- c("E · Climate change", "E · Pollution & waste", "S · Labour & human rights",
"S · Diversity & inclusion", "G · Board & executive pay", "G · Corruption & ethics")
mix <- list("North America" = c(.30, .10, .12, .22, .18, .08), "Europe" = c(.38, .14, .12, .14, .14, .08),
"Asia-Pacific" = c(.28, .24, .14, .10, .14, .10), "Latin America" = c(.24, .16, .20, .10, .08, .22),
"Africa" = c(.22, .14, .24, .10, .08, .22))
sizes <- c(1400, 1200, 800, 350, 250)
d <- do.call(rbind, lapply(seq_along(mix), function(i)
data.frame(region = names(mix)[i], topic = sample(topics, sizes[i], replace = TRUE, prob = mix[[i]]))))
obs <- table(factor(d$topic, topics), factor(d$region, names(mix)))
n <- sum(obs)
# Chi-squared test and adjusted (standardized) residuals:
# (O − E) / √(E · (1 − row share) · (1 − column share)), returned by chisq.test() as $stdres
chi <- chisq.test(obs, correct = FALSE)
v <- sqrt(unname(chi$statistic) / (n * (min(dim(obs)) - 1)))
comma <- function(x) format(x, big.mark = ",", trim = TRUE)
cells <- data.frame(topic = rownames(obs)[row(obs)], region = colnames(obs)[col(obs)],
count = as.vector(obs), resid = as.vector(chi$stdres),
row_pct = as.vector(100 * prop.table(obs, 1)))
# Totals in the axis labels; two-word regions on two lines; first topic on top
cells$topic <- factor(cells$topic, levels = rev(topics),
labels = rev(sprintf("%s (n = %s)", topics, comma(rowSums(obs)))))
cells$region <- factor(cells$region, levels = names(mix),
labels = sprintf("%s\n(n = %s)", sub(" ", "\n", names(mix)), comma(colSums(obs))))
cells$ink <- ifelse(abs(cells$resid) > 3, "white", "#1D1D1F")
cells$face <- ifelse(abs(cells$resid) >= 2, "bold", "plain")
p <- ggplot(cells, aes(region, topic)) +
geom_tile(aes(fill = resid), colour = "white", linewidth = 1.5) + # white gutters between cells
geom_text(aes(label = comma(count), colour = ink, fontface = face), size = 3.9, nudge_y = 0.12) +
geom_text(aes(label = sprintf("%.0f%%", row_pct), colour = ink), size = 3, nudge_y = -0.2) +
scale_colour_identity() +
# red = fewer than expected, blue = more
scale_fill_gradient2("Standardized\nresidual", low = "#B2182B", mid = "#F7F7F7", high = "#2166AC",
midpoint = 0, limits = c(-6, 6), breaks = seq(-6, 6, 2), oob = scales::squish) +
scale_x_discrete(expand = c(0, 0)) +
scale_y_discrete(expand = c(0, 0)) +
labs(title = "Each region tweets about a different side of ESG",
subtitle = sprintf(paste("Pearson χ²(%d) = %.0f, %s, V = %.2f · n = %s tweets (simulated) ·",
"count & row %% · bold: |resid.| ≥ 2"),
chi$parameter, chi$statistic,
if (chi$p.value < .001) "p < .001" else sprintf("p = %.3f", chi$p.value),
v, comma(n)),
x = "World region of the tweet", y = "ESG sub-topic") +
theme_minimal(base_size = 11) +
theme(plot.title = element_text(face = "bold"),
plot.title.position = "plot",
plot.subtitle = element_text(size = 8.5, colour = "#6E6E73"),
axis.text = element_text(colour = "#1D1D1F", size = 9.5),
axis.text.x = element_text(lineheight = 0.95),
panel.grid = element_blank(),
legend.title = element_text(size = 9.5, colour = "#3A3A3C"),
legend.key.height = unit(2.2, "lines"))
print(p)
图表使用了可选的 PyStatlas 样式:添加 plt.style.use("pystatlas.mplstyle") 即可完全还原其外观。
数据来源
- 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. - Kouloukoui et al. (2023), global conversations on ESG topics. Kouloukoui, D., de Marcellis-Warin, N., Gomes, S. M. S., & Warin, T. (2023). Mapping global conversations on twitter about environmental, social, and governance topics through natural language processing. Journal of Cleaner Production, 414, 137369. https://doi.org/10.1016/j.jclepro.2023.137369
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.
这些示例用于说明统计方法。除条目另有说明外,其数值均为模拟数据,图表标题描述的是该图在这些模拟数据中呈现的内容——既不是所引论文的结论,也不是作者对实质问题的立场。关于结果、背景和数据,请以此处引用的论文为准。
如何引用
PyStatlas 由 Thierry Warin 创建并维护。如果它对你的工作有所帮助,敬请引用。
Warin, T. (2026). Cross-table with standardized 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/crosstab-residuals/
@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}
}