Comparaison de fonctions de répartition empiriques
Fonctions de répartition empiriques de deux groupes, avec l'écart de Kolmogorov–Smirnov.

Une fonction de répartition empirique (ECDF) indique, pour chaque valeur de l'axe des x, la proportion d'observations inférieures ou égales à cette valeur. Contrairement à un histogramme, elle ne nécessite aucune classe, et chaque quantile peut être lu directement. Lorsque deux ECDF sont tracées ensemble, le plus grand écart vertical entre elles correspond exactement à la statistique D de Kolmogorov–Smirnov à deux échantillons, représentée ici par un segment rouge.
Le contexte est celui de Pastoriza Rivas et Warin (2022, Data in Brief), un jeu de données couvrant deux décennies de conférences de presse et de performances en tournoi de Tiger Woods. Les chiffres sont ici simulés à des fins d'illustration — des scores par tour rapportés au par (en coups entiers, plus bas = meilleur) pour n = 520 tours, 1997–2009 contre 2010–2019 — et ne sont ni les données ni les résultats de l'article. scipy.stats.ecdf construit les courbes et scipy.stats.ks_2samp renvoie D, sa position et la valeur p (approximative ici, car les scores en coups entiers comportent de nombreux ex aequo).
Le code et le texte à l'intérieur des figures sont en anglais.
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
# Simulated data, set in the context of Pastoriza Rivas & Warin (2022) [pastoriza2022]
# Data: round score to par (strokes) in two periods of the career
rng = np.random.default_rng(2022)
groups = {"1997–2009": np.round(rng.normal(-2.4, 2.9, 320)),
"2010–2019": np.round(rng.normal(-0.6, 3.1, 200))}
palette = ["#007AFF", "#FF9500"]
# Two-sample Kolmogorov–Smirnov test: D is the largest vertical gap
ks = stats.ks_2samp(*groups.values())
x_gap = ks.statistic_location
F = [stats.ecdf(d).cdf for d in groups.values()]
y_gap = [f.evaluate(x_gap) for f in F]
allx = np.concatenate(list(groups.values()))
lo, hi = allx.min() - 1, allx.max() + 1 # common x-range for both curves
fig, ax = plt.subplots(figsize=(8, 5))
for (name, d), f, c in zip(groups.items(), F, palette):
ax.step(np.r_[lo, f.quantiles, hi], np.r_[0, f.probabilities, 1], where="post",
color=c, lw=2, label=f"Rounds {name} (n = {len(d)}, median {np.median(d):+.0f})")
# Mark the KS distance
ax.plot([x_gap, x_gap], y_gap, color="#FF3B30", lw=2.5, solid_capstyle="round", zorder=5)
ax.scatter([x_gap, x_gap], y_gap, color="#FF3B30", s=30, zorder=6)
ax.annotate(f"D = {ks.statistic:.2f}\nat {x_gap:+.0f}", (x_gap + 0.1, min(y_gap)),
xytext=(x_gap + 0.6, min(y_gap) - 0.14), ha="left", va="center", fontsize=10,
fontweight="semibold", color="#FF3B30",
arrowprops=dict(arrowstyle="-", color="#FF3B30", lw=0.8, shrinkB=2))
ax.set_xlim(lo, hi)
ax.set_xticks(np.arange(-10, hi, 2))
ax.set_ylim(0, 1.02)
ax.set_yticks(np.linspace(0, 1, 5), [f"{v:.0%}" for v in np.linspace(0, 1, 5)])
ax.set_xlabel("Round score relative to par (strokes; lower is better)")
ax.set_ylabel("Cumulative share of rounds")
ax.legend(loc="lower right")
ax.set_title(f"The KS statistic is the widest vertical gap between the two ECDFs: D = {ks.statistic:.2f}", pad=26)
ax.text(0, 1.02, f"n = {len(allx)} rounds (simulated) · two-sample Kolmogorov–Smirnov "
f"D = {ks.statistic:.3f}, p = {ks.pvalue:.1e}", transform=ax.transAxes,
fontsize=9.5, color="#6E6E73")
plt.show()
# ECDF comparison: the R equivalent of plot.py
# Simulated data, set in the context of Pastoriza Rivas & Warin (2022) [pastoriza2022]
# R and NumPy draw different random numbers, so the values differ slightly from the Python figure.
library(ggplot2)
set.seed(2022)
# Data: round score to par (strokes) in two periods of the career
early <- round(rnorm(320, -2.4, 2.9))
late <- round(rnorm(200, -0.6, 3.1))
label <- function(name, x) sprintf("Rounds %s (n = %d, median %+.0f)", name, length(x), median(x))
d <- data.frame(score = c(early, late),
period = rep(c(label("1997–2009", early), label("2010–2019", late)),
c(length(early), length(late))))
# Two-sample Kolmogorov–Smirnov test: D is the largest vertical gap
# (the p-value is approximate, because whole-stroke scores have many ties)
ks <- suppressWarnings(ks.test(early, late, exact = FALSE))
D <- unname(ks$statistic)
values <- sort(unique(d$score))
x_gap <- values[which.max(abs(ecdf(early)(values) - ecdf(late)(values)))]
gap <- data.frame(x = x_gap, y = c(ecdf(early)(x_gap), ecdf(late)(x_gap)))
lo <- min(d$score) - 1 # common x-range for both curves
hi <- max(d$score) + 1
p <- ggplot(d, aes(score, colour = period)) +
stat_ecdf(geom = "step", pad = TRUE, linewidth = 0.9) +
scale_colour_manual(NULL, values = c("#007AFF", "#FF9500")) +
# Mark the KS distance
geom_line(data = gap, aes(x, y), colour = "#FF3B30", linewidth = 1.2, lineend = "round") +
geom_point(data = gap, aes(x, y), colour = "#FF3B30", size = 2) +
annotate("segment", x = x_gap + 0.1, y = min(gap$y), xend = x_gap + 0.55, yend = min(gap$y) - 0.11,
colour = "#FF3B30", linewidth = 0.35) +
annotate("text", x = x_gap + 0.6, y = min(gap$y) - 0.14, hjust = 0, lineheight = 0.95,
label = sprintf("D = %.2f\nat %+.0f", D, x_gap), colour = "#FF3B30", fontface = "bold",
size = 3.5) +
scale_x_continuous(breaks = seq(-10, hi, 2)) +
scale_y_continuous(breaks = seq(0, 1, 0.25), labels = scales::percent) +
coord_cartesian(xlim = c(lo, hi), ylim = c(0, 1.02), expand = FALSE) +
labs(title = sprintf("The KS statistic is the widest vertical gap between the two ECDFs: D = %.2f", D),
subtitle = sprintf("n = %d rounds (simulated) · two-sample Kolmogorov–Smirnov D = %.3f, p = %.1e",
nrow(d), D, ks$p.value),
x = "Round score relative to par (strokes; lower is better)",
y = "Cumulative share of rounds") +
theme_minimal(base_size = 11) +
theme(plot.title = element_text(face = "bold", size = 11.5),
plot.subtitle = element_text(size = 8.5, colour = "#6E6E73"),
panel.grid.minor = element_blank(),
legend.position = "inside", legend.position.inside = c(0.98, 0.04),
legend.justification = c(1, 0),
legend.background = element_rect(fill = "white", colour = NA),
plot.margin = margin(8, 14, 8, 8))
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. - Pastoriza Rivas & Warin (2022), Tiger Woods press conferences and performance. Pastoriza Rivas, D., & Warin, T. (2022). Dataset of two decades of Tiger Woods press conferences and tournament performance. Data in Brief, 41, 107955. https://doi.org/10.1016/j.dib.2022.107955
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). ECDF comparison. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/distributions/ecdf-comparison/
@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 Distributions
Histogramme avec densité
Histogramme, densité par noyau et courbe normale ajustée, avec statistiques de forme.
ggplot2::geom_histogram() + geom_density()Graphique en nuage de pluie
Demi-violon, boîte à moustaches et points bruts par groupe, tracés à l'horizontale.
ggdist::stat_halfeye() / ggrain::geom_rain()Graphique en crêtes
Courbes de densité qui se chevauchent pour comparer une distribution entre de nombreux groupes.
ggridges::geom_density_ridges()