Comparaison intra-sujets
Mesures répétées avec une ligne par sujet, moyennes, ANOVA à mesures répétées et tests appariés.

Lorsque les mêmes unités sont mesurées dans chaque condition, la variation intéressante se situe à l'intérieur de chaque unité. De fines lignes grises relient les mesures de chaque ligne de production, ce qui permet de voir si presque toutes les lignes évoluent dans le même sens ; les violons montrent la distribution par étape et les gros points (reliés par une ligne foncée) sont les moyennes de chaque étape.
Le contexte est celui de Warin, d'Anglade et de Marcellis-Warin (2025, International Journal of Sustainable Engineering), qui combine le partitionnement k-means et la science des données pour réduire les rebuts dans l'industrie manufacturière. Les chiffres sont ici simulés à des fins d'illustration — le taux de rebut des mêmes n = 24 lignes de production au départ, après une réorganisation fondée sur le partitionnement, puis lors du suivi — et ne sont ni les données ni les résultats de l'article. Le sous-titre rapporte une ANOVA à mesures répétées à un facteur (statsmodels.stats.anova.AnovaRM) avec η² partiel, et les crochets indiquent des tests t appariés corrigés selon Holm (scipy.stats.ttest_rel) avec le d_z de Cohen (négatif = les rebuts ont baissé).
Le code et le texte à l'intérieur des figures sont en anglais.
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()
# Within-subjects comparison: the R equivalent of plot.py
# Simulated data, set in the context of Warin, d'Anglade & de Marcellis-Warin (2025) [warin2025waste]
# R and NumPy draw different random numbers, so the values differ slightly from the Python figure.
library(ggplot2)
set.seed(2025)
# Data: waste rate (% of output) of the same 24 lines at three stages
conditions <- c("Baseline", "After\nreorganisation", "Follow-up")
n <- 24
level <- rnorm(n, 8, 1.8) # each line's own level
wide <- sapply(c(0, -1.8, -1.4), function(shift) level + shift + rnorm(n, 0, 0.9))
long <- data.frame(id = factor(rep(1:n, 3)),
condition = factor(rep(conditions, each = n), levels = conditions),
waste = as.vector(wide))
# Repeated-measures ANOVA + partial eta squared
aov_table <- summary(aov(waste ~ condition + Error(id / condition), data = long))[["Error: id:condition"]][[1]]
Fv <- aov_table[["F value"]][1]
df <- aov_table[["Df"]]
eta_p <- Fv * df[1] / (Fv * df[1] + df[2])
# Pairwise paired t-tests (Holm) with Cohen's d_z; brackets stacked from the shortest to the longest
pairs <- as.data.frame(t(combn(3, 2)))
names(pairs) <- c("i", "j")
pairs$p <- p.adjust(mapply(function(i, j) t.test(wide[, j], wide[, i], paired = TRUE)$p.value,
pairs$i, pairs$j), method = "holm")
pairs$dz <- mapply(function(i, j) mean(wide[, j] - wide[, i]) / sd(wide[, j] - wide[, i]),
pairs$i, pairs$j)
pairs <- pairs[order(pairs$j - pairs$i), ]
top <- max(wide) + 0.4
pairs$y <- top + (seq_len(nrow(pairs)) - 1) * 0.8
pairs$label <- sprintf("%s, d_z = %.2f",
ifelse(pairs$p < 0.001, "p < .001", sprintf("p = %.3f", pairs$p)), pairs$dz)
means <- aggregate(waste ~ condition, data = long, FUN = mean)
fell <- sum(wide[, 2] < wide[, 1])
p <- ggplot(long, aes(condition, waste)) +
geom_line(aes(group = id), colour = "#C7C7CC", linewidth = 0.35, alpha = 0.8) + # one line per subject
geom_violin(aes(fill = condition), alpha = 0.15, colour = NA, width = 0.55) +
geom_point(aes(colour = condition), size = 1.6, alpha = 0.7, stroke = 0) +
geom_line(data = means, aes(group = 1), colour = "#1D1D1F", linewidth = 1.1) +
geom_point(data = means, shape = 21, size = 4.5, fill = "#1D1D1F", colour = "white", stroke = 1.2) +
geom_label(data = means, aes(label = sprintf("μ = %.1f%%", waste)), fill = "white", alpha = 0.9,
label.size = 0, fontface = "bold", size = 3.3, hjust = 0, colour = "#1D1D1F",
position = position_nudge(x = 0.09)) +
# Significance brackets
geom_segment(data = pairs, aes(x = i, xend = j, y = y, yend = y), colour = "#8E8E93", linewidth = 0.4) +
geom_segment(data = pairs, aes(x = i, xend = i, y = y - 0.2, yend = y), colour = "#8E8E93",
linewidth = 0.4) +
geom_segment(data = pairs, aes(x = j, xend = j, y = y - 0.2, yend = y), colour = "#8E8E93",
linewidth = 0.4) +
geom_text(data = pairs, aes(x = (i + j) / 2, y = y + 0.07, label = label), vjust = 0, size = 3.1,
colour = "#3A3A3C") +
scale_colour_manual(values = c("#FF9500", "#AF52DE", "#007AFF"), aesthetics = c("colour", "fill"),
guide = "none") +
scale_x_discrete(labels = sprintf("%s\n(n = %d)", conditions, n)) +
scale_y_continuous(limits = c(0, top + 3 * 0.8 + 0.2), expand = c(0, 0)) +
labs(title = sprintf("Waste fell on %d of %d production lines after the reorganisation", fell, n),
subtitle = sprintf(paste("n = %d lines (simulated) · repeated-measures ANOVA F(%.0f, %.0f) = %.1f,",
"p = %.1e, η²p = %.2f · pairwise: paired t, Holm"),
n, df[1], df[2], Fv, aov_table[["Pr(>F)"]][1], eta_p),
x = NULL, y = "Waste rate (% of output)") +
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.x = element_text(colour = "#1D1D1F", size = 10),
panel.grid.minor = element_blank(), panel.grid.major.x = element_blank())
print(p)
Les figures utilisent le style PyStatlas (facultatif) : ajoutez plt.style.use("pystatlas.mplstyle") pour obtenir exactement le même rendu.
Source des données
- 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.
Les exemples illustrent des méthodes statistiques. Leurs chiffres sont simulés, sauf mention contraire dans l'entrée, et leurs titres décrivent ce que chaque figure montre dans ces données simulées — ni les résultats des articles cités, ni la position de l'auteur sur la question de fond. Pour les résultats, le contexte et les données, reportez-vous aux articles cités ici.
Comment citer
PyStatlas est créé et maintenu par Thierry Warin. S'il vous a été utile dans vos travaux, merci de le citer.
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}
}Plus dans Comparaisons de groupes
Comparaison entre groupes
Violon, boîte et points avec ANOVA de Welch, taille d'effet et tests deux à deux.
ggstatsplot::ggbetweenstats()Graphique d'estimation
Données brutes de deux groupes, avec la différence de moyennes et son IC à 95 % par bootstrap.
dabestr::dabest() + plot()Graphique d'interaction
Moyennes de groupes avec intervalles de confiance à 95 % pour deux facteurs, avec ANOVA à deux facteurs.
ggpubr::ggline(add = "mean_ci") / ggstats