ECDF の比較

2群の経験累積分布関数を、コルモゴロフ・スミルノフ統計量の差とともに描きます。

ECDF の比較

経験累積分布関数(ECDF)は、x軸上の各値について、その値以下の観測値の割合をプロットしたものです。ヒストグラムと違って階級の設定が不要で、あらゆる分位点を直接読み取れます。2つの ECDF を重ねて描くと、両者の垂直方向の最大距離がそのまま2標本 コルモゴロフ・スミルノフ 統計量 D となり、ここでは赤い線分で示しています。

舞台は Pastoriza Rivas & Warin(2022、Data in Brief)による、タイガー・ウッズの20年にわたる記者会見とトーナメント成績のデータセットです。ここでの数値は説明のために シミュレーション したもの——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}
}

分布のその他のグラフ