组间比较
小提琴图 + 箱线图 + 散点,附 Welch 方差分析、效应量和两两检验。

ggbetweenstats() 的 Python 版本:展示每一个观测值,外面包裹小提琴图(分布)和细长的箱线图(四分位数),并突出显示各组均值。副标题报告 Welch 单因素方差分析(对方差不齐稳健),以及作为效应量的 ω²;括号标注经 Holm 校正的两两 Welch t 检验结果。
本例的背景是 Kouloukoui 等(2021,Journal of Cleaner Production)对全球最大碳密集型行业中影响企业气候风险暴露感知之因素的研究。此处的数字为说明而模拟——三个行业 n = 125 家企业 0–100 分的感知暴露得分——并非论文的数据或结果。方差分析来自 statsmodels.stats.oneway.anova_oneway,两两检验来自 scipy.stats.ttest_ind 和 statsmodels.stats.multitest.multipletests。
代码及图中文字均为英文。
from itertools import combinations
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
from statsmodels.stats.multitest import multipletests
from statsmodels.stats.oneway import anova_oneway
# Simulated data, set in the context of Kouloukoui et al. (2021) [kouloukoui2021]
# Data: perceived climate-risk exposure score (0–100) of firms, by industry
rng = np.random.default_rng(2021)
groups = {"Oil and gas": (68, 12, 45), "Mining and metals": (61, 14, 38),
"Electric utilities": (53, 10, 42)} # mean, SD, number of firms
data = [np.clip(rng.normal(m, s, n), 0, 100) for m, s, n in groups.values()]
palette = ["#007AFF", "#FF9500", "#34C759"]
# Welch's ANOVA + omega squared
res = anova_oneway(data, use_var="unequal")
k, n = len(data), sum(len(d) for d in data)
omega2 = (res.statistic - 1) * (k - 1) / ((res.statistic - 1) * (k - 1) + n)
# Pairwise Welch t-tests, Holm-corrected
pairs = list(combinations(range(k), 2))
raw_p = [stats.ttest_ind(data[i], data[j], equal_var=False).pvalue for i, j in pairs]
adj_p = multipletests(raw_p, method="holm")[1]
fig, ax = plt.subplots(figsize=(8, 5.4))
for i, (d, c) in enumerate(zip(data, palette)):
v = ax.violinplot(d, positions=[i], widths=0.8, showextrema=False)
for body in v["bodies"]:
body.set(facecolor=c, alpha=0.15, edgecolor="none")
ax.boxplot(d, positions=[i], widths=0.12, showfliers=False, patch_artist=True,
boxprops=dict(facecolor="white", edgecolor="#3A3A3C", lw=1),
medianprops=dict(color="#3A3A3C", lw=1.5),
whiskerprops=dict(color="#3A3A3C"), capprops=dict(visible=False))
ax.scatter(i + rng.uniform(-0.22, 0.22, len(d)) * 0.9, d, s=16, color=c, alpha=0.6, lw=0)
ax.scatter(i, d.mean(), s=90, color=c, edgecolor="white", lw=2, zorder=5)
ax.annotate(f"μ = {d.mean():.0f}", (i + 0.09, d.mean()), xytext=(10, 0), textcoords="offset points",
va="center", bbox=dict(boxstyle="round,pad=0.25", fc="white", ec="none", alpha=0.9), fontsize=9.5, fontweight="semibold", color=c)
# Significance brackets
top, step = max(map(np.max, data)), 8
for h, ((i, j), p) in enumerate(sorted(zip(pairs, adj_p), key=lambda t: t[0][1] - t[0][0])):
y = top + 4 + h * step
ax.plot([i, i, j, j], [y - 1.5, y, y, y - 1.5], color="#8E8E93", lw=1)
label = "p < .001" if p < 0.001 else f"p = {p:.3f}"
ax.text((i + j) / 2, y + 0.8, label, ha="center", va="bottom", fontsize=9, color="#3A3A3C")
ax.set_xticks(range(k), [f"{g}\n(n = {len(d)} firms)" for g, d in zip(groups, data)])
ax.set_ylabel("Perceived climate-risk exposure\n(score, 0–100)")
ax.set_ylim(top=top + 4 + len(pairs) * step + 2)
ax.set_yticks(range(20, 101, 20))
ax.set_title("Three industries compared: Welch's ANOVA with Holm-adjusted pairwise tests", pad=26)
ax.text(0, 1.02, f"n = {n} firms (simulated) · Welch's F({res.df_num:.0f}, {res.df_denom:.1f}) = "
f"{res.statistic:.1f}, p = {res.pvalue:.1e}, ω² = {omega2:.2f} · pairwise: Welch t, Holm",
transform=ax.transAxes, fontsize=9.5, color="#6E6E73")
plt.show()
# Between-groups comparison: the R equivalent of plot.py
# Simulated data, set in the context of Kouloukoui et al. (2021) [kouloukoui2021]
# R and NumPy draw different random numbers, so the values differ slightly from the Python figure.
library(ggplot2)
set.seed(2021)
# Data: perceived climate-risk exposure score (0–100) of firms, by industry
industries <- c("Oil and gas", "Mining and metals", "Electric utilities")
design <- data.frame(mean = c(68, 61, 53), sd = c(12, 14, 10), firms = c(45, 38, 42))
d <- do.call(rbind, lapply(1:3, function(i)
data.frame(industry = industries[i],
score = pmin(pmax(rnorm(design$firms[i], design$mean[i], design$sd[i]), 0), 100))))
d$industry <- factor(d$industry, levels = industries)
palette <- setNames(c("#007AFF", "#FF9500", "#34C759"), industries)
k <- nlevels(d$industry)
n <- nrow(d)
# Welch's ANOVA + omega squared
welch <- oneway.test(score ~ industry, data = d, var.equal = FALSE)
Fw <- unname(welch$statistic)
omega2 <- (Fw - 1) * (k - 1) / ((Fw - 1) * (k - 1) + n)
# Pairwise Welch t-tests, Holm-corrected; brackets stacked from the shortest to the longest
pairs <- as.data.frame(t(combn(k, 2)))
names(pairs) <- c("i", "j")
pairs$p <- p.adjust(mapply(function(i, j)
t.test(d$score[as.integer(d$industry) == i], d$score[as.integer(d$industry) == j])$p.value,
pairs$i, pairs$j), method = "holm")
pairs <- pairs[order(pairs$j - pairs$i), ]
top <- max(d$score)
pairs$y <- top + 4 + (seq_len(nrow(pairs)) - 1) * 8
pairs$label <- ifelse(pairs$p < 0.001, "p < .001", sprintf("p = %.3f", pairs$p))
means <- aggregate(score ~ industry, data = d, FUN = mean)
p <- ggplot(d, aes(industry, score, colour = industry, fill = industry)) +
geom_violin(alpha = 0.15, colour = NA, width = 0.8, trim = TRUE) +
geom_boxplot(width = 0.12, outlier.shape = NA, fill = "white", colour = "#3A3A3C",
linewidth = 0.4) +
geom_jitter(width = 0.2, height = 0, size = 1.4, alpha = 0.6, stroke = 0) +
geom_point(data = means, shape = 21, size = 4, colour = "white", stroke = 1.2) +
geom_label(data = means, aes(label = sprintf("μ = %.0f", score)), fill = "white", alpha = 0.9,
label.size = 0, fontface = "bold", size = 3.3, hjust = 0,
position = position_nudge(x = 0.16)) +
# Significance brackets
geom_segment(data = pairs, aes(x = i, xend = j, y = y, yend = y), inherit.aes = FALSE,
colour = "#8E8E93", linewidth = 0.4) +
geom_segment(data = pairs, aes(x = i, xend = i, y = y - 1.5, yend = y), inherit.aes = FALSE,
colour = "#8E8E93", linewidth = 0.4) +
geom_segment(data = pairs, aes(x = j, xend = j, y = y - 1.5, yend = y), inherit.aes = FALSE,
colour = "#8E8E93", linewidth = 0.4) +
geom_text(data = pairs, aes(x = (i + j) / 2, y = y + 0.8, label = label), inherit.aes = FALSE,
vjust = 0, size = 3.1, colour = "#3A3A3C") +
scale_colour_manual(values = palette, aesthetics = c("colour", "fill"), guide = "none") +
scale_x_discrete(labels = sprintf("%s\n(n = %d firms)", industries, table(d$industry))) +
scale_y_continuous(breaks = seq(20, 100, 20)) +
coord_cartesian(ylim = c(NA, top + 4 + nrow(pairs) * 8 + 2)) +
labs(title = "Three industries compared: Welch's ANOVA with Holm-adjusted pairwise tests",
subtitle = sprintf(paste("n = %d firms (simulated) · Welch's F(%.0f, %.1f) = %.1f, p = %.1e,",
"ω² = %.2f · pairwise: Welch t, Holm"),
n, welch$parameter[1], welch$parameter[2], Fw, welch$p.value, omega2),
x = NULL, y = "Perceived climate-risk exposure\n(score, 0–100)") +
theme_minimal(base_size = 11) +
theme(plot.title = element_text(face = "bold", size = 11.5),
plot.title.position = "plot",
plot.subtitle = element_text(size = 8.5, colour = "#6E6E73"),
axis.text.x = element_text(colour = "#1D1D1F", size = 10),
panel.grid.minor = element_blank(), panel.grid.major.x = element_blank())
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. (2021), perceived exposure to climate risks. Kouloukoui, D., de Marcellis-Warin, N., Armellini, F., Warin, T., & Andrade Torres, E. (2021). Factors influencing the perception of exposure to climate risks: Evidence from the world's largest carbon-intensive industries. Journal of Cleaner Production, 306, 127160. https://doi.org/10.1016/j.jclepro.2021.127160
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). Between-groups comparison. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/group-comparisons/between-groups-violin/
@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}
}