Correlation matrices and the multiplicity trap
A matrix of many correlations will produce small p-values by chance. Adjust for it, understand pairwise and listwise deletion, and read the heatmap well.
What runs in CodeSplash
- Correlation matrix (Pearson / Spearman / Kendall) Verified in Python and R
You will be able to
- Count how many tests a correlation matrix contains
- Choose between Holm, Benjamini–Hochberg and no adjustment
- Explain pairwise versus listwise handling of missing values
- Read a correlation heatmap without over-reading it
How many tests is that?
ReadWith variables, a correlation matrix contains different pairs. Four variables give 6 tests. Twenty variables give 190.
If no variable were related to any other and you tested each pair at the 0.05 convention, you'd still expect about one "significant" correlation in every twenty pairs. A big matrix almost guarantees some.
Predict the surprises
PredictPredict first
Forty variables of pure noise make 780 pairs. Test each at the 0.05 convention with no adjustment. Roughly how many will come out "significant"?
Make your guess between 0 and 40 false alarms, then reveal.
Reveal
About 39, which is 780 × 0.05. All of them are false alarms, and any one of them could look like a discovery if you reported it alone.
Adjusting the p-values
ExploreA family-wiseFamily-wise error rateThe chance of at least one false positive across a family of tests. method such as HolmHolm correctionA step-down version of Bonferroni that controls the same error rate with more power; use it instead. controls the chance of any false alarm. A false discovery rateFalse discovery rateThe expected share of false positives among the results you call significant. method such as Benjamini–HochbergBenjamini–Hochberg procedureControls the false discovery rate by comparing sorted p-values with rising thresholds. controls the expected share of false alarms among the findings.
BExplorable · The Benjamini–Hochberg step-up
How does controlling the false discovery rate find more than Bonferroni while keeping errors in check?
How many tests will Benjamini–Hochberg reject?
Commit your prediction above to see the result
Make your prediction to see the result.
Slide the rejection line and see which p-values survive. Use Holm when one false claim would be costly. Use BH when you're screening for pairs to follow up.
Read the matrix
Readmpg and weight (1000 lbs): r = −.87, adjusted p < .001
- Pairs
- 6
- Significant (holm)
- 5
Plots
View data
| Variable | label | Variable | r |
|---|---|---|---|
| mpg | mpg | 1 | |
| weight (1000 lbs) | −.87* | mpg | −0.8677 |
| hp | −.78* | mpg | −0.7762 |
| qsec | .42* | mpg | 0.4187 |
| mpg | −.87* | weight (1000 lbs) | −0.8677 |
| weight (1000 lbs) | weight (1000 lbs) | 1 | |
| hp | .66* | weight (1000 lbs) | 0.6587 |
| qsec | −.17 | weight (1000 lbs) | −0.1747 |
| mpg | −.78* | hp | −0.7762 |
| weight (1000 lbs) | .66* | hp | 0.6587 |
| hp | hp | 1 | |
| qsec | −.71* | hp | −0.7082 |
| mpg | .42* | qsec | 0.4187 |
| weight (1000 lbs) | −.17 | qsec | −0.1747 |
| hp | −.71* | qsec | −0.7082 |
| qsec | qsec | 1 |
Assumptions
- Linear relationships — Coefficients summarize only this kind of association; check scatter plots of the strongest pairs.
- Rows per pair — Every pair has at least 10 complete rows (smallest n = 32).
Pairwise correlations
| Variable 1 | Variable 2 | n | r | 95% CI low | 95% CI high | p | p (holm) |
|---|---|---|---|---|---|---|---|
| mpg | weight (1000 lbs) | 32 | −0.8677 | −0.9338 | −0.7441 | < .001 | < .001 |
| mpg | hp | 32 | −0.7762 | −0.8853 | −0.5861 | < .001 | < .001 |
| mpg | qsec | 32 | 0.4187 | 0.0820 | 0.6696 | .017 | .034 |
| weight (1000 lbs) | hp | 32 | 0.6587 | 0.4025 | 0.8193 | < .001 | < .001 |
| weight (1000 lbs) | qsec | 32 | −0.1747 | −0.4934 | 0.1853 | .339 | .339 |
| hp | qsec | 32 | −0.7082 | −0.8476 | −0.4774 | < .001 | < .001 |
Correlation matrix (r)
| mpg | weight (1000 lbs) | hp | qsec | |
|---|---|---|---|---|
| mpg | 1 | −0.8677 | −0.7762 | 0.4187 |
| weight (1000 lbs) | −0.8677 | 1 | 0.6587 | −0.1747 |
| hp | −0.7762 | 0.6587 | 1 | −0.7082 |
| qsec | 0.4187 | −0.1747 | −0.7082 | 1 |
- Pairwise deletion; two-sided tests; holm adjustment over 6 pairs; * = adjusted p < 0.05.
The exact R script · R R version 4.5.1 (2025-06-13)
# Correlation matrix (Pearson / Spearman / Kendall)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method correlation.matrix 1.0.1 · spec 1efaf86cc5080e08
# Dataset: mtcars (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
variables <- c("mpg", "weight (1000 lbs)", "hp", "qsec")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/mtcars.parquet", col_select = variables))
n_input <- nrow(df)
missing <- "pairwise" # pairwise | listwise
warnings <- list()
for (v in variables) {
if (n_input > 0 && all(is.na(df[[v]]))) cs_error("CS_E_ALL_MISSING", column = v)
}
if (missing == "listwise") {
df <- df[stats::complete.cases(df[variables]), , drop = FALSE] # rows complete on every variable
if (n_input - nrow(df) > 0) warnings <- c(warnings, sprintf("%d of %d rows were left out because a value was missing.", n_input - nrow(df), n_input))
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
}
cs_check_finite_columns(df, variables) # infinite values stop the run (registry/errors.yaml)
# %% Correlations
method <- "pearson"
adjust <- "holm"
conf <- 0.95
pairs <- list()
for (i in seq_along(variables)) {
for (j in seq_along(variables)) {
if (j <= i) next
a <- variables[i]
b <- variables[j]
d <- df[stats::complete.cases(df[c(a, b)]), c(a, b)] # pairwise complete rows (all rows when listwise)
cs_check_rows(nrow(d), 3, sprintf("The correlation of %s and %s", a, b))
for (col in c(a, b)) {
if (length(unique(d[[col]])) < 2) cs_error("CS_E_CONSTANT", column = col) # r = 0 / 0
}
res <- cs_cor_pair(d[[a]], d[[b]], method, "two-sided", conf)
pairs[[length(pairs) + 1]] <- c(list(a = a, b = b), res)
}
}
p_adj <- cs_p_adjust(vapply(pairs, `[[`, 0, "p"), adjust) # the family: every pair in this matrix
for (i in seq_along(pairs)) pairs[[i]]$p_adj <- p_adj[i]
# %% Result
alpha <- 1 - conf
symbol <- c(pearson = "r", spearman = "ρ", kendall = "τ_b")[[method]]
best <- pairs[[which.max(abs(vapply(pairs, `[[`, 0, "estimate")))]]
n_sig <- sum(vapply(pairs, `[[`, 0, "p_adj") < alpha)
small <- vapply(Filter(function(r) r$n < 10, pairs), function(r) paste(r$a, "–", r$b), "")
n_used <- if (missing == "listwise") nrow(df) else n_input
values <- list(n = n_used, n_pairs = length(pairs), n_significant = n_sig, strongest_pair = paste(best$a, "and", best$b),
strongest_r = best$estimate, strongest_p_adj = best$p_adj, max_abs_r = abs(best$estimate), method = method, adjust = adjust)
for (r in pairs) {
key <- paste0(r$a, "|", r$b)
values[[sprintf("r[%s]", key)]] <- r$estimate
values[[sprintf("p[%s]", key)]] <- r$p
values[[sprintf("p_adj[%s]", key)]] <- r$p_adj
values[sprintf("ci_low[%s]", key)] <- list(r$ci_low) # list(): an empty interval stays as null
values[sprintf("ci_high[%s]", key)] <- list(r$ci_high)
values[[sprintf("n[%s]", key)]] <- r$n
}
find <- function(a, b) {
for (r in pairs) if ((r$a == a && r$b == b) || (r$a == b && r$b == a)) return(r)
NULL
}
cells <- expand.grid(col = variables, row = variables, stringsAsFactors = FALSE)[, c("row", "col")]
cells_val <- numeric(nrow(cells))
cells_label <- character(nrow(cells))
for (i in seq_len(nrow(cells))) {
r <- find(cells$row[i], cells$col[i])
cells_val[i] <- if (is.null(r)) 1 else r$estimate
cells_label[i] <- if (is.null(r)) "" else paste0(cs_fmt_num(r$estimate, leading_zero = FALSE), if (r$p_adj < alpha) "*" else "")
}
matrix_rows <- lapply(variables, function(a) {
row <- list(variable = a)
for (b in variables) row[[b]] <- if (a == b) 1 else find(a, b)$estimate
row
})
summary <- sprintf("Of %d pairs, %d %s significant after %s adjustment; the strongest association is between %s and %s (%s = %.2f, adjusted %s).",
length(pairs), n_sig, if (n_sig == 1) "is" else "are", adjust, best$a, best$b, symbol, best$estimate, cs_fmt_p(best$p_adj))
pct <- sprintf("%.0f%%", conf * 100)
cs_publish(list(
method = "correlation.matrix",
methodVersion = "1.0.1",
title = paste(c(pearson = "Pearson", spearman = "Spearman", kendall = "Kendall")[[method]], "correlation matrix"),
engine = cs_engine_info("stats", "nanoparquet"),
n = n_used,
summary = summary,
apa = sprintf("%s and %s: %s = %s, adjusted %s", best$a, best$b, symbol, cs_fmt_num(best$estimate, leading_zero = FALSE), cs_fmt_p(best$p_adj)),
statistics = list(list(key = "n_pairs", label = "Pairs", value = length(pairs), format = "integer"),
list(key = "n_significant", label = sprintf("Significant (%s)", adjust), value = n_sig, format = "integer")),
tables = list(
list(key = "pairs", title = "Pairwise correlations", columns = list(
list(key = "a", label = "Variable 1", type = "string"), list(key = "b", label = "Variable 2", type = "string"),
list(key = "n", label = "n", type = "integer"), list(key = "estimate", label = symbol, type = "number"),
list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number"),
list(key = "p", label = "p", type = "pvalue"), list(key = "p_adj", label = sprintf("p (%s)", adjust), type = "pvalue")),
rows = lapply(pairs, function(r) r[names(r) != "df"])),
list(key = "matrix", title = sprintf("Correlation matrix (%s)", symbol),
columns = c(list(list(key = "variable", label = "", type = "string")), lapply(variables, function(v) list(key = v, label = v, type = "number"))),
rows = matrix_rows)
),
effectSizes = list(),
assumptions = list(
list(key = "form", label = if (method == "pearson") "Linear relationships" else "Monotonic relationships", status = "info",
detail = "Coefficients summarize only this kind of association; check scatter plots of the strongest pairs."),
list(key = "sample_size", label = "Rows per pair", status = if (length(small)) "warn" else "pass",
detail = if (length(small)) sprintf("Fewer than 10 complete rows: %s.", paste(small, collapse = ", "))
else sprintf("Every pair has at least 10 complete rows (smallest n = %d).", min(vapply(pairs, `[[`, 0, "n"))))
),
warnings = warnings,
notes = list(sprintf("%s deletion; two-sided tests; %s adjustment over %d pairs; * = adjusted p < %s.",
paste0(toupper(substr(missing, 1, 1)), substr(missing, 2, nchar(missing))), adjust, length(pairs), format(alpha))),
charts = list(cs_chart("matrix", "matrix-heatmap", sprintf("%s between every pair", symbol), list(
row = cs_col("Variable", cells$row, levels = variables), col = cs_col("Variable ", cells$col, levels = variables),
value = cs_col(symbol, cells_val), label = cs_col("label", cells_label, kind = "categorical")),
controls = list(scale = "diverging", min = -1, max = 1))),
values = values
))
mpg and weight (1000 lbs): r = −.87, adjusted p < .001
- Pairs
- 6
- Significant (holm)
- 5
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Linear relationships — Coefficients summarize only this kind of association; check scatter plots of the strongest pairs.
- Rows per pair — Every pair has at least 10 complete rows (smallest n = 32).
Pairwise correlations
| Variable 1 | Variable 2 | n | r | 95% CI low | 95% CI high | p | p (holm) |
|---|---|---|---|---|---|---|---|
| mpg | weight (1000 lbs) | 32 | −0.8677 | −0.9338 | −0.7441 | < .001 | < .001 |
| mpg | hp | 32 | −0.7762 | −0.8853 | −0.5861 | < .001 | < .001 |
| mpg | qsec | 32 | 0.4187 | 0.0820 | 0.6696 | .017 | .034 |
| weight (1000 lbs) | hp | 32 | 0.6587 | 0.4025 | 0.8193 | < .001 | < .001 |
| weight (1000 lbs) | qsec | 32 | −0.1747 | −0.4934 | 0.1853 | .339 | .339 |
| hp | qsec | 32 | −0.7082 | −0.8476 | −0.4774 | < .001 | < .001 |
Correlation matrix (r)
| mpg | weight (1000 lbs) | hp | qsec | |
|---|---|---|---|---|
| mpg | 1 | −0.8677 | −0.7762 | 0.4187 |
| weight (1000 lbs) | −0.8677 | 1 | 0.6587 | −0.1747 |
| hp | −0.7762 | 0.6587 | 1 | −0.7082 |
| qsec | 0.4187 | −0.1747 | −0.7082 | 1 |
- Pairwise deletion; two-sided tests; holm adjustment over 6 pairs; * = adjusted p < 0.05.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Correlation matrix (Pearson / Spearman / Kendall)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method correlation.matrix 1.0.1 · spec 1efaf86cc5080e08
# Dataset: mtcars (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.stats import correlation as cscor
from codesplash.stats.padjust import p_adjust
# %% Data
variables = ["mpg", "weight (1000 lbs)", "hp", "qsec"]
df = pd.read_parquet("tests/parity/fixtures/mtcars.parquet", columns=variables)
n_input = len(df)
missing = "pairwise" # pairwise | listwise
warnings = []
for v in variables:
if n_input and df[v].isna().all():
cs.cs_error("CS_E_ALL_MISSING", column=v)
if missing == "listwise":
df = df.dropna(subset=variables) # rows complete on every variable
if n_input - len(df):
warnings.append(f"{n_input - len(df)} of {n_input} rows were left out because a value was missing.")
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, variables) # infinite values stop the run (registry/errors.yaml)
# %% Correlations
method = "pearson"
adjust = "holm"
conf = 0.95
pairs = []
for i in range(len(variables)):
for j in range(i + 1, len(variables)):
a, b = variables[i], variables[j]
d = df[[a, b]].dropna() # pairwise complete rows (all rows when listwise)
cs.check_rows(len(d), 3, f"The correlation of {a} and {b}")
for col in (a, b):
if d[col].nunique() < 2: # r = 0 / 0
cs.cs_error("CS_E_CONSTANT", column=col)
res = cscor.pair_test(d[a].to_numpy(dtype=float), d[b].to_numpy(dtype=float), method, "two-sided", conf)
pairs.append({"a": a, "b": b, **res})
p_adj = p_adjust([r["p"] for r in pairs], adjust) # the family: every pair in this matrix
for r, q in zip(pairs, p_adj):
r["p_adj"] = float(q)
# %% Result
alpha = 1 - conf
symbol = {"pearson": "r", "spearman": "ρ", "kendall": "τ_b"}[method]
best = max(pairs, key=lambda r: abs(r["estimate"]))
n_sig = sum(r["p_adj"] < alpha for r in pairs)
small = [f"{r['a']} – {r['b']}" for r in pairs if r["n"] < 10]
values = {"n": len(df) if missing == "listwise" else n_input, "n_pairs": len(pairs), "n_significant": n_sig,
"strongest_pair": f"{best['a']} and {best['b']}", "strongest_r": best["estimate"], "strongest_p_adj": best["p_adj"],
"max_abs_r": abs(best["estimate"]), "method": method, "adjust": adjust}
for r in pairs:
key = f"{r['a']}|{r['b']}"
values.update({f"r[{key}]": r["estimate"], f"p[{key}]": r["p"], f"p_adj[{key}]": r["p_adj"],
f"ci_low[{key}]": r["ci_low"], f"ci_high[{key}]": r["ci_high"], f"n[{key}]": r["n"]})
lookup = {(r["a"], r["b"]): r for r in pairs} | {(r["b"], r["a"]): r for r in pairs}
cells_row, cells_col, cells_val, cells_label = [], [], [], []
for a in variables:
for b in variables:
r = lookup.get((a, b))
cells_row.append(a)
cells_col.append(b)
cells_val.append(1.0 if r is None else r["estimate"])
cells_label.append("" if r is None else f"{cs.fmt_num(r['estimate'], leading_zero=False)}{'*' if r['p_adj'] < alpha else ''}")
summary = (
f"Of {len(pairs)} pairs, {n_sig} {'is' if n_sig == 1 else 'are'} significant after {adjust} adjustment; the strongest association is between "
f"{best['a']} and {best['b']} ({symbol} = {best['estimate']:.2f}, adjusted {cs.fmt_p(best['p_adj'])})."
)
cs.publish({
"method": "correlation.matrix",
"methodVersion": "1.0.1",
"title": {"pearson": "Pearson", "spearman": "Spearman", "kendall": "Kendall"}[method] + " correlation matrix",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": values["n"],
"summary": summary,
"apa": f"{best['a']} and {best['b']}: {symbol} = {cs.fmt_num(best['estimate'], leading_zero=False)}, adjusted {cs.fmt_p(best['p_adj'])}",
"statistics": [{"key": "n_pairs", "label": "Pairs", "value": len(pairs), "format": "integer"},
{"key": "n_significant", "label": f"Significant ({adjust})", "value": n_sig, "format": "integer"}],
"tables": [
{"key": "pairs", "title": "Pairwise correlations", "columns": [
{"key": "a", "label": "Variable 1", "type": "string"}, {"key": "b", "label": "Variable 2", "type": "string"},
{"key": "n", "label": "n", "type": "integer"}, {"key": "estimate", "label": symbol, "type": "number"},
{"key": "ci_low", "label": f"{conf:.0%} CI low", "type": "number"}, {"key": "ci_high", "label": f"{conf:.0%} CI high", "type": "number"},
{"key": "p", "label": "p", "type": "pvalue"}, {"key": "p_adj", "label": f"p ({adjust})", "type": "pvalue"}],
"rows": [{k: v for k, v in r.items() if k != "df"} for r in pairs]},
{"key": "matrix", "title": f"Correlation matrix ({symbol})", "columns": [{"key": "variable", "label": "", "type": "string"}]
+ [{"key": v, "label": v, "type": "number"} for v in variables],
"rows": [{"variable": a, **{b: (1.0 if a == b else lookup[(a, b)]["estimate"]) for b in variables}} for a in variables]},
],
"effectSizes": [],
"assumptions": [
{"key": "form", "label": "Linear relationships" if method == "pearson" else "Monotonic relationships", "status": "info",
"detail": "Coefficients summarize only this kind of association; check scatter plots of the strongest pairs."},
{"key": "sample_size", "label": "Rows per pair", "status": "warn" if small else "pass",
"detail": f"Fewer than 10 complete rows: {', '.join(small)}." if small else f"Every pair has at least 10 complete rows (smallest n = {min(r['n'] for r in pairs)})."},
],
"warnings": warnings,
"notes": [f"{missing.capitalize()} deletion; two-sided tests; {adjust} adjustment over {len(pairs)} pairs; * = adjusted p < {alpha:g}."],
"charts": [cs.chart("matrix", "matrix-heatmap", f"{symbol} between every pair", {
"row": cs.col("Variable", cells_row, levels=variables), "col": cs.col("Variable ", cells_col, levels=variables),
"value": cs.col(symbol, cells_val), "label": cs.col("label", cells_label, kind="categorical")},
controls={"scale": "diverging", "min": -1, "max": 1})],
"values": values,
})
The card names the strongest pair: mpg and weight (1000 lbs), r = −0.868. After Holm's adjustment, 5 of 6 pairs remain below the threshold.
Each cell of the heatmap is a separate estimate with its own uncertainty. A strong color on a small sample can have a wide interval, so check it in the table.
Missing values change what you compare
ReadIn airquality, ozone is missing on many days. There are two ways to handle that:
- Pairwise: each pair uses every row where both values are present. It keeps more data, but pairs can come from different rows.
- Listwise: only rows complete on all the variables are used. Every pair then has the same rows, but fewer of them.
With pairwise handling on four variables, each pair uses its own subset of the 153 rows. With listwise handling on three of those variables, every pair uses the same 111 complete rows.
New York air quality, 1973Check your understanding
CheckpointCheck yourself
How many distinct correlations are there among 10 variables?
Show the answer
Answer: 45
k(k − 1)/2 = 10 × 9 / 2 = 45.
Check yourself
You're screening 200 variables for a follow-up study, and a few false leads are acceptable. Which adjustment fits best?
Show the answer
Answer: c
BH suits screening: it limits the expected share of false findings. Bonferroni would miss most real ones when there are this many tests.
Check yourself
What's the main risk of pairwise handling of missing values?
Show the answer
Answer: b
Pairwise keeps more data, but if missingness relates to the values, cells can describe different populations. Compare with the listwise result as a check.
Do it on your own data
In the appAdd three or more numeric columns, then pick the coefficient, the adjustment and how to treat missing values.
import itertools
import pandas as pd
from scipy import stats
from statsmodels.stats.multitest import multipletests
df = pd.read_csv("mtcars.csv")[["mpg", "wt", "hp", "qsec"]]
pairs = list(itertools.combinations(df.columns, 2))
res = [stats.pearsonr(df[a], df[b]) for a, b in pairs]
adj = multipletests([r.pvalue for r in res], method="holm")[1]
for (a, b), r, p in zip(pairs, res, adj):
print(a, b, round(r.statistic, 3), round(p, 4))df <- read.csv("mtcars.csv")[, c("mpg", "wt", "hp", "qsec")]
pairs <- combn(names(df), 2, simplify = FALSE)
res <- lapply(pairs, function(v) cor.test(df[[v[1]]], df[[v[2]]]))
adj <- p.adjust(sapply(res, `[[`, "p.value"), method = "holm")
data.frame(pair = sapply(pairs, paste, collapse = " ~ "),
r = sapply(res, function(x) x$estimate), p_holm = adj)Recap
Recap- A matrix of variables is tests, so adjust before you claim anything from it.
- Holm controls any false alarm; Benjamini–Hochberg controls the share of false findings.
- Pairwise keeps more rows but mixes subsets; listwise uses one consistent set of rows.
Concepts in this lesson