テューキーの HSD 区間
すべての平均値の差の対について、同時 95% 信頼区間を示します。

分散分析で「群間に差がある」とわかったあと、テューキーの HSD(honestly significant difference)は どの 対に差があるのかを教えてくれます。各行は平均値の差の1つの対を表し、すべての区間が 同時に 95% で成り立つように幅を広げた信頼区間を伴います。ゼロをまたがない区間には色を付けており、1つ目の群の平均のほうが高い場合は青、低い場合はオレンジです。
舞台は Sanger & Warin(2020、Global Economy Journal)による、欧州中央銀行総裁の演説を自然言語処理で分析した研究です。ここでの数値は説明のために シミュレーション したもの——ドイセンベルク、トリシェ、ドラギ、ラガルドによる n = 290 本の演説について、各演説のうち物価安定に充てられた割合——であり、論文のデータや結果ではありません。区間は statsmodels.stats.multicomp.pairwise_tukeyhsd、全体の検定は scipy.stats.f_oneway によるものです。
コードおよび図中のテキストは英語です。
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats
from statsmodels.stats.multicomp import pairwise_tukeyhsd
# Simulated data, set in the context of Sanger & Warin (2020) [sanger2020ecb]
# Data: % of each speech on price stability, by ECB president (mean, SD, number of speeches)
rng = np.random.default_rng(2020)
spec = {"Duisenberg": (22, 7, 60), "Trichet": (19, 7, 90), "Draghi": (14, 6, 90),
"Lagarde": (16, 7, 50)}
names = list(spec)
df = pd.DataFrame({"president": np.repeat(range(4), [n for _, _, n in spec.values()]),
"share": np.concatenate([np.clip(rng.normal(m, s, n), 0, 100)
for m, s, n in spec.values()])})
# One-way ANOVA, then Tukey HSD on all 6 pairs
F, p = stats.f_oneway(*[g.share for _, g in df.groupby("president")])
k, n = len(names), len(df)
eta2 = F * (k - 1) / (F * (k - 1) + n - k)
tukey = pairwise_tukeyhsd(df.share, df.president)
g1, g2 = np.triu_indices(k, 1) # pairs in the order statsmodels reports them
res = pd.DataFrame({"group1": g1, "group2": g2, "meandiff": tukey.meandiffs,
"lower": tukey.confint[:, 0], "upper": tukey.confint[:, 1],
"p-adj": tukey.pvalues, "reject": tukey.reject})
# statsmodels reports group2 − group1; flip to read "group1 − group2"
res = res.assign(diff=-res.meandiff, low=-res.upper, high=-res.lower,
label=[f"{names[a]} − {names[b]}" for a, b in zip(res.group1, res.group2)])
res = res.iloc[::-1].reset_index(drop=True) # first pair on top
colors = np.where(~res.reject, "#AEAEB2", np.where(res["diff"] > 0, "#007AFF", "#FF9500"))
fig, ax = plt.subplots(figsize=(8, 4.8))
y = np.arange(len(res))
ax.axvline(0, color="#8E8E93", lw=1, ls="--", zorder=1)
ax.hlines(y, res.low, res.high, color=colors, lw=2.5, zorder=2)
ax.scatter(res["diff"], y, s=55, color=colors, edgecolor="white", lw=1.2, zorder=3)
for yi, row in res[res.reject].iterrows():
pv = "p < .001" if row["p-adj"] < 0.001 else f"p = {row['p-adj']:.3f}"
ax.annotate(f"{row['diff']:+.1f} pts, {pv}", (row.high, yi), xytext=(8, 0),
textcoords="offset points", va="center", fontsize=9, color="#3A3A3C")
ax.set_yticks(y, res.label, fontsize=9.5)
ax.set_ylim(-0.6, len(res) - 0.4)
ax.set_xlim(right=res.high.max() + 6)
ax.grid(axis="x"); ax.grid(axis="y", visible=False)
ax.set_xlabel("Difference in mean share on price stability (percentage points), Tukey 95% CI")
ax.set_title("Tukey intervals for every pair of presidents in a simulated speech sample", pad=26)
ax.text(0, 1.02, f"n = {n} speeches (simulated) · one-way ANOVA F({k - 1}, {n - k}) = {F:.1f}, "
f"p = {p:.1e}, η² = {eta2:.2f} · {res.reject.sum()} of {len(res)} pairs differ",
transform=ax.transAxes, fontsize=9.5, color="#6E6E73")
plt.show()
# Tukey HSD intervals: the R equivalent of plot.py
# Simulated data, set in the context of Sanger & Warin (2020) [sanger2020ecb]
# R and NumPy draw different random numbers, so the values differ slightly from the Python figure.
library(ggplot2)
set.seed(2020)
# Data: % of each speech on price stability, by ECB president (mean, SD, number of speeches)
spec <- data.frame(president = c("Duisenberg", "Trichet", "Draghi", "Lagarde"),
mean = c(22, 19, 14, 16), sd = c(7, 7, 6, 7), speeches = c(60, 90, 90, 50))
d <- data.frame(president = factor(rep(spec$president, spec$speeches), levels = spec$president),
share = pmin(pmax(rnorm(sum(spec$speeches), rep(spec$mean, spec$speeches),
rep(spec$sd, spec$speeches)), 0), 100))
# One-way ANOVA, then Tukey HSD on all 6 pairs
fit <- aov(share ~ president, data = d)
tab <- summary(fit)[[1]]
Fv <- tab[["F value"]][1]
k <- nlevels(d$president)
n <- nrow(d)
eta2 <- Fv * (k - 1) / (Fv * (k - 1) + n - k)
res <- as.data.frame(TukeyHSD(fit)$president)
# TukeyHSD() reports "later − earlier" president; flip to read "earlier − later"
pair <- do.call(rbind, strsplit(rownames(res), "-"))
res <- data.frame(label = paste(pair[, 2], "−", pair[, 1]), diff = -res$diff, low = -res$upr,
high = -res$lwr, p_adj = res[["p adj"]])
res$label <- factor(res$label, levels = rev(res$label)) # first pair on top
res$reject <- res$p_adj < 0.05
res$direction <- ifelse(!res$reject, "none", ifelse(res$diff > 0, "higher", "lower"))
res$note <- sprintf("%+.1f pts, %s", res$diff,
ifelse(res$p_adj < 0.001, "p < .001", sprintf("p = %.3f", res$p_adj)))
p <- ggplot(res, aes(diff, label, colour = direction)) +
geom_vline(xintercept = 0, colour = "#8E8E93", linewidth = 0.45, linetype = "dashed") +
geom_linerange(aes(xmin = low, xmax = high), linewidth = 1.2) +
geom_point(aes(fill = direction), shape = 21, size = 3, colour = "white", stroke = 0.8) +
geom_text(data = res[res$reject, ], aes(x = high, label = note), hjust = 0, nudge_x = 0.4,
size = 3.1, colour = "#3A3A3C") +
scale_colour_manual(values = c(none = "#AEAEB2", higher = "#007AFF", lower = "#FF9500"),
aesthetics = c("colour", "fill"), guide = "none") +
scale_x_continuous(limits = c(NA, max(res$high) + 6)) +
labs(title = "Tukey intervals for every pair of presidents in a simulated speech sample",
subtitle = sprintf(paste("n = %d speeches (simulated) · one-way ANOVA F(%d, %d) = %.1f, p = %.1e,",
"η² = %.2f · %d of %d pairs differ"),
n, k - 1, n - k, Fv, tab[["Pr(>F)"]][1], eta2, sum(res$reject), nrow(res)),
x = "Difference in mean share on price stability (percentage points), Tukey 95% CI",
y = NULL) +
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.y = element_text(colour = "#1D1D1F", size = 9.5),
panel.grid.minor = element_blank(), panel.grid.major.y = 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. - Sanger & Warin (2020), the speeches of the ECB's presidents. Sanger, W., & Warin, T. (2020). The speeches of the European Central Bank's presidents: An NLP study. Global Economy Journal, 20(2), 2050009. https://doi.org/10.1142/s2194565920500098
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). Tukey HSD intervals. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/group-comparisons/tukey-hsd/
@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}
}