Skip to content

Correlation as a first look

Scan pairs of variables without fooling yourself, and catch the relationships a correlation can't see.

Introductory ~11 min9 steps

What runs in CodeSplash

You will be able to

  • Read a correlation matrix, and account for how many pairs you scanned
  • Tell Pearson from Spearman in practice
  • Recognize a relationship with a correlation near zero

Read first

01

How strong is that?

Read

Before reading any numbers, calibrate your eye. Guess rr from the scatter, and notice how much noise 0.5 still has.

CExplorable · Guess the correlation

How well can you read a correlation from a scatter plot?

Guess the correlation r for this cloud.

0.00
How sure?
50

Adds a single point against the trend.

Your guesses this session will be tallied here.

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

02

The strongest pair

In the app

A correlation matrix scans every pair at once. Here it is for 32 cars.

Pearson correlation matrixRecorded · Python and R agreeRecorded 2026-11-17 · 45 values compared
R

mpg and weight (1000 lbs): r = −.87, adjusted p < .001

Pairs
6
Significant (holm)
5

Plots

r between every pairWhat do the values of a square or rectangular result matrix look like at a glance?
View data
Variable labelVariabler
mpgmpg1
weight (1000 lbs)−.87*mpg−0.8677
hp−.78*mpg−0.7762
qsec.42*mpg0.4187
mpg−.87*weight (1000 lbs)−0.8677
weight (1000 lbs)weight (1000 lbs)1
hp.66*weight (1000 lbs)0.6587
qsec−.17weight (1000 lbs)−0.1747
mpg−.78*hp−0.7762
weight (1000 lbs).66*hp0.6587
hphp1
qsec−.71*hp−0.7082
mpg.42*qsec0.4187
weight (1000 lbs)−.17qsec−0.1747
hp−.71*qsec−0.7082
qsecqsec1

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 1Variable 2nr95% CI low95% CI highpp (holm)
mpgweight (1000 lbs)32−0.8677−0.9338−0.7441< .001< .001
mpghp32−0.7762−0.8853−0.5861< .001< .001
mpgqsec320.41870.08200.6696.017.034
weight (1000 lbs)hp320.65870.40250.8193< .001< .001
weight (1000 lbs)qsec32−0.1747−0.49340.1853.339.339
hpqsec32−0.7082−0.8476−0.4774< .001< .001

Correlation matrix (r)

mpgweight (1000 lbs)hpqsec
mpg1−0.8677−0.77620.4187
weight (1000 lbs)−0.867710.6587−0.1747
hp−0.77620.65871−0.7082
qsec0.4187−0.1747−0.70821
  • 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
))
Python

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 1Variable 2nr95% CI low95% CI highpp (holm)
mpgweight (1000 lbs)32−0.8677−0.9338−0.7441< .001< .001
mpghp32−0.7762−0.8853−0.5861< .001< .001
mpgqsec320.41870.08200.6696.017.034
weight (1000 lbs)hp320.65870.40250.8193< .001< .001
weight (1000 lbs)qsec32−0.1747−0.49340.1853.339.339
hpqsec32−0.7082−0.8476−0.4774< .001< .001

Correlation matrix (r)

mpgweight (1000 lbs)hpqsec
mpg1−0.8677−0.77620.4187
weight (1000 lbs)−0.867710.6587−0.1747
hp−0.77620.65871−0.7082
qsec0.4187−0.1747−0.70821
  • 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 strongest pair is mpg and weight (1000 lbs), at r=r = −0.87. Six pairs were scanned, and the p-values are adjusted for that.

03

Scanning has a price

Predict

Predict first

A table has 20 numeric columns. How many pairs will a correlation matrix scan?

Make your guess between 0 and 200 pairs, then reveal.

Reveal

20×19/2=19020 \times 19 / 2 = 190 pairs. At the 0.05 level, about 9 or 10 would look significant if nothing at all were related. Adjust for multiplicity, and treat a scan as a source of questions rather than answers.

04

Pearson or Spearman?

Read

Pearson's rr measures straight-line association, and one extreme point can move it a long way. Spearman's ρ\rho does the same on ranks, so it handles curved but steadily rising patterns, and it resists outliers.

In airquality, the strongest Spearman pair is Ozone and Temp, at 0.77.

If Pearson and Spearman disagree, look at the scatter: it often means a curve or an outlier.

05

Drag the outlier

Explore

Drag one point away from the cloud, and compare how far each coefficient moves.

CExplorable · Drag one point across five correlations

How much can one point move a correlation, and which measures hold steady?

Drag a far-out point into the corner. Which measure moves the most?

How sure?
0.20
30
0.0
0.0
0.13Pearson0.06Spearman0.03Kendall0.10ξ0.27dCor

Bars show the size of each measure. Drag the red point, or focus it and use the arrow keys.

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

06

When r is near zero

Read

A strong curved relationship can have a Pearson rr near zero. In a quadratic example, r=r = −0.03 and ρ=\rho = −0.03, yet Chatterjee's ξ\xi is 0.40, with p < .001.

Always plot before you trust a coefficient:

CExplorable · Same statistics, different pictures

How can datasets with identical summaries look nothing alike?

As the cloud morphs into this shape, what happens to Pearson's r?

How sure?

Target

1.00

Mean, SD and correlation are held fixed along the way.

Mean of xSD of yPearson rSpearman ρ
54.3026.90−0.060−0.029

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

07

In Insights

In the app

In Insights (⌘5), the Data scientist page shows an association matrix that handles mixed column types, and the strongest pairs. It's a screen, computed on a seeded sample of rows when the data are large.

Pick one pair that surprises you and draw its scatter in Charts, using Use my data.

08

Check your understanding

Checkpoint

Check yourself

A table has 10 numeric columns. How many distinct pairs does a correlation matrix contain?

Show the answer

Answer: 45

10×9/210 \times 9 / 2.

Check yourself

Pearson's rr between dose and response is 0.02. What can you conclude?

Show the answer

Answer: b

Pearson's rr only sees lines. An inverted U can give rr near zero with a very strong relationship.

Check yourself

Pearson gives 0.85, and Spearman gives 0.30. What's the likely reason?

Show the answer

Answer: a

Ranks limit how much any point can matter. A big gap means a few values are doing the work, so look at the scatter.

09

Recap

Recap
  • A correlation scan raises questions, and you must account for how many pairs you looked at.
  • Pearson sees lines, and Spearman sees steady trends. A disagreement is worth a look.
  • A coefficient near zero doesn't mean no relationship, so plot first.

Concepts in this lesson