svgecdf-two-sample
Two-sample ECDF with KS gap
Where do two distributions differ most?
How to read it
- Read each curve as a group's cumulative share.
- The marked vertical gap is the largest distance: the Kolmogorov–Smirnov D.
- Look at where it falls: location, spread and tails produce different gaps.
- Callout 1: The largest gap between the curves: D.
- 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
# Two-sample ECDF with KS gap — Codesplash Chart Lab (recipe "ecdf-two-sample")
# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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)
k = int(np.argmax(np.abs(fa - fb)))
fig = go.Figure()
fig.add_scatter(x=grid, y=fa, mode="lines", line_shape="hv", line_color=PALETTE[0], name=str(g1))
fig.add_scatter(x=grid, y=fb, mode="lines", line_shape="hv", line_color=PALETTE[1], name=str(g2))
fig.add_scatter(x=[grid[k], grid[k]], y=[fa[k], fb[k]], mode="lines+text", text=["", f"D = {abs(fa[k] - fb[k]):.3f}"], textposition="middle right", line=dict(color=REF, dash="dash", width=3), name="KS gap")
fig.update_layout(xaxis_title=V, yaxis_title="cumulative share")
fig.show()Needs pandas, numpy, plotly · reads ecdf-two-sample-demo.csv · app theme from the optional codesplash helper
# Two-sample ECDF with KS gap — Codesplash Chart Lab (recipe "ecdf-two-sample")
# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("ecdf-two-sample-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["courier"]] <- factor(df[["courier"]], levels = c("Northside", "Express"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
v_col <- "minutes"
g_col <- "courier"
d <- df[!is.na(df[[v_col]]) & !is.na(df[[g_col]]), ]
lv <- levels_of(d[[g_col]])[1:2]
a <- d[[v_col]][as.character(d[[g_col]]) == lv[1]]; b <- d[[v_col]][as.character(d[[g_col]]) == lv[2]]
grid <- sort(unique(c(a, b))); fa <- ecdf(a)(grid); fb <- ecdf(b)(grid)
k <- which.max(abs(fa - fb)) # Kolmogorov–Smirnov D
e <- rbind(data.frame(x = grid, f = fa, g = lv[1]), data.frame(x = grid, f = fb, g = lv[2]))
e$g <- factor(e$g, levels = lv)
p <- ggplot(e, aes(x, f, colour = g)) + geom_step() +
annotate("segment", x = grid[k], xend = grid[k], y = fa[k], yend = fb[k], linetype = "dashed", linewidth = 0.9, colour = ref_col) +
annotate("text", x = grid[k], y = (fa[k] + fb[k]) / 2, label = sprintf("D = %.3f", abs(fa[k] - fb[k])), hjust = -0.15, size = 3.2) +
scale_colour_manual(values = cs_cat[1:2], name = NULL) + labs(x = v_col, y = "cumulative share") + theme_cs
print(p)Needs ggplot2 · reads ecdf-two-sample-demo.csv · app theme from the optional codesplashr helper