Correlation
Correlation measures how strongly two quantitative variables move together. Do students who study longer score higher? Do heavier cars use more fuel? Correlation puts a single number on such relationships.
Scatter plots first
Always start with a scatter plot: one point per observation, one variable on each axis. It shows the direction, the form (straight or curved) and the strength of the relationship, plus any outliers.
import numpy as np
import matplotlib.pyplot as plt
hours = np.array([2, 4, 5, 1, 7, 3, 6, 8, 4, 5, 9, 2, 6, 7, 3])
score = np.array([55, 64, 70, 48, 79, 60, 72, 88, 62, 74, 90, 58, 75, 80, 59])
fig, ax = plt.subplots(figsize=(5, 3.5))
ax.scatter(hours, score, color="#2a78d6", s=40)
ax.set_xlabel("hours studied")
ax.set_ylabel("exam score")
plt.tight_layout()
plt.show()
print(f"{len(hours)} students: more study hours go with higher scores")15 students: more study hours go with higher scores
Pearson's correlation coefficient r
Pearson's r measures the strength of a linear relationship:
r = Σ(x − x̄)(y − ȳ) / √( Σ(x − x̄)² × Σ(y − ȳ)² )ris always between −1 and +1.r > 0: positive relationship (both rise together);r < 0: negative (one rises, the other falls).|r|near 1: points lie close to a straight line;rnear 0: no linear relationship.rhas no units and doesn't change if you rescale a variable (minutes vs. hours).
Rough guide for |r|: below 0.3 weak, 0.3–0.7 moderate, above 0.7 strong. Context matters more than these labels.
import math
import statistics
hours = [2, 4, 5, 1, 7, 3, 6, 8, 4, 5, 9, 2, 6, 7, 3]
score = [55, 64, 70, 48, 79, 60, 72, 88, 62, 74, 90, 58, 75, 80, 59]
mx, my = statistics.mean(hours), statistics.mean(score)
sxy = sum((x - mx) * (y - my) for x, y in zip(hours, score))
sxx = sum((x - mx) ** 2 for x in hours)
syy = sum((y - my) ** 2 for y in score)
r = sxy / math.sqrt(sxx * syy)
print(f"r by hand = {r:.4f}")
print(f"statistics.correlation = {statistics.correlation(hours, score):.4f}")r by hand = 0.9862
statistics.correlation = 0.9862
Testing whether a correlation is real
In a sample, r is rarely exactly 0 even when the variables are unrelated. scipy.stats.pearsonr tests H₀: ρ = 0 (no correlation in the population, ρ = rho) and returns a p-value and a confidence interval:
import numpy as np
from scipy import stats
hours = np.array([2, 4, 5, 1, 7, 3, 6, 8, 4, 5, 9, 2, 6, 7, 3])
score = np.array([55, 64, 70, 48, 79, 60, 72, 88, 62, 74, 90, 58, 75, 80, 59])
res = stats.pearsonr(hours, score)
ci = res.confidence_interval(confidence_level=0.95)
print(f"r = {res.statistic:.3f}, p-value = {res.pvalue:.2e}")
print(f"95% CI for ρ: ({ci.low:.3f}, {ci.high:.3f})")r = 0.986, p-value = 1.58e-11
95% CI for ρ: (0.958, 0.996)
The p-value is tiny, so a correlation this strong would almost never appear by chance in 15 unrelated pairs.
Correlation matrices with pandas
With several variables, DataFrame.corr() computes every pairwise correlation:
import numpy as np
import pandas as pd
rng = np.random.default_rng(4)
n = 60
weight = rng.normal(1400, 250, n) # car weight in kg
power = 0.08 * weight + rng.normal(0, 15, n) # engine power in kW
fuel = 2 + 0.003 * weight + 0.01 * power + rng.normal(0, 0.5, n) # l/100 km
cars = pd.DataFrame({"weight": weight, "power": power, "fuel": fuel})
print(cars.corr().round(2)) weight power fuel
weight 1.00 0.80 0.85
power 0.80 1.00 0.78
fuel 0.85 0.78 1.00
The diagonal is always 1 (every variable correlates perfectly with itself), and the matrix is symmetric.
Spearman's rank correlation
Pearson's r only captures straight-line relationships and is sensitive to outliers. Spearman's ρ computes Pearson's r on the ranks of the data, so it measures any monotonic relationship (always increasing or always decreasing) and resists outliers. It also suits ordinal data.
import numpy as np
from scipy import stats
x = np.arange(1, 21)
y = np.exp(x / 4) # always increasing, but strongly curved
print(f"Pearson r = {stats.pearsonr(x, y).statistic:.3f}")
print(f"Spearman rho = {stats.spearmanr(x, y).statistic:.3f}")Pearson r = 0.860
Spearman rho = 1.000
The relationship is perfectly monotonic, which Spearman recognises (ρ = 1). Pearson's r is lower because the points don't lie on a straight line.
Pitfalls
import numpy as np
from scipy import stats
x = np.linspace(-3, 3, 41)
y = x ** 2 # perfect, but U-shaped, relationship
print(f"U-shape: r = {round(stats.pearsonr(x, y).statistic, 3) + 0.0:.3f}")
rng = np.random.default_rng(1)
a = rng.normal(0, 1, 30)
b = rng.normal(0, 1, 30)
print(f"unrelated: r = {stats.pearsonr(a, b).statistic:.3f}")
a_out, b_out = np.append(a, 8), np.append(b, 8) # add a single extreme point
print(f"+1 outlier: r = {stats.pearsonr(a_out, b_out).statistic:.3f}")U-shape: r = 0.000
unrelated: r = -0.160
+1 outlier: r = 0.696
- r = 0 doesn't mean "no relationship": the U-shape is a perfect relationship with r = 0.
- One outlier can create (or destroy) a correlation: always look at the scatter plot.
- Correlation is not causation: ice-cream sales and drowning accidents are correlated because both rise in hot weather. See Study Types.
Test yourself
Which value of r indicates the strongest linear relationship?
- 0.65
- −0.85
- 0.10
- −0.30
A scatter plot shows a perfect U-shape. What is Pearson's r likely to be?
- Close to 1
- Close to −1
- Close to 0
- Undefined
When is Spearman's rank correlation preferable to Pearson's r?
- When the relationship is monotonic but curved, or there are outliers or ordinal data
- Never
- Only for perfectly linear data
- When both variables are categorical