ECDF 比较

两组的经验累积分布,并标出 Kolmogorov–Smirnov 最大差距。

ECDF 比较

经验累积分布函数(ECDF)对 x 轴上的每个值,绘出小于或等于该值的观测所占的比例。与直方图不同,它无需分箱,任何分位数都可以直接读出。将两条 ECDF 画在一起时,二者之间的最大垂直距离正是双样本 Kolmogorov–Smirnov 统计量 D,图中以红色线段表示。

本例的背景是 Pastoriza Rivas 与 Warin(2022,Data in Brief)发布的老虎伍兹二十年新闻发布会与赛事成绩数据集。此处的数字为说明而模拟——n = 520 轮比赛相对标准杆的单轮成绩(整数杆数,越低越好),比较 1997–2009 年与 2010–2019 年——并非论文的数据或结果。scipy.stats.ecdf 构建曲线,scipy.stats.ks_2samp 给出 D、其位置以及 p 值(由于整数杆数存在大量结,此处的 p 值为近似值)。

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

ecdf-comparison.py · 45 行
下载 GitHub
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()

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

这些示例用于说明统计方法。除条目另有说明外,其数值均为模拟数据,图表标题描述的是该图在这些模拟数据中呈现的内容——既不是所引论文的结论,也不是作者对实质问题的立场。关于结果、背景和数据,请以此处引用的论文为准。

如何引用

PyStatlas 由 Thierry Warin 创建并维护。如果它对你的工作有所帮助,敬请引用。

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

更多分布图表