Why three groups break the t-test
With three treatment groups there are three pairwise comparisons, and running each at the five percent level does not give a five percent error rate for the set. If every pair is truly equal, the chance of at least one false rejection is about fourteen percent, and it keeps climbing as groups are added. That is the multiple comparisons problem in its simplest form, and analysis of variance is the classical answer: a single test that asks whether any group means differ while keeping the overall error rate at the level you specified.
The name is misleading in one important respect. ANOVA does not analyse means; it analyses variances and uses the ratio of two of them to draw a conclusion about means. Group differences show up as extra variation between groups, and random scatter shows up as variation within groups. If the between-group variation is large relative to what pure within-group noise would produce, the means cannot all be equal. That reframing β from comparing means to comparing sources of variation β is what generalises cleanly to factorial designs with many factors.
Decomposing the total variation
Start with the grand mean and measure every observation's squared distance from it; summing those gives the total sum of squares. Now split each distance into two pieces: the distance from the observation's own group mean, and the distance from that group mean to the grand mean. Squaring and summing both pieces gives the within-group and between-group sums of squares, and the decomposition is exact β total equals between plus within, with no remainder.
The ratio of the between-group sum of squares to the total has a name and an interpretation: eta-squared, the proportion of total variance explained by group membership. It is the analysis-of-variance counterpart of R-squared from regression, and it carries the same caution β it never decreases when groups are added, even at random, so an adjusted version is preferable when comparing models with different numbers of groups. Omega-squared corrects for the same optimism that adjusted R-squared addresses in regression.
| Source | Sum of squares | Degrees of freedom | Mean square |
|---|---|---|---|
| Between groups | Deviations of group means from the grand mean, weighted by size | k minus one | Between sum of squares over k minus one |
| Within groups | Deviations of observations from their own group mean | N minus k | Within sum of squares over N minus k |
| Total | Deviations from the grand mean | N minus one | β |
The F statistic and its two sources of noise
The F statistic divides the between-group mean square by the within-group mean square. The numerator combines genuine treatment effects with ordinary sampling noise, because group means differ slightly even when treatments do nothing. The denominator is pure noise: variation of individuals around their own group mean. If the treatments do nothing, both quantities estimate the same variance and their ratio follows an F distribution centred near one. If the treatments do something, the numerator picks up the extra signal and the ratio grows.
The reference F distribution is parameterised by the two degrees of freedom β numerator from the number of groups, denominator from the residual count. Because both mean squares are estimates with their own sampling variability, the F statistic is noisier than a t statistic for the same data, and power depends on the number of groups as well as their separation. A significant F is only a gateway: it says at least one group differs, and it cannot say which. Treating the omnibus result as evidence for a specific pairwise claim is the most common misuse of the test.
Two factors and the interaction nobody checks
Two-way ANOVA extends the partition to two categorical factors and, crucially, to their interaction. The sums of squares now split across a grand mean, each main effect, the interaction, and the residuals, and three hypotheses are tested at once: does factor A matter, does factor B matter, and does the effect of A depend on the level of B.
The interaction is the term practitioners skip and then get burned by. A significant interaction means the main effects cannot be interpreted in isolation, because the size or even the sign of A's effect changes across levels of B. A drug that helps young patients and harms elderly ones has a main effect near zero and a large interaction, and reporting only the main effect would recommend a treatment that hurts half the population. When an interaction is present, report the simple effects β the effect of A within each level of B β rather than the averaged main effect.
Assumptions, diagnostics, and what to do instead
Independence again comes first and cannot be repaired by transformation: observations must be independent within and across groups, which rules out repeated measures on the same subject. For that structure, a repeated-measures ANOVA or a mixed model is required. Normality of residuals matters less than it seems, because the F test is fairly robust and the central limit theorem rescues large groups, but severe skew or heavy tails with small samples will distort the p-value.
Homogeneity of variances is the assumption most often violated, especially when group sizes differ. Levene's test checks it robustly by comparing absolute deviations rather than raw values, and a significant result means the pooled within-group variance is an unfair average. The remedies are Welch's ANOVA, which does not pool, or the Kruskal-Wallis test, which works on ranks and drops the normality assumption entirely. Residual plots are the fastest diagnostic: a funnel shape in the residuals-versus-fitted plot is heteroscedasticity, and curvature means a factor is standing in for a continuous predictor that should be modelled directly.
Post-hoc comparisons after a significant F
Once the omnibus test rejects, the job is to identify differing pairs while keeping the family-wise error rate under control. Tukey's honestly significant difference compares all pairs with a single critical value derived from the studentized range distribution and is the standard all-pairs choice. Bonferroni divides the significance level by the number of comparisons; it is simple, transparent, and conservative, which makes it appropriate when only a few planned contrasts matter. Dunnett compares every group against a single control and needs fewer corrections than all-pairs testing.
ScheffΓ©'s method is the most conservative because it covers every possible contrast, not just pairs, so it suits exploratory groupings defined after the fact. Whichever you choose, state it before running it; picking the method that yields significance afterwards undermines the error control the whole procedure exists to provide.
Running and diagnosing ANOVA in Python
import numpy as np
from scipy import stats
def one_way_anova(groups):
"""ANOVA by hand: returns F, p, and eta-squared."""
all_values = np.concatenate(groups)
grand = all_values.mean()
ss_between = sum(len(g) * (g.mean() - grand) ** 2 for g in groups)
ss_within = sum(np.sum((g - g.mean()) ** 2) for g in groups)
ss_total = ss_between + ss_within
k, n = len(groups), all_values.size
df_b, df_w = k - 1, n - k
ms_b, ms_w = ss_between / df_b, ss_within / df_w
f = ms_b / ms_w
return f, 1 - stats.f.cdf(f, df_b, df_w), ss_between / ss_total
rng = np.random.default_rng(21)
g1 = rng.normal(62, 8, 30)
g2 = rng.normal(68, 8, 30)
g3 = rng.normal(71, 8, 30)
f, p, eta2 = one_way_anova([g1, g2, g3])
print(f"F = {f:.3f}, p = {p:.4f}, eta^2 = {eta2:.3f}")
print("scipy:", stats.f_oneway(g1, g2, g3))
print("Levene:", stats.levene(g1, g2, g3))
The hand-computed F matches f_oneway exactly, which is a useful sanity check on both implementations, and Levene's test confirms the equal-variance assumption that the pooled calculation relies on.
The second block runs the factorial version and shows why interactions matter.
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
from statsmodels.stats.multicomp import pairwise_tukeyhsd
rng = np.random.default_rng(4)
rows = []
for drug in ("A", "B"):
for dose in ("low", "high"):
base = 40 if drug == "A" else 44
bump = 6 if dose == "high" else 0
interaction = 5 if (drug == "B" and dose == "high") else 0
for _ in range(25):
rows.append({"drug": drug, "dose": dose,
"recovery": rng.normal(base + bump + interaction, 5)})
df = pd.DataFrame(rows)
model = smf.ols("recovery ~ C(drug) * C(dose)", data=df).fit()
anova_table = sm.stats.anova_lm(model, typ=2)
print(anova_table)
tukey = pairwise_tukeyhsd(df["recovery"], df["drug"] + df["dose"], alpha=0.05)
print(tukey)
The interaction row is the one to read first. When it is significant, the two main-effect rows describe averages over a pattern that reverses or vanishes within individual cells, and the Tukey output shows exactly which of the four combinations differ from each other.
ANOVA mistakes
Common Mistakes
Declaring which groups differ from a significant F alone
Fix: Run a post-hoc procedure with family-wise control, such as Tukey's honestly significant difference.
Running three separate t-tests instead of one ANOVA
Fix: Each extra test inflates the error rate; a single omnibus test keeps it at the stated level.
Interpreting main effects while an interaction is significant
Fix: Report simple effects within each level of the second factor instead of the averaged effect.
Ignoring unequal variances when group sizes differ
Fix: Test with Levene's test and fall back to Welch's ANOVA or Kruskal-Wallis when it fails.
Using ANOVA on repeated measures as if rows were independent
Fix: Use repeated-measures ANOVA or a mixed-effects model that accounts for subject-level correlation.
Reporting significance without effect size
Fix: Quote eta-squared or omega-squared so readers can judge how much variance the factor explains.
Best Practices
- Choose and state the post-hoc method before running the omnibus test.
- Plot the group distributions, not just their means, before trusting the F statistic.
- Check Levene's test whenever group sizes are unequal.
- Report F with both degrees of freedom, the p-value, and an effect size.
- Follow a significant interaction with simple-effects analysis.
ANOVA essentials
Where to go next
- One-Way ANOVA derives the F test and the sum of squares decomposition fully.
- F-Test for Equality of Variances covers the assumption check directly.
- Multiple Testing Problem explains why post-hoc correction is necessary.
- Kruskal-Wallis Test is the rank-based alternative when assumptions fail.