被试内比较

重复测量数据,每名被试一条线,附均值、重复测量方差分析和配对检验。

被试内比较

当同一批单位在每种条件下都接受测量时,值得关注的是每个单位内部的变化。细灰线连接每条生产线的各次测量,便于看出是否几乎所有生产线都朝同一方向变化;小提琴图展示各阶段的分布,大圆点(以深色线相连)为各阶段的均值。

本例的背景是 Warin、d'Anglade 与 de Marcellis-Warin(2025,International Journal of Sustainable Engineering)结合 k-means 聚类与数据科学减少制造业废料的研究。此处的数字为说明而模拟——同样 n = 24 条生产线在基线、基于聚类的重组之后以及随访时的废品率——并非论文的数据或结果。副标题报告单因素重复测量方差分析(statsmodels.stats.anova.AnovaRM)及偏 η²,括号标注经 Holm 校正的配对 t 检验(scipy.stats.ttest_rel)及 Cohen's d_z(负值表示废料减少)。

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

within-subjects.py · 67 行
下载 GitHub
from itertools import combinations

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats
from statsmodels.stats.anova import AnovaRM
from statsmodels.stats.multitest import multipletests

# Simulated data, set in the context of Warin, d'Anglade & de Marcellis-Warin (2025) [warin2025waste]

# Data: waste rate (% of output) of the same 24 lines at three stages
rng = np.random.default_rng(2025)
conditions = ["Baseline", "After\nreorganisation", "Follow-up"]
line = rng.normal(8, 1.8, 24)                          # each line's own level
wide = pd.DataFrame({c: line + shift + rng.normal(0, 0.9, 24)
                     for c, shift in zip(conditions, [0, -1.8, -1.4])})
n = len(wide)
long = wide.rename_axis("id").reset_index().melt("id", var_name="condition", value_name="waste")

# Repeated-measures ANOVA + partial eta squared
aov = AnovaRM(long, "waste", "id", within=["condition"]).fit().anova_table.iloc[0]
eta_p = aov["F Value"] * aov["Num DF"] / (aov["F Value"] * aov["Num DF"] + aov["Den DF"])

# Pairwise paired t-tests (Holm) with Cohen's d_z
pairs = list(combinations(range(3), 2))
tests = [stats.ttest_rel(wide.iloc[:, j], wide.iloc[:, i]) for i, j in pairs]
adj_p = multipletests([t.pvalue for t in tests], method="holm")[1]
dz = [(wide.iloc[:, j] - wide.iloc[:, i]).mean() / (wide.iloc[:, j] - wide.iloc[:, i]).std()
      for i, j in pairs]

fig, ax = plt.subplots(figsize=(8, 5.6))
palette = ["#FF9500", "#AF52DE", "#007AFF"]
x = np.arange(3)
for _, row in wide.iterrows():                      # one line per subject
    ax.plot(x, row.values, color="#C7C7CC", lw=0.8, alpha=0.8, zorder=1)
for i, c in enumerate(palette):
    v = ax.violinplot(wide.iloc[:, i], positions=[i], widths=0.55, showextrema=False)
    v["bodies"][0].set(facecolor=c, alpha=0.15, edgecolor="none")
    ax.scatter(np.full(n, i), wide.iloc[:, i], s=18, color=c, alpha=0.7, lw=0, zorder=2)
means = wide.mean()
ax.plot(x, means, color="#1D1D1F", lw=2.5, zorder=3)
ax.scatter(x, means, s=110, color="#1D1D1F", edgecolor="white", lw=2, zorder=4)
for i, m in enumerate(means):
    ax.annotate(f"μ = {m:.1f}%", (i, m), xytext=(14, 0), textcoords="offset points", va="center",
                fontsize=9.5, fontweight="semibold", color="#1D1D1F",
                bbox=dict(boxstyle="round,pad=0.2", fc="white", ec="none", alpha=0.9), zorder=5)

# Significance brackets
top, step = wide.values.max() + 0.4, 0.8
for h, ((i, j), p, d) in enumerate(sorted(zip(pairs, adj_p, dz), key=lambda t: t[0][1] - t[0][0])):
    y = top + h * step
    ax.plot([i, i, j, j], [y - 0.2, y, y, y - 0.2], color="#8E8E93", lw=1)
    label = "p < .001" if p < 0.001 else f"p = {p:.3f}"
    ax.text((i + j) / 2, y + 0.07, f"{label}, d_z = {d:.2f}", ha="center", va="bottom",
            fontsize=9, color="#3A3A3C")

ax.set_xticks(x, [f"{c}\n(n = {n})" for c in conditions])
ax.set_xlim(-0.5, 2.6)
ax.set_ylim(0, top + 3 * step + 0.2)
ax.set_ylabel("Waste rate (% of output)")
fell = (wide.iloc[:, 1] < wide.iloc[:, 0]).sum()
ax.set_title(f"Waste fell on {fell} of {n} production lines after the reorganisation", pad=26)
ax.text(0, 1.02, f"n = {n} lines (simulated) · repeated-measures ANOVA F({aov['Num DF']:.0f}, "
        f"{aov['Den DF']:.0f}) = {aov['F Value']:.1f}, p = {aov['Pr > F']:.1e}, η²p = {eta_p:.2f}"
        " · pairwise: paired t, Holm", 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.
  • Warin, d'Anglade & de Marcellis-Warin (2025), data science for waste reduction in manufacturing. Warin, T., d'Anglade, P. M., & de Marcellis-Warin, N. (2025). Optimising industrial efficiency: Integrating K-means clustering and data science for sustainable manufacturing and waste reduction. International Journal of Sustainable Engineering, 18(1), 2527300. https://doi.org/10.1080/19397038.2025.2527300
    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). Within-subjects 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/within-subjects/

@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}
}

更多组间比较图表