Tukey HSD 区间

所有两两均值差的 95% 联合置信区间。

Tukey HSD 区间

方差分析表明“各组存在差异”之后,Tukey 真实显著差异(HSD)法进一步指出哪些组对之间存在差异。每一行是一组两两均值差,其置信区间经过放宽,使所有区间同时在 95% 水平上成立。不跨过零的区间会被着色:第一组均值更高时为蓝色,更低时为橙色。

本例的背景是 Sanger 与 Warin(2020,Global Economy Journal)运用自然语言处理分析欧洲中央银行行长演讲的研究。此处的数字为说明而模拟——杜伊森贝赫、特里谢、德拉吉和拉加德 n = 290 篇演讲中每篇用于价格稳定的篇幅占比——并非论文的数据或结果。区间来自 statsmodels.stats.multicomp.pairwise_tukeyhsd,总体检验来自 scipy.stats.f_oneway。

代码及图中文字均为英文。

tukey-hsd.py · 52 行
下载 GitHub
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()

图表使用了可选的 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}
}

更多组间比较图表