Comparing whole distributions
When you care about more than the mean, compare groups with the two-sample Kolmogorov–Smirnov, Cramér–von Mises and k-sample Anderson–Darling tests.
What runs in CodeSplash
- STAT117Two sample Kolmogorov–Smirnov test Runs in CodeSplash
- STAT119Anderson–Darling k sample test Runs in CodeSplash
- STAT121Cramér–von Mises two sample test Runs in CodeSplash
- Compare distributions (two or more groups) Verified in Python and R
You will be able to
- Say when a test of whole distributions answers your question better than a test of means
- Read a two-sample KS result, including its one-sided form
- Choose among KS, CvM and k-sample AD before you look
Read first
Same mean, different story
PredictPredict first
Two groups have nearly the same mean, but one group is very spread out and the other is tightly packed.
Which test is more likely to notice?
Reveal
The KS test. A t test compares means and has nothing to find. KS compares the whole curve, so a difference in spread shows up as a gap in the tails.
The gap between two ECDFs
ReadThe two-sample Kolmogorov–SmirnovKolmogorov–Smirnov testCompares distributions by the largest vertical gap (D) between their cumulative curves. statistic is the largest vertical gap between the groups' ECDFs:
For tooth growth by supplement, D = 0.333, p = .062, from exact calculation.
Tooth growth in guinea pigsSee the gap
ExploreChange the shift and the spread of the two samples below. Find a setting where the means match but the curves still come apart.
BExplorable · Two sample Kolmogorov–Smirnov test
Do two samples come from the same distribution?
Your data
Drag a point or use ↑/↓ to change itIf H₀ were true
- The reference: how D varies across samples when H₀ is true.
- Your statistic, from the data above.
- The p-value: the area at least as extreme as yours (p = .002).
- The hatched rejection region at α = .050: statistics landing here reject H₀.
The formula
With your numbers
- empirical CDF of sample j
- the largest vertical gap over all x
The verdict
D = 0.530, p = .002
p ≤ α = .050: reject H₀
Effect size: largest gap between the ECDFs D = 0.530
Sensitive to any difference — location, spread, shape — but most sensitive near the middle and weak in the tails.
- Statistic
- 0.530
- p-value
- 0.0023
Two sample Kolmogorov–Smirnov test on Group 1: n = 20; Group 2: n = 25: D = 0.530, p = .002. The p-value is below α = .050, so the data are hard to reconcile with H₀.
Three tests
ReadKS is sensitive near the middle of the distribution and less so in the tails, where the ECDFs are pinned close to 0 and 1.
- Cramér–von MisesCramér–von Mises testGoodness-of-fit test summing the squared gaps between the data's ECDF and the fitted distribution over all values. adds up squared gaps across the range: p = .057 here.
- Anderson–DarlingAnderson–Darling testGoodness-of-fit test that weighs the tails more than Kolmogorov–Smirnov, so it notices heavy or light tails sooner. weights the tails more, and handles three or more groups.
For chick weights across 6 feeds and 71 chicks, A² = 22.8, p = .002 by permutation. The asymptotic table gives p = .001.
Anderson–Darling k-sample test, statistic = 22.82, p = .002
- Statistic
- 22.822
- p
- 0.0020
Plots
View data
| feed | weight |
|---|---|
| horsebean | 179 |
| horsebean | 160 |
| horsebean | 136 |
| horsebean | 227 |
| horsebean | 217 |
| horsebean | 168 |
| horsebean | 108 |
| horsebean | 124 |
| horsebean | 143 |
| horsebean | 140 |
| linseed | 309 |
| linseed | 229 |
| linseed | 181 |
| linseed | 141 |
| linseed | 260 |
| linseed | 203 |
| linseed | 148 |
| linseed | 169 |
| linseed | 213 |
| linseed | 257 |
| linseed | 244 |
| linseed | 271 |
| soybean | 243 |
| soybean | 230 |
| soybean | 248 |
| soybean | 327 |
| soybean | 329 |
| soybean | 250 |
| soybean | 193 |
| soybean | 271 |
| soybean | 316 |
| soybean | 267 |
| soybean | 199 |
| soybean | 171 |
| soybean | 158 |
| soybean | 248 |
| sunflower | 423 |
| sunflower | 340 |
| sunflower | 392 |
| sunflower | 339 |
| sunflower | 341 |
| sunflower | 226 |
| sunflower | 320 |
| sunflower | 295 |
| sunflower | 334 |
| sunflower | 322 |
| sunflower | 297 |
| sunflower | 318 |
| meatmeal | 325 |
| meatmeal | 257 |
| meatmeal | 303 |
| meatmeal | 315 |
| meatmeal | 380 |
| meatmeal | 153 |
| meatmeal | 263 |
| meatmeal | 242 |
| meatmeal | 206 |
| meatmeal | 344 |
| meatmeal | 258 |
| casein | 368 |
First 60 of 71 rows.
Assumptions
- Independent groups — Each value belongs to one group and the groups are sampled independently.
Distribution tests
| Test | Statistic | df | p | p-value from |
|---|---|---|---|---|
| Anderson–Darling k-sample | 22.822 | — | .002 | permutation |
Groups
| feed | n | Median | IQR |
|---|---|---|---|
| casein | 12 | 342 | 93.500 |
| horsebean | 10 | 151.50 | 39.250 |
| linseed | 12 | 221 | 79.750 |
| meatmeal | 11 | 263 | 70.500 |
| soybean | 14 | 248 | 63.250 |
| sunflower | 12 | 328 | 27.500 |
- Distribution tests compare whole distributions, not just centers: a small p says the shapes, spreads or locations differ somewhere.
- Permutation p-values relabel the pooled values 499 times (seed 42); the smallest possible p is 1/500.
The exact R script · R R version 4.5.1 (2025-06-13)
# Compare distributions (two or more groups)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method distribution.compare 1.0.1 · spec 2114eccd843bdc4c
# Dataset: chickwts (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/chickwts.parquet", col_select = c("weight", "feed")))
n_input <- nrow(df)
df[["feed"]] <- factor(df[["feed"]], levels = c("casein", "horsebean", "linseed", "meatmeal", "soybean", "sunflower")) # stored level order
df <- df[stats::complete.cases(df[c("weight", "feed")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("weight", "feed")) # infinite values stop the run (registry/errors.yaml)
# %% Test
y <- "weight"
g <- "feed"
present <- Filter(function(lv) any(df[[g]] == lv), levels(df[[g]]))
levels_g <- as.character(present)
groups <- lapply(present, function(lv) as.numeric(df[[y]][df[[g]] == lv]))
k <- length(groups)
test <- "ad"
alternative <- "two.sided"
calibration <- "auto"
seed <- 42 # permutations relabel the pooled sample with the shared Wichmann-Hill stream
reps <- as.integer(499)
sesoi <- NULL
alpha <- 0.05
two_only <- c("ks", "cvm", "bws", "es", "lepage", "cucconi", "runs")
labels_t <- c(ks = "Kolmogorov–Smirnov", ad = "Anderson–Darling k-sample", cvm = "Cramér–von Mises",
bws = "Baumgartner–Weiß–Schindler", es = "Epps–Singleton", lepage = "Lepage (location and scale)",
cucconi = "Cucconi (location and scale)", runs = "Wald–Wolfowitz runs")
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = g, min = 2, k = k)
lead <- if (test %in% c("auto", "all")) (if (k == 2) "ks" else "ad") else test
if (k != 2 && lead %in% two_only) stop(sprintf("The %s test compares two groups; %s has %d. Use Anderson–Darling k-sample.", labels_t[[lead]], g, k))
names_t <- c(lead, if (test == "all") Filter(function(t) t != lead && (k == 2 || !(t %in% two_only)), cs_compare_test_names()) else character(0))
results <- lapply(names_t, function(t) cs_compare_test(groups, t, alternative = if (t == "ks") alternative else "two.sided",
calibration = calibration, reps = reps, seed = seed))
main <- results[[1]]
ks_d <- if (k == 2) cs_compare_test(groups, "ks")$statistic else NaN
# %% Result
n_all <- sum(vapply(groups, length, numeric(1)))
n_reject <- sum(vapply(results, function(r) is.finite(r$p) && r$p < alpha, logical(1)))
values <- list(n = n_all, groups = k, test = lead, statistic = main$statistic, p = main$p, calibration = main$calibration,
ks_d = ks_d, n_reject = n_reject)
for (i in seq_len(k)) values[[sprintf("n[%s]", levels_g[i])]] <- length(groups[[i]])
if (test == "all") {
for (r in results) values[[sprintf("stat[%s]", r$test)]] <- r$statistic
for (r in results) values[[sprintf("p[%s]", r$test)]] <- r$p
}
verdict <- if (main$p < alpha) "differ" else "show no evidence of differing"
summary <- sprintf("%s: statistic = %s, %s (%s%s). The distributions of %s across %s %s.", main$label, formatC(main$statistic, digits = 4, format = "g"),
cs_fmt_p(main$p), main$calibration, if (main$calibration == "permutation") sprintf(", %d permutations, seed %d", reps, as.integer(seed)) else "",
y, g, verdict)
if (k == 2) {
summary <- paste0(summary, sprintf(" The largest gap between the two ECDFs is D = %.3f", ks_d),
if (!is.null(sesoi)) sprintf(" — %s the smallest difference of interest (%s).", if (ks_d > sesoi) "beyond" else "within", format(sesoi)) else ".")
}
if (test == "all") summary <- paste0(summary, sprintf(" %d of %d tests reject at α = .05.", n_reject, length(results)))
rows <- lapply(results, function(r) list(test = r$label, statistic = r$statistic, df = r$df, p = r$p, calibration = r$calibration))
notes <- list("Distribution tests compare whole distributions, not just centers: a small p says the shapes, spreads or locations differ somewhere.")
if (any(vapply(results, function(r) r$calibration == "permutation", logical(1)))) {
notes[[length(notes) + 1]] <- sprintf("Permutation p-values relabel the pooled values %d times (seed %d); the smallest possible p is 1/%d.", reps, as.integer(seed), reps + 1)
}
if (lead == "runs" && isTRUE(main$extra$ties_between > 0)) {
warnings <- c(warnings, sprintf("%d tied value(s) occur in both groups; runs were counted with the tied values arranged to give the most runs (conservative).", as.integer(main$extra$ties_between)))
}
if (lead == "ks" && main$calibration == "exact" && length(unique(unlist(groups))) < n_all) {
notes[[length(notes) + 1]] <- "Ties: the exact p is computed conditionally on the tied values (the bound is checked only where the pooled sample changes value)."
}
q <- function(x, p) stats::quantile(x, p, names = FALSE, type = 7)
cs_publish(list(
method = "distribution.compare",
methodVersion = "1.0.1",
title = paste("Distribution comparison —", main$label),
engine = cs_engine_info("stats", "nanoparquet"),
n = n_all,
summary = summary,
apa = paste0(sprintf("%s test, statistic = %.2f, %s", main$label, main$statistic, cs_fmt_p(main$p)), if (k == 2) sprintf(", D = %.2f", ks_d) else ""),
statistics = c(list(list(key = "statistic", label = "Statistic", value = main$statistic), list(key = "p", label = "p", value = main$p)),
if (k == 2) list(list(key = "ks_d", label = "KS D", value = ks_d)) else list()),
tables = list(
list(key = "tests", title = "Distribution tests", columns = list(
list(key = "test", label = "Test", type = "string"), list(key = "statistic", label = "Statistic", type = "number"),
list(key = "df", label = "df", type = "number"), list(key = "p", label = "p", type = "pvalue"),
list(key = "calibration", label = "p-value from", type = "string")), rows = rows),
list(key = "groups", title = "Groups", columns = list(
list(key = "group", label = g, type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "median", label = "Median", type = "number"), list(key = "iqr", label = "IQR", type = "number")),
rows = lapply(seq_len(k), function(i) list(group = levels_g[i], n = length(groups[[i]]), median = stats::median(groups[[i]]),
iqr = q(groups[[i]], 0.75) - q(groups[[i]], 0.25))))
),
effectSizes = if (k == 2) list(list(key = "ks_d", label = "Kolmogorov–Smirnov D (largest ECDF gap)", value = ks_d, method = "max |F₁ − F₂|")) else list(),
assumptions = list(list(key = "independence", label = "Independent groups", status = "info", detail = "Each value belongs to one group and the groups are sampled independently.")),
warnings = warnings,
notes = notes,
charts = list(cs_chart("ecdf", "ecdf", sprintf("ECDFs of %s by %s", y, g), list(x = cs_col(y, df[[y]]), group = cs_col(g, as.character(df[[g]]), levels = levels_g)))),
values = values
))
Anderson–Darling k-sample test, statistic = 22.82, p = .002
- Statistic
- 22.822
- p
- 0.0020
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Independent groups — Each value belongs to one group and the groups are sampled independently.
Distribution tests
| Test | Statistic | df | p | p-value from |
|---|---|---|---|---|
| Anderson–Darling k-sample | 22.822 | — | .002 | permutation |
Groups
| feed | n | Median | IQR |
|---|---|---|---|
| casein | 12 | 342 | 93.500 |
| horsebean | 10 | 151.50 | 39.250 |
| linseed | 12 | 221 | 79.750 |
| meatmeal | 11 | 263 | 70.500 |
| soybean | 14 | 248 | 63.250 |
| sunflower | 12 | 328 | 27.500 |
- Distribution tests compare whole distributions, not just centers: a small p says the shapes, spreads or locations differ somewhere.
- Permutation p-values relabel the pooled values 499 times (seed 42); the smallest possible p is 1/500.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Compare distributions (two or more groups)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method distribution.compare 1.0.1 · spec 2114eccd843bdc4c
# Dataset: chickwts (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.stats import distribution as csd
# %% Data
df = pd.read_parquet("tests/parity/fixtures/chickwts.parquet", columns=["weight", "feed"])
n_input = len(df)
df["feed"] = pd.Categorical(df["feed"], categories=["casein", "horsebean", "linseed", "meatmeal", "soybean", "sunflower"]) # stored level order
df = df.dropna(subset=["weight", "feed"]) # listwise deletion over the analysis columns
df["feed"] = df["feed"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["weight", "feed"]) # infinite values stop the run (registry/errors.yaml)
# %% Test
y = "weight"
g = "feed"
levels = [str(lv) for lv in df[g].cat.categories if (df[g] == lv).any()]
groups = [df.loc[df[g] == lv, y].to_numpy(dtype=float) for lv in df[g].cat.categories if (df[g] == lv).any()]
k = len(groups)
test = "ad"
alternative = "two.sided"
calibration = "auto"
seed, reps = 42, int(499) # permutations relabel the pooled sample with the shared Wichmann–Hill stream
sesoi = None
alpha = 0.05
if k < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=g, min=2, k=k)
lead = test if test not in ("auto", "all") else ("ks" if k == 2 else "ad")
if k != 2 and lead in csd.TWO_SAMPLE_ONLY:
raise ValueError(f"The {csd.COMPARE_TESTS[lead]} test compares two groups; {g} has {k}. Use Anderson–Darling k-sample.")
names = [lead] + ([t for t in csd.COMPARE_TESTS if t != lead and (k == 2 or t not in csd.TWO_SAMPLE_ONLY)] if test == "all" else [])
results = [csd.compare_test(groups, t, alternative=alternative if t == "ks" else "two.sided", calibration=calibration, reps=reps, seed=seed) for t in names]
main = results[0]
ks_d = csd.compare_test(groups, "ks")["statistic"] if k == 2 else math.nan
# %% Result
values = {"n": int(sum(len(x) for x in groups)), "groups": k, "test": lead, "statistic": main["statistic"], "p": main["p"],
"calibration": main["calibration"], "ks_d": ks_d, "n_reject": sum(1 for r in results if np.isfinite(r["p"]) and r["p"] < alpha)}
values.update({f"n[{lv}]": int(len(x)) for lv, x in zip(levels, groups)})
if test == "all":
values.update({f"stat[{r['test']}]": r["statistic"] for r in results})
values.update({f"p[{r['test']}]": r["p"] for r in results})
differ = main["p"] < alpha
verdict = "differ" if differ else "show no evidence of differing"
summary = (f"{main['label']}: statistic = {main['statistic']:.4g}, {cs.fmt_p(main['p'])} ({main['calibration']}"
+ (f", {reps} permutations, seed {seed}" if main["calibration"] == "permutation" else "") + f"). The distributions of {y} across {g} {verdict}.")
if k == 2:
summary += f" The largest gap between the two ECDFs is D = {ks_d:.3f}"
if sesoi is not None:
summary += f" — {'beyond' if ks_d > sesoi else 'within'} the smallest difference of interest ({sesoi:g})."
else:
summary += "."
if test == "all":
summary += f" {values['n_reject']} of {len(results)} tests reject at α = .05."
rows = [{"test": r["label"], "statistic": r["statistic"], "df": r["df"], "p": r["p"], "calibration": r["calibration"]} for r in results]
notes = ["Distribution tests compare whole distributions, not just centers: a small p says the shapes, spreads or locations differ somewhere."]
if any(r["calibration"] == "permutation" for r in results):
notes.append(f"Permutation p-values relabel the pooled values {reps} times (seed {seed}); the smallest possible p is 1/{reps + 1}.")
if lead == "runs" and main["extra"].get("ties_between"):
warnings.append(f"{main['extra']['ties_between']} tied value(s) occur in both groups; runs were counted with the tied values arranged to give the most runs (conservative).")
if lead == "ks" and main["calibration"] == "exact" and len(np.unique(np.concatenate(groups))) < values["n"]:
notes.append("Ties: the exact p is computed conditionally on the tied values (the bound is checked only where the pooled sample changes value).")
cs.publish({
"method": "distribution.compare",
"methodVersion": "1.0.1",
"title": f"Distribution comparison — {main['label']}",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": values["n"],
"summary": summary,
"apa": f"{main['label']} test, statistic = {main['statistic']:.2f}, {cs.fmt_p(main['p'])}" + (f", D = {ks_d:.2f}" if k == 2 else ""),
"statistics": [{"key": "statistic", "label": "Statistic", "value": main["statistic"]}, {"key": "p", "label": "p", "value": main["p"]}]
+ ([{"key": "ks_d", "label": "KS D", "value": ks_d}] if k == 2 else []),
"tables": [
{"key": "tests", "title": "Distribution tests", "columns": [
{"key": "test", "label": "Test", "type": "string"}, {"key": "statistic", "label": "Statistic", "type": "number"},
{"key": "df", "label": "df", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
{"key": "calibration", "label": "p-value from", "type": "string"}], "rows": rows},
{"key": "groups", "title": "Groups", "columns": [
{"key": "group", "label": g, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "median", "label": "Median", "type": "number"}, {"key": "iqr", "label": "IQR", "type": "number"}],
"rows": [{"group": lv, "n": int(len(x)), "median": float(np.median(x)), "iqr": float(np.subtract(*np.quantile(x, [0.75, 0.25])))} for lv, x in zip(levels, groups)]},
],
"effectSizes": [{"key": "ks_d", "label": "Kolmogorov–Smirnov D (largest ECDF gap)", "value": ks_d, "method": "max |F₁ − F₂|"}] if k == 2 else [],
"assumptions": [{"key": "independence", "label": "Independent groups", "status": "info", "detail": "Each value belongs to one group and the groups are sampled independently."}],
"warnings": warnings,
"notes": notes,
"charts": [cs.chart("ecdf", "ecdf", f"ECDFs of {y} by {g}", {"x": cs.col(y, df[y]), "group": cs.col(g, df[g].astype(str), levels=levels)})],
"values": values,
})
A one-sided trap
PredictPredict first
One-sided KS has an awkward direction. The alternative greater means the first group's ECDF sits above the second's.
An ECDF that sits higher reaches any given probability earlier. So what does it say about that group's values?
Reveal
They tend to be smaller. Higher curve, smaller values. In the tooth-growth example, orange juice is the first group with the larger values, so this alternative finds little: D = 0.067, p = .878.
What will the difference mean?
ReflectKS rejects, and you tell a colleague that the groups differ. They ask, "Differ how?"
Rejection doesn't say whether it's location, spread or shape. What would you show next? Think about the ECDF plot, and a follow-up focused on a feature you named in advance.
Also try deciding on a smallest gap you'd care about before you run it. Smallest KS distance of interest then says whether the observed D passes it.
Check your understanding
CheckpointCheck yourself
You suspect two groups differ only in their extreme values. Which test is the better first choice?
Show the answer
Answer: b
KS loses sensitivity in the tails, where both ECDFs are pinned close to 0 or 1. Anderson–Darling gives gaps there more weight. Choose it because of what you suspect, not because of the p-value.
Check yourself
At a tooth length of 18.8, two-thirds of the VC values and one-third of the OJ values lie at or below that length. That is the largest gap between their ECDFs. What is ? Give three decimals.
Show the answer
Answer: 0.333333333333333
. D is the largest vertical distance between the curves.
Check yourself
You have five groups. What does the method's Automatic setting use?
Show the answer
Answer: b
Automatic uses KS for two groups and Anderson–Darling for three or more. A significant result says that some group differs, not which one.
Do it in CodeSplash
In the appLeave Test on Automatic, or name your test in advance. Under p-value from, the automatic choice uses exact, asymptotic or permutation calibration according to the test.
Both scripts give D = 0.333. R's exact p-value allows for the tied lengths and matches the card, p = .062. SciPy's exact calculation doesn't allow for ties, so it reads a little higher.
import pandas as pd
from scipy import stats
d = pd.read_csv("toothgrowth.csv")
oj = d.loc[d["supp"] == "OJ", "len"]
vc = d.loc[d["supp"] == "VC", "len"]
print(stats.ks_2samp(oj, vc, method="exact"))d <- read.csv("toothgrowth.csv")
oj <- d$len[d$supp == "OJ"]
vc <- d$len[d$supp == "VC"]
ks.test(oj, vc, exact = TRUE)Recap
Recap- These tests compare whole distributions, so they can see differences a test of means can't.
- KS uses the largest gap; CvM adds up the gaps; AD weights the tails and handles several groups.
- A higher ECDF means smaller values, so check the direction of a one-sided KS test.
- A rejection doesn't say how the groups differ. Look at the curves.
Concepts in this lesson