Skip to content
svgecdf-two-sample

Two-sample ECDF with KS gap

Where do two distributions differ most?

Demo data · seed 20261101 · 80 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read each curve as a group's cumulative share.
  2. The marked vertical gap is the largest distance: the Kolmogorov–Smirnov D.
  3. Look at where it falls: location, spread and tails produce different gaps.
  1. Callout 1: The largest gap between the curves: D.
  2. Callout 2: Curves meet at 1.

Watch out

  • D is most sensitive around the centre of the distributions, less so in the tails.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • ECDFs are right-continuous steps (F(x) = share of values ≤ x) — the same definition as R's ecdf and scipy's ks_2samp.
  • D is the largest |F₁(x) − F₂(x)| over the pooled observed values; the marker sits at the first value where it occurs.
  • The test's p-value (exact or asymptotic) comes from the engine; the chart shows where the gap is.
# Two-sample ECDF with KS gap — Codesplash Chart Lab (recipe "ecdf-two-sample")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

try:
    import codesplash as cs  # optional: the app's chart theme
except ImportError:
    cs = None
if cs:
    cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]

df = pd.read_csv("ecdf-two-sample-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["courier"] = pd.Categorical(df["courier"].astype("string"), categories=["Northside", "Express"])

_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"])  # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"])  # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
def levels_of(s):
    """Declared level order (categoricals), else order of first appearance."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [v for v in s.cat.categories if (s == v).any()]
    return list(dict.fromkeys(s.dropna().astype(str)))
V = "minutes"
G = "courier"
d = df.dropna(subset=[V, G])
g1, g2 = levels_of(d[G])[:2]
a, b = np.sort(d.loc[d[G].astype(str) == str(g1), V].to_numpy(float)), np.sort(d.loc[d[G].astype(str) == str(g2), V].to_numpy(float))
grid = np.unique(np.concatenate([a, b]))
fa, fb = np.searchsorted(a, grid, side="right") / len(a), np.searchsorted(b, grid, side="right") / len(b)  # right-continuous ECDFs
k = int(np.argmax(np.abs(fa - fb)))  # Kolmogorov–Smirnov D: the largest vertical gap
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.step(grid, fa, where="post", color=PALETTE[0], label=f"{g1} (n = {len(a)})")
ax.step(grid, fb, where="post", color=PALETTE[1], label=f"{g2} (n = {len(b)})")
ax.vlines(grid[k], fa[k], fb[k], colors=REF, linestyles="--", linewidth=2)
ax.annotate(f"D = {abs(fa[k] - fb[k]):.3f}", (grid[k], (fa[k] + fb[k]) / 2), xytext=(6, 0), textcoords="offset points", fontsize=9)
ax.set_xlabel(V)
ax.set_ylabel("cumulative share")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads ecdf-two-sample-demo.csv · app theme from the optional codesplash helper