ECDF comparison
Empirical cumulative distributions of two groups, with the Kolmogorov–Smirnov gap.

An empirical cumulative distribution function (ECDF) plots, for every value on the x-axis, the share of observations at or below it. Unlike a histogram it needs no bins, and every quantile can be read off directly. When two ECDFs are drawn together, the largest vertical distance between them is exactly the two-sample Kolmogorov–Smirnov statistic D, drawn here as a red segment.
The setting is Pastoriza Rivas & Warin (2022, Data in Brief), a dataset of
two decades of Tiger Woods' press conferences and tournament performance.
The numbers here are simulated for illustration — round scores relative
to par (whole strokes, lower is better) for n = 520 rounds, 1997–2009 versus
2010–2019 — and are not the paper's data or results. scipy.stats.ecdf
builds the curves and scipy.stats.ks_2samp returns D, its location and the
p-value (approximate here, because whole-stroke scores have many ties).
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)
Figures use the optional PyStatlas style: add plt.style.use("pystatlas.mplstyle") to match the look exactly.
Data source
- 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.
The examples illustrate statistical methods. Their numbers are simulated unless an entry says otherwise, and their titles describe what each figure shows in these simulated data — not findings of the cited papers, nor the author's position on the substantive question. For results, context and data, rely on the papers cited here.
How to cite
PyStatlas is created and maintained by Thierry Warin. If it helped your work, please cite it.
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}
}More in Distributions
Histogram with density
Histogram, kernel density and fitted normal curve, with shape statistics.
ggplot2::geom_histogram() + geom_density()Raincloud plot
Half violin, box plot and raw points per group, drawn horizontally.
ggdist::stat_halfeye() / ggrain::geom_rain()Ridgeline plot
Overlapping density curves to compare one distribution across many groups.
ggridges::geom_density_ridges()