One-Way ANOVA
To compare the means of two groups you can use a two-sample t-test. With three or more groups, running a t-test for every pair is a bad idea: with 5 groups there are 10 pairs, and the chance of at least one false positive grows far above 5%. Analysis of variance (ANOVA) tests all groups at once:
H₀: μ₁ = μ₂ = … = μₖ (all group means are equal)
H₁: at least one mean differsThe idea: between vs. within
Despite its name, ANOVA compares means by looking at variances:
- Between-group variation: how far the group means are from the overall mean.
- Within-group variation: how much the values vary inside each group (the noise).
If the group means differ only by chance, the between-group variation should be about as large as the noise. The F statistic is their ratio:
SS_between = Σ nᵢ × (x̄ᵢ − x̄)² df_between = k − 1
SS_within = Σ Σ (x − x̄ᵢ)² df_within = N − k
F = (SS_between / df_between) / (SS_within / df_within)k is the number of groups and N the total number of observations. Large F → the group means differ more than noise would explain. Under H₀, F follows an F-distribution with (k − 1, N − k) degrees of freedom.
Example: three fertilisers
A gardener grows tomato plants with three fertilisers and records each plant's yield (kg):
import numpy as np
groups = {
"A": np.array([4.2, 4.8, 5.1, 4.5, 4.9, 4.4, 5.0]),
"B": np.array([5.3, 5.9, 5.6, 6.1, 5.4, 5.8, 5.7]),
"C": np.array([4.6, 5.2, 4.9, 5.5, 5.0, 4.7, 5.3]),
}
everything = np.concatenate(list(groups.values()))
grand = everything.mean()
k, N = len(groups), everything.size
ss_between = sum(len(g) * (g.mean() - grand) ** 2 for g in groups.values())
ss_within = sum(((g - g.mean()) ** 2).sum() for g in groups.values())
ms_between = ss_between / (k - 1)
ms_within = ss_within / (N - k)
F = ms_between / ms_within
for name, g in groups.items():
print(f"group {name}: mean = {g.mean():.3f}")
print(f"SS_between = {ss_between:.4f}, SS_within = {ss_within:.4f}")
print(f"F = {ms_between:.4f} / {ms_within:.4f} = {F:.3f} (df = {k - 1}, {N - k})")group A: mean = 4.700
group B: mean = 5.686
group C: mean = 5.029
SS_between = 3.5267, SS_within = 1.7829
F = 1.7633 / 0.0990 = 17.803 (df = 2, 18)
The p-value is the area to the right of F:
from scipy import stats
F, df1, df2 = 17.803, 2, 18
print(f"p-value = {stats.f.sf(F, df1, df2):.6f}")
print(f"5% critical value = {stats.f.ppf(0.95, df1, df2):.3f}")p-value = 0.000054
5% critical value = 3.555
With SciPy in one line
from scipy import stats
a = [4.2, 4.8, 5.1, 4.5, 4.9, 4.4, 5.0]
b = [5.3, 5.9, 5.6, 6.1, 5.4, 5.8, 5.7]
c = [4.6, 5.2, 4.9, 5.5, 5.0, 4.7, 5.3]
res = stats.f_oneway(a, b, c)
print(f"F = {res.statistic:.3f}, p = {res.pvalue:.6f}")F = 17.803, p = 0.000054
p < 0.05, so we reject H₀: the fertilisers do not all give the same mean yield.
In context: there is strong evidence that mean tomato yield differs between at least two of the three fertilisers.
Which groups differ? Post-hoc tests
ANOVA only says that some difference exists. A post-hoc test compares all pairs while keeping the overall error rate at α. Tukey's HSD ("honestly significant difference") is the standard choice:
from scipy import stats
a = [4.2, 4.8, 5.1, 4.5, 4.9, 4.4, 5.0]
b = [5.3, 5.9, 5.6, 6.1, 5.4, 5.8, 5.7]
c = [4.6, 5.2, 4.9, 5.5, 5.0, 4.7, 5.3]
res = stats.tukey_hsd(a, b, c)
names = ["A", "B", "C"]
ci = res.confidence_interval(0.95)
for i in range(3):
for j in range(i + 1, 3):
print(f"{names[i]} vs {names[j]}: diff = {res.statistic[i, j]:+.3f}, "
f"p = {res.pvalue[i, j]:.4f}, 95% CI ({ci.low[i, j]:+.3f}, {ci.high[i, j]:+.3f})")A vs B: diff = -0.986, p = 0.0000, 95% CI (-1.415, -0.556)
A vs C: diff = -0.329, p = 0.1528, 95% CI (-0.758, +0.101)
B vs C: diff = +0.657, p = 0.0028, 95% CI (+0.228, +1.086)
Fertiliser B gives a higher mean yield than both A and C, while A and C cannot be told apart.
Assumptions
- Independent observations (e.g. plants randomly assigned to fertilisers).
- Roughly normal values within each group (less important with larger groups).
- Equal variances across groups. Levene's test checks this; if variances clearly differ, use Welch's ANOVA instead.
import pandas as pd
from scipy import stats
a = [4.2, 4.8, 5.1, 4.5, 4.9, 4.4, 5.0]
b = [5.3, 5.9, 5.6, 6.1, 5.4, 5.8, 5.7]
c = [4.6, 5.2, 4.9, 5.5, 5.0, 4.7, 5.3]
print(f"Levene's test p = {stats.levene(a, b, c).pvalue:.3f}")
sds = pd.Series({"A": pd.Series(a).std(), "B": pd.Series(b).std(), "C": pd.Series(c).std()})
print("group standard deviations:")
print(sds.round(3))Levene's test p = 0.821
group standard deviations:
A 0.337
B 0.279
C 0.325
dtype: float64
Levene's p-value is large and the group standard deviations are similar, so the equal-variance assumption is reasonable.
Effect size: η²
Eta squared is the share of the total variation explained by the groups: η² = SS_between / SS_total. Here the fertiliser explains about two thirds of the variation in yield, a large effect.
import numpy as np
groups = [np.array([4.2, 4.8, 5.1, 4.5, 4.9, 4.4, 5.0]),
np.array([5.3, 5.9, 5.6, 6.1, 5.4, 5.8, 5.7]),
np.array([4.6, 5.2, 4.9, 5.5, 5.0, 4.7, 5.3])]
allv = np.concatenate(groups)
ss_total = ((allv - allv.mean()) ** 2).sum()
ss_between = sum(len(g) * (g.mean() - allv.mean()) ** 2 for g in groups)
print(f"eta squared = {ss_between / ss_total:.3f}")eta squared = 0.664
Test yourself
Why not simply run t-tests between every pair of 5 groups?
- t-tests can't compare means
- With 10 tests, the chance of at least one false positive is much larger than α
- It requires equal sample sizes
- It is too slow
An ANOVA with 4 groups and 40 observations in total has which degrees of freedom?
- (4, 40)
- (3, 36)
- (3, 39)
- (4, 36)
An ANOVA gives p = 0.002. What can you conclude?
- All group means differ from each other
- At least one group mean differs; a post-hoc test shows which
- The largest group is significantly different
- The variances are unequal