svgbrushableecdf
ECDF
What share of values falls below any threshold, and how do groups differ across the whole range?
How to read it
- Pick a value on the x axis and read up: the curve's height is the share of rows at or below that value.
- Read across at 50% to find each group's median, at 90% for the upper tail.
- Where one curve sits to the right of another across the whole range, that group has larger values throughout.
- Callout 1: Read across at 50%: each group's median.
- Callout 2: The curve further right has larger values at that share.
- Callout 3: The band: uncertainty around each curve.
Watch out
- Steep is not high: a steep section means many values packed into a narrow range.
- Crossing curves mean no group is larger throughout; say where each one leads.
Defaults
- DKW 95% band
- On
- Shade a band that holds the whole true curve 95% of the time.
- Median reference
- On
- Draw a reference at 50%, so you can read medians off the curve.
- Show 1 − F (exceedance)
- Off
- Plot the share above each value rather than below it.
Pinned in the code
- F̂(x) = #{xᵢ ≤ x}/n, right-continuous steps (R `ecdf`, `scipy.stats.ecdf`).
- Band: Dvoretzky–Kiefer–Wolfowitz, F̂ ± ε with ε = √(ln(2/α)/(2n)), α = 0.05, clipped to [0, 1] — simultaneous over x.
- Median marker at the type-7 median.
# ECDF — Codesplash Chart Lab (recipe "ecdf")
# controls: band=true, median=true, complement=false
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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]
df = pd.read_csv("ecdf-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["device"] = pd.Categorical(df["device"].astype("string"), categories=["Desktop", "Mobile", "Tablet"])
def groups(frame, value, group=None, max_levels=12):
"""(label, values) per group in level order; rows missing the value or the group are dropped."""
if group is None:
return [(value, frame[value].dropna().to_numpy(dtype=float))]
d = frame[[value, group]].dropna()
out = []
for level in list(d[group].cat.categories)[:max_levels]:
v = d.loc[d[group] == level, value].to_numpy(dtype=float)
if v.size:
out.append((str(level), v))
return out
parts = groups(df, "minutes", "device", max_levels=8)
fig, ax = plt.subplots(figsize=(7, 4))
for i, (label, v) in enumerate(parts):
color = PALETTE[i % len(PALETTE)]
many = len(parts) > 1 # several groups: a dash and a median marker shape per group, as in the app
ax.ecdf(v, complementary=False, color=color, linewidth=1.8, linestyle=SERIES_DASHES[i % 8] if many else "-", label=label) # F̂(x) = #{xᵢ ≤ x}/n, right-continuous
xs = np.unique(v)
F = np.searchsorted(np.sort(v), xs, side="right") / v.size
eps = np.sqrt(np.log(2 / 0.05) / (2 * v.size)) # DKW 95% band, simultaneous over x
lo, hi = np.clip(F - eps, 0, 1), np.clip(F + eps, 0, 1)
ax.fill_between(xs, lo, hi, step="post", color=color, alpha=0.15, linewidth=0)
ax.axvline(np.median(v), color=color, linestyle=":", linewidth=1) # type-7 median
ax.plot([np.median(v)], [0.5], linestyle="none", marker=SERIES_MARKERS[i % 8] if many else "o", markersize=6, markerfacecolor=plt.rcParams["axes.facecolor"], markeredgecolor=color, markeredgewidth=1.5)
ax.set_xlabel("minutes")
ax.set_ylabel("F(x)")
if len(parts) > 1:
ax.legend()
plt.show()Needs pandas, numpy, matplotlib · reads ecdf-demo.csv · app theme from the optional codesplash helper
# ECDF — Codesplash Chart Lab (recipe "ecdf")
# controls: band=true, median=true, complement=false
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
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["solid", "6px,3px", "1.5px,2.5px", "8px,3px,2px,3px", "12px,4px", "3px,3px", "8px,2px,2px,2px,2px,2px", "1.5px,5px"]
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
df = pd.read_csv("ecdf-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["device"] = pd.Categorical(df["device"].astype("string"), categories=["Desktop", "Mobile", "Tablet"])
def groups(frame, value, group=None, max_levels=12):
"""(label, values) per group in level order; rows missing the value or the group are dropped."""
if group is None:
return [(value, frame[value].dropna().to_numpy(dtype=float))]
d = frame[[value, group]].dropna()
out = []
for level in list(d[group].cat.categories)[:max_levels]:
v = d.loc[d[group] == level, value].to_numpy(dtype=float)
if v.size:
out.append((str(level), v))
return out
def rgba(color, alpha):
r, g, b = px.colors.hex_to_rgb(color) if color.startswith("#") else px.colors.unlabel_rgb(color)
return f"rgba({r:.0f}, {g:.0f}, {b:.0f}, {alpha})"
parts = groups(df, "minutes", "device", max_levels=8)
fig = go.Figure()
for i, (label, v) in enumerate(parts):
color = PALETTE[i % len(PALETTE)]
xs = np.unique(v)
F = np.searchsorted(np.sort(v), xs, side="right") / v.size # F̂(x) = #{xᵢ ≤ x}/n
eps = np.sqrt(np.log(2 / 0.05) / (2 * v.size)) # DKW 95% band
lo, hi = np.clip(F - eps, 0, 1), np.clip(F + eps, 0, 1)
fig.add_scatter(x=xs, y=lo, mode="lines", line=dict(width=0, shape="hv"), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=xs, y=hi, mode="lines", line=dict(width=0, shape="hv"), fill="tonexty", fillcolor=rgba(color, 0.15), showlegend=False, hoverinfo="skip")
many = len(parts) > 1 # several groups: a dash and a median marker shape per group, as in the app
fig.add_scatter(x=xs, y=F, mode="lines", line=dict(color=color, width=2, shape="hv", dash=SERIES_DASHES[i % 8] if many else "solid"), name=label)
fig.add_vline(x=np.median(v), line=dict(color=color, dash="dot", width=1)) # type-7 median
fig.add_scatter(x=[np.median(v)], y=[0.5], mode="markers", marker=dict(symbol=SERIES_MARKERS[i % 8] if many else "circle", size=8, color="rgba(0,0,0,0)", line=dict(color=color, width=1.5)), showlegend=False, hoverinfo="skip")
fig.update_layout(xaxis_title="minutes", yaxis_title="F(x)", yaxis_range=[0, 1.02], showlegend=len(parts) > 1)
fig.show()Needs pandas, numpy, plotly · reads ecdf-demo.csv · app theme from the optional codesplash helper
# ECDF — Codesplash Chart Lab (recipe "ecdf")
# controls: band=true, median=true, complement=false
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))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("ecdf-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["device"]] <- factor(df[["device"]], levels = c("Desktop", "Mobile", "Tablet"))
groups_of <- function(df, value, group = NULL, max_levels = 12) {
# values per group in level order; rows missing the value or the group are dropped
v <- df[[value]]
if (is.null(group)) return(stats::setNames(list(v[is.finite(v)]), value))
g <- df[[group]]
keep <- is.finite(v) & !is.na(g)
out <- split(v[keep], factor(g[keep], levels = utils::head(levels(g), max_levels)))
out[lengths(out) > 0]
}
parts <- groups_of(df, "minutes", "device", max_levels = 8)
steps <- do.call(rbind, lapply(names(parts), function(k) {
v <- parts[[k]]
xs <- sort(unique(v))
F <- ecdf(v)(xs) # F̂(x) = #{xᵢ ≤ x}/n, right-continuous
eps <- sqrt(log(2 / 0.05) / (2 * length(v))) # DKW 95% band, simultaneous over x
data.frame(group = k, x = xs, xend = c(xs[-1], max(xs)), F = F, lo = pmax(F - eps, 0), hi = pmin(F + eps, 1))
}))
steps$group <- factor(steps$group, levels = names(parts))
cols <- setNames(rep(cs_cat, length.out = length(parts)), names(parts))
p <- ggplot(steps)
p <- p + geom_rect(aes(xmin = x, xmax = xend, ymin = lo, ymax = hi, fill = group), alpha = 0.15, show.legend = FALSE)
p <- p + geom_step(aes(x, F, colour = group, linetype = group), direction = "hv", linewidth = 0.9) # dash per group, as in the app
med <- data.frame(group = factor(names(parts), levels = names(parts)), m = vapply(parts, median, 0)) # type-7 median
p <- p + geom_vline(data = med, aes(xintercept = m, colour = group), linetype = "dotted", show.legend = FALSE)
p <- p + geom_point(data = med, aes(x = m, y = 0.5, colour = group, shape = group), size = 2.2, show.legend = FALSE) + scale_shape_manual(values = cs_shapes)
p <- p + scale_colour_manual(values = cols) + scale_fill_manual(values = cols) + scale_linetype_manual(values = cs_linetypes) +
labs(x = "minutes", y = "F(x)", colour = NULL, linetype = NULL) + theme_cs
if (length(parts) == 1) p <- p + theme(legend.position = "none")
print(p)Needs ggplot2 · reads ecdf-demo.csv · app theme from the optional codesplashr helper
-- ECDF — Codesplash Chart Lab (recipe "ecdf")
-- controls: band=true, median=true, complement=false
-- empirical CDF per group: F̂(x) = #{xᵢ ≤ x}/n at each distinct value (cume_dist), with the
-- Dvoretzky–Kiefer–Wolfowitz 95% band F̂ ± √(ln(2/0.05)/(2n)) clipped to [0, 1]
WITH v0 AS (
SELECT "device"::VARCHAR AS grp, "minutes"::DOUBLE AS x
FROM read_csv('ecdf-demo.csv')
WHERE "minutes" IS NOT NULL AND isfinite("minutes"::DOUBLE) AND "device" IS NOT NULL
),
lv AS ( -- level order as stored in the data dictionary; at most 8 groups
SELECT grp, row_number() OVER (ORDER BY list_position(['Desktop', 'Mobile', 'Tablet'], grp)) AS rk
FROM (SELECT grp, count(*) AS n FROM v0 GROUP BY grp)
),
v AS (SELECT v0.grp, v0.x, lv.rk FROM v0 JOIN lv USING (grp) WHERE lv.rk <= 8),
n AS (SELECT grp, rk, count(*) AS n FROM v GROUP BY grp, rk),
e AS (SELECT DISTINCT grp, x, cume_dist() OVER (PARTITION BY grp ORDER BY x) AS f FROM v)
SELECT e.grp AS "group", e.x, e.f AS ecdf,
greatest(e.f - sqrt(ln(2 / 0.05) / (2 * n.n)), 0) AS band_lo,
least(e.f + sqrt(ln(2 / 0.05) / (2 * n.n)), 1) AS band_hi,
1 - e.f AS exceedance
FROM e JOIN n USING (grp)
ORDER BY n.rk, e.x;Needs duckdb · reads ecdf-demo.csv