Two-way ANOVA & Interactions
A two-way design crosses two factors, such as genotype and treatment, so that every combination has its own group of independent units. The design answers a question that two separate experiments cannot: does the effect of one factor depend on the level of the other? This page fits the model with an interaction to a mouse glucose experiment, reads the interaction as a difference of differences in mg/dL, and shows where the three types of sums of squares disagree, in R and Python.
Get the data
Section titled “Get the data”Download glucose_genotype_drug.csv into your working directory. The invented table has 40 rows, one per mouse, and four columns: mouse_id, genotype (WT or KO), treatment (vehicle or drug), and glucose_mg_dl, the fasting plasma glucose. Each mouse received one treatment and gave one value, so the mouse is the experimental unit.
The values come from a simulation with known answers. The true cell means are 180 mg/dL for wild type on vehicle, 140 for wild type on drug, 190 for knockout on vehicle, and 180 for knockout on drug, with a standard deviation of 15 mg/dL in every cell. The drug therefore lowers glucose by 40 mg/dL in the wild type and by 10 mg/dL in the knockout, which lacks most of the drug target. The true interaction is the difference of those two effects, +30 mg/dL.
Start with the cell means
Section titled “Start with the cell means”A two-by-two design has four cells. Print the count, the mean, and the standard deviation of each cell before any model, then compute the drug effect inside each genotype.
Both languages order factor levels alphabetically unless told otherwise, which would make KO and drug the reference levels. The code sets WT and vehicle as the references, so every coefficient below is a comparison with wild-type mice on vehicle. On load, car attaches carData and emmeans prints a welcome note; neither message concerns the analysis.
library(car)library(emmeans)library(ggplot2)
glucose <- read.csv("glucose_genotype_drug.csv")glucose$genotype <- factor(glucose$genotype, levels = c("WT", "KO"))glucose$treatment <- factor(glucose$treatment, levels = c("vehicle", "drug"))dir.create("outputs", showWarnings = FALSE)
cell_means <- tapply(glucose$glucose_mg_dl, list(glucose$genotype, glucose$treatment), mean)for (genotype in levels(glucose$genotype)) { for (treatment in levels(glucose$treatment)) { values <- glucose$glucose_mg_dl[glucose$genotype == genotype & glucose$treatment == treatment] cat(sprintf("%s %-8s n = %2d, mean = %.2f, SD = %.2f\n", genotype, treatment, length(values), mean(values), sd(values))) }}drug_effect <- cell_means[, "drug"] - cell_means[, "vehicle"]cat(sprintf("Drug minus vehicle in WT: %.2f\n", drug_effect["WT"]))cat(sprintf("Drug minus vehicle in KO: %.2f\n", drug_effect["KO"]))cat(sprintf("Difference of differences: %.2f\n", drug_effect["KO"] - drug_effect["WT"]))WT vehicle n = 12, mean = 179.83, SD = 15.75WT drug n = 10, mean = 137.50, SD = 18.83KO vehicle n = 7, mean = 189.71, SD = 16.15KO drug n = 11, mean = 176.45, SD = 15.61Drug minus vehicle in WT: -42.33Drug minus vehicle in KO: -13.26Difference of differences: 29.07from pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport statsmodels.formula.api as smffrom statsmodels.stats.anova import anova_lm
glucose = pd.read_csv("glucose_genotype_drug.csv")glucose["genotype"] = pd.Categorical(glucose["genotype"], ["WT", "KO"])glucose["treatment"] = pd.Categorical(glucose["treatment"], ["vehicle", "drug"])output = Path("outputs")output.mkdir(exist_ok=True)
cells = glucose.groupby(["genotype", "treatment"], observed=True)[ "glucose_mg_dl"].agg(["count", "mean", "std"])for (genotype, treatment), cell in cells.iterrows(): print(f"{genotype} {treatment:<8} n = {cell['count']:2.0f}, " f"mean = {cell['mean']:.2f}, SD = {cell['std']:.2f}")cell_means = cells["mean"].unstack()drug_effect = cell_means["drug"] - cell_means["vehicle"]print(f"Drug minus vehicle in WT: {drug_effect['WT']:.2f}")print(f"Drug minus vehicle in KO: {drug_effect['KO']:.2f}")print("Difference of differences: " f"{drug_effect['KO'] - drug_effect['WT']:.2f}")WT vehicle n = 12, mean = 179.83, SD = 15.75WT drug n = 10, mean = 137.50, SD = 18.83KO vehicle n = 7, mean = 189.71, SD = 16.15KO drug n = 11, mean = 176.45, SD = 15.61Drug minus vehicle in WT: -42.33Drug minus vehicle in KO: -13.26Difference of differences: 29.07The cell counts are unequal: 12, 10, 7, and 11 mice. The drug lowered mean glucose by 42.33 mg/dL in the wild type and by 13.26 mg/dL in the knockout. The difference of those two differences, 29.07 mg/dL, is the interaction in the sample: the drug effect is 29.07 mg/dL weaker in the knockout.
The interaction has no preferred direction. Computed the other way, as the genotype difference under drug minus the genotype difference under vehicle, it is the same 29.07 mg/dL.
Draw the interaction plot
Section titled “Draw the interaction plot”Plot the four cell means, join the two means of each genotype, and compare the slopes. Parallel lines mean that the drug effect is the same in both genotypes. The factorial ANOVA figure page covers the grouped box plot for a publication; the plot here is a working tool for the model.
interaction_plot <- ggplot(glucose, aes(treatment, glucose_mg_dl, color = genotype, group = genotype)) + geom_point(position = position_jitterdodge(jitter.width = 0.08, dodge.width = 0.3, seed = 1), alpha = 0.45, size = 1.6) + stat_summary(fun = mean, geom = "line", linewidth = 0.9) + stat_summary(fun = mean, geom = "point", size = 3.2) + scale_color_manual(values = c(WT = "#1f4e5f", KO = "#d1803a")) + labs(x = "Treatment", y = "Fasting glucose (mg/dL)", color = "Genotype") + theme_classic(base_size = 12)ggsave("outputs/two-way-interaction-r.png", interaction_plot, width = 5.5, height = 4, dpi = 150)
palette = {"WT": "#1f2a44", "KO": "#c46a2b"}offsets = {"WT": -0.06, "KO": 0.06}rng = np.random.default_rng(1)figure, axes = plt.subplots(figsize=(5.5, 4))for genotype in ["WT", "KO"]: mice = glucose[glucose["genotype"] == genotype] position = (mice["treatment"].cat.codes + offsets[genotype] + rng.uniform(-0.03, 0.03, len(mice))) axes.scatter(position, mice["glucose_mg_dl"], color=palette[genotype], alpha=0.45, s=18) axes.plot([0, 1], cell_means.loc[genotype], color=palette[genotype], marker="o", markersize=8, linewidth=2, label=genotype)axes.set_xticks([0, 1], ["vehicle", "drug"])axes.set_xlim(-0.4, 1.4)axes.set_xlabel("Treatment")axes.set_ylabel("Fasting glucose (mg/dL)")axes.legend(title="Genotype", frameon=False)figure.tight_layout()figure.savefig(output / "two-way-interaction-python.png", dpi=150)plt.close(figure)
The wild-type line drops steeply and the knockout line is nearly flat. Lines that are not parallel are what an interaction looks like. The two lines also start close together under vehicle and end far apart under drug, which is the same interaction read along the other factor.
Fit the model with the interaction
Section titled “Fit the model with the interaction”The formula genotype * treatment expands to the two factors and their product. With WT and vehicle as the reference levels, each of the four coefficients has a direct reading in mg/dL.
model <- lm(glucose_mg_dl ~ genotype * treatment, data = glucose)estimates <- summary(model)$coefficientsintervals <- confint(model)for (term in rownames(estimates)) { cat(sprintf("%-24s %7.2f SE %5.2f 95%% CI [%6.2f, %6.2f] p = %.2g\n", term, estimates[term, "Estimate"], estimates[term, "Std. Error"], intervals[term, 1], intervals[term, 2], estimates[term, "Pr(>|t|)"]))}cat(sprintf("Residual SD %.2f on %d degrees of freedom\n", sigma(model), df.residual(model)))(Intercept) 179.83 SE 4.79 95% CI [170.11, 189.55] p = 1.8e-30genotypeKO 9.88 SE 7.89 95% CI [ -6.13, 25.89] p = 0.22treatmentdrug -42.33 SE 7.11 95% CI [-56.75, -27.92] p = 8e-07genotypeKO:treatmentdrug 29.07 SE 10.72 95% CI [ 7.33, 50.82] p = 0.01Residual SD 16.60 on 36 degrees of freedommodel = smf.ols("glucose_mg_dl ~ genotype * treatment", data=glucose).fit()intervals = model.conf_int()for term in model.params.index: print(f"{term:<32} {model.params[term]:7.2f} SE {model.bse[term]:5.2f} " f"95% CI [{intervals.loc[term, 0]:6.2f}, " f"{intervals.loc[term, 1]:6.2f}] p = {model.pvalues[term]:.2g}")print(f"Residual SD {np.sqrt(model.scale):.2f} on {model.df_resid:.0f} " "degrees of freedom")Intercept 179.83 SE 4.79 95% CI [170.11, 189.55] p = 1.8e-30genotype[T.KO] 9.88 SE 7.89 95% CI [ -6.13, 25.89] p = 0.22treatment[T.drug] -42.33 SE 7.11 95% CI [-56.75, -27.92] p = 8e-07genotype[T.KO]:treatment[T.drug] 29.07 SE 10.72 95% CI [ 7.33, 50.82] p = 0.01Residual SD 16.60 on 36 degrees of freedom- The intercept, 179.83, is the mean of the reference cell, wild type on vehicle.
- The genotype coefficient, 9.88, is knockout minus wild type among the vehicle mice only.
- The treatment coefficient, −42.33, is the drug effect in the wild-type mice only.
- The interaction coefficient, 29.07, is the difference of differences from the cell means.
The interaction is 29.07 mg/dL with a 95% interval from 7.33 to 50.82, and the true value of +30 lies inside it. The interval is wide. At its lower end the knockout removes about a sixth of the 42.33 mg/dL drug effect, and at its upper end the knockout reverses the effect. The standard error of the interaction, 10.72, is larger than the 7.11 of the drug effect in the wild type, because the interaction combines four cell means and the drug effect only two. An experiment sized to detect a drug effect is usually too small to estimate how that effect changes. The residual standard deviation, 16.60 mg/dL, estimates the 15 mg/dL of the simulation.
The two coefficients named after one factor are not main effects. Each is a simple effect at the reference level of the other factor. The genotype coefficient has p = 0.22, and that p-value concerns vehicle mice only; under drug, the knockout mean sits far above the wild-type mean.
Why a main effect is hard to read here
Section titled “Why a main effect is hard to read here”A main effect is an average of the effect of one factor over the levels of the other. The drug lowers glucose by about 42 mg/dL in one genotype and by about 13 mg/dL in the other, and an average of the two describes neither. When the interaction is large relative to the effects, report the drug effect within each genotype and treat the main-effect rows of an ANOVA table as secondary.
The main-effect rows carry a second problem. An average needs weights, and with unequal cell counts the types of sums of squares choose different ones.
Type I, II, and III sums of squares
Section titled “Type I, II, and III sums of squares”An ANOVA table gives each term a sum of squares, the drop in residual variation when the term joins a model. The types differ in which other terms that model already holds.
- Type I adds the terms in the order of the formula. It tests the first factor alone, the second factor after the first, and the interaction after both.
- Type II tests each factor after the other factor, and the interaction after both. A factor is not adjusted for the interaction that contains it.
- Type III tests every term after all the others, the interaction included.
With equal cell counts the three types agree, provided that Type III uses the coding shown further down. anova() in R gives Type I, car::Anova() gives Type II or III, and anova_lm() in statsmodels takes typ=1, 2, or 3.
#' Print each term of an ANOVA table on one line.#'#' @param title A heading for the table.#' @param table A table from anova() or car::Anova().#' @return Invisibly, the table.PrintAnova <- function(title, table) { cat(title, "\n", sep = "") for (term in head(rownames(table), -1)) { cat(sprintf(" %-19s SS %7.1f df %.0f F %5.2f p = %.2g\n", term, table[term, "Sum Sq"], table[term, "Df"], table[term, "F value"], table[term, "Pr(>F)"])) } invisible(table)}
treatment_first <- lm(glucose_mg_dl ~ treatment * genotype, data = glucose)PrintAnova("Type I, genotype first", anova(model))PrintAnova("Type I, treatment first", anova(treatment_first))PrintAnova("Type II", car::Anova(model, type = 2))Type I, genotype first genotype SS 4374.3 df 1 F 15.87 p = 0.00032 treatment SS 8500.7 df 1 F 30.85 p = 2.7e-06 genotype:treatment SS 2026.6 df 1 F 7.35 p = 0.01Type I, treatment first treatment SS 6521.4 df 1 F 23.67 p = 2.3e-05 genotype SS 6353.7 df 1 F 23.06 p = 2.7e-05 treatment:genotype SS 2026.6 df 1 F 7.35 p = 0.01Type II genotype SS 6353.7 df 1 F 23.06 p = 2.7e-05 treatment SS 8500.7 df 1 F 30.85 p = 2.7e-06 genotype:treatment SS 2026.6 df 1 F 7.35 p = 0.01def print_anova(title, table): """Print each term of an ANOVA table on one line.
Args: title: A heading for the table. table: A data frame from ``anova_lm()``.
Returns: The table. """ print(title) for term, row in table.iloc[:-1].iterrows(): print(f" {term:<19} SS {row['sum_sq']:7.1f} df {row['df']:.0f} " f"F {row['F']:5.2f} p = {row['PR(>F)']:.2g}") return table
treatment_first = smf.ols("glucose_mg_dl ~ treatment * genotype", data=glucose).fit()print_anova("Type I, genotype first", anova_lm(model, typ=1))print_anova("Type I, treatment first", anova_lm(treatment_first, typ=1))print_anova("Type II", anova_lm(model, typ=2))Type I, genotype first genotype SS 4374.3 df 1 F 15.87 p = 0.00032 treatment SS 8500.7 df 1 F 30.85 p = 2.7e-06 genotype:treatment SS 2026.6 df 1 F 7.35 p = 0.01Type I, treatment first treatment SS 6521.4 df 1 F 23.67 p = 2.3e-05 genotype SS 6353.7 df 1 F 23.06 p = 2.7e-05 treatment:genotype SS 2026.6 df 1 F 7.35 p = 0.01Type II genotype SS 6353.7 df 1 F 23.06 p = 2.7e-05 treatment SS 8500.7 df 1 F 30.85 p = 2.7e-06 genotype:treatment SS 2026.6 df 1 F 7.35 p = 0.01The genotype sum of squares is 4374.3 when genotype enters first and 6353.7 when it enters second. The mice are the same; two words changed places in the formula. Entered first, genotype is tested with treatment ignored, and the groups are not comparable on treatment: 11 of the 18 knockout mice received the drug, against 10 of the 22 wild-type mice.
The Type II table does not depend on the order. Its genotype row, 6353.7, equals the Type I row in which genotype came after treatment, and its treatment row, 8500.7, equals the Type I row in which treatment came after genotype. The interaction row, 2026.6 with F = 7.35 and p = 0.01, is identical in all three tables because the interaction always enters last. Its p-value is the p-value of the interaction coefficient above.
Type III needs more care, because its main-effect rows depend on how the factors are coded.
sum_coded <- lm(glucose_mg_dl ~ genotype * treatment, data = glucose, contrasts = list(genotype = "contr.sum", treatment = "contr.sum"))PrintAnova("Type III, sum-to-zero contrasts", car::Anova(sum_coded, type = 3)[-1, ])PrintAnova("Type III, treatment contrasts", car::Anova(model, type = 3)[-1, ])Type III, sum-to-zero contrasts genotype SS 5717.8 df 1 F 20.75 p = 5.8e-05 treatment SS 7409.7 df 1 F 26.89 p = 8.5e-06 genotype:treatment SS 2026.6 df 1 F 7.35 p = 0.01Type III, treatment contrasts genotype SS 431.6 df 1 F 1.57 p = 0.22 treatment SS 9775.2 df 1 F 35.47 p = 8e-07 genotype:treatment SS 2026.6 df 1 F 7.35 p = 0.01sum_coded = smf.ols( "glucose_mg_dl ~ C(genotype, Sum) * C(treatment, Sum)", data=glucose).fit()sum_table = anova_lm(sum_coded, typ=3).drop("Intercept")sum_table.index = ["genotype", "treatment", "genotype:treatment", "Residual"]print_anova("Type III, sum-to-zero contrasts", sum_table)print_anova("Type III, treatment contrasts", anova_lm(model, typ=3).drop("Intercept"))Type III, sum-to-zero contrasts genotype SS 5717.8 df 1 F 20.75 p = 5.8e-05 treatment SS 7409.7 df 1 F 26.89 p = 8.5e-06 genotype:treatment SS 2026.6 df 1 F 7.35 p = 0.01Type III, treatment contrasts genotype SS 431.6 df 1 F 1.57 p = 0.22 treatment SS 9775.2 df 1 F 35.47 p = 8e-07 genotype:treatment SS 2026.6 df 1 F 7.35 p = 0.01With sum-to-zero contrasts, the Type III treatment row tests the average of the two drug effects with equal weight for each genotype, whatever the cell counts. Its F of 26.89 comes back in the next section as the square of a t statistic for exactly that average.
With treatment contrasts, the default coding in both languages, the same call tests something else. The genotype row has F = 1.57 and p = 0.22, the p-value of the genotype coefficient in the model above: knockout against wild type among vehicle mice only. Both tables carry the label Type III. Set sum-to-zero contrasts before you ask for Type III, or the rows named after a factor are simple effects at a reference level.
For this experiment, read the interaction row first, since every type agrees on it. When an interaction is small and a main effect is the target, Type II is the usual choice, because it adjusts each factor for the other factor and not for the interaction, which matches the assumption behind a main effect. When the interaction is large, as here, no main-effect row answers a useful question, and the simple effects do.
Simple effects
Section titled “Simple effects”A simple effect is the effect of one factor at one level of the other. Two are of interest here: the drug effect in the wild type and the drug effect in the knockout. Both use the residual variance of the full model on 36 degrees of freedom, which two separate t-tests would not.
Two intervals form a family of two. The code applies a Bonferroni adjustment: each interval is computed at 97.5% so that the pair has at least 95% joint coverage, and each p-value is doubled.
emmeans computes the cell means of the model, and pairs() contrasts them within each genotype. statsmodels has no equivalent of emmeans, but a simple effect is a sum of coefficients, and t_test() takes that sum as a row of weights. The drug effect in the wild type is the treatment coefficient. The drug effect in the knockout is the treatment coefficient plus the interaction coefficient.
cell_grid <- emmeans(model, ~ treatment | genotype)simple <- summary(pairs(cell_grid, reverse = TRUE), by = NULL, adjust = "bonferroni", infer = TRUE)for (row in seq_len(nrow(simple))) { cat(sprintf("Drug minus vehicle in %s: %.2f 95%% CI [%.2f, %.2f] ", as.character(simple$genotype[row]), simple$estimate[row], simple$lower.CL[row], simple$upper.CL[row])) cat(sprintf("adjusted p = %.2g\n", simple$p.value[row]))}average <- summary(pairs(emmeans(model, ~ treatment), reverse = TRUE))cat(sprintf("Average of the two: %.2f, t = %.3f, t squared = %.2f\n", average$estimate, average$t.ratio, average$t.ratio^2))Drug minus vehicle in WT: -42.33 95% CI [-58.96, -25.71] adjusted p = 1.6e-06Drug minus vehicle in KO: -13.26 95% CI [-32.03, 5.51] adjusted p = 0.21Average of the two: -27.80, t = -5.185, t squared = 26.89drug = "treatment[T.drug]"product = "genotype[T.KO]:treatment[T.drug]"weights = pd.DataFrame(0.0, index=["WT", "KO", "average"], columns=model.params.index)weights.loc["WT", drug] = 1.0weights.loc["KO", [drug, product]] = 1.0weights.loc["average"] = (weights.loc["WT"] + weights.loc["KO"]) / 2
simple = model.t_test(weights.loc[["WT", "KO"]].to_numpy())bonferroni = simple.conf_int(alpha=0.05 / 2)adjusted = np.minimum(simple.pvalue * 2, 1.0)for row, genotype in enumerate(["WT", "KO"]): print(f"Drug minus vehicle in {genotype}: {simple.effect[row]:.2f} " f"95% CI [{bonferroni[row, 0]:.2f}, {bonferroni[row, 1]:.2f}] " f"adjusted p = {adjusted[row]:.2g}")average = model.t_test(weights.loc[["average"]].to_numpy())print(f"Average of the two: {average.effect.item():.2f}, " f"t = {average.tvalue.item():.3f}, " f"t squared = {average.tvalue.item() ** 2:.2f}")Drug minus vehicle in WT: -42.33 95% CI [-58.96, -25.71] adjusted p = 1.6e-06Drug minus vehicle in KO: -13.26 95% CI [-32.03, 5.51] adjusted p = 0.21Average of the two: -27.80, t = -5.185, t squared = 26.89In the wild type the drug lowered glucose by 42.33 mg/dL, and reductions from 25.71 to 58.96 mg/dL are compatible with the data; the true value is 40. In the knockout the estimate is a reduction of 13.26 mg/dL, with an interval from a reduction of 32.03 to an increase of 5.51; the true value is 10.
These two lines do not show that the drug works in the wild type and fails in the knockout. The knockout interval includes zero, and it also includes a reduction of 32 mg/dL. The claim that the two effects differ rests on the interaction, 29.07 mg/dL with its interval from 7.33 to 50.82, and never on one simple effect having a small p-value while the other does not.
The last line settles the Type III question. The equal-weight average of the two drug effects is −27.80 mg/dL, and its t statistic squared is 26.89, the F of the treatment row under sum-to-zero contrasts. When asked for that average, emmeans prints “NOTE: Results may be misleading due to involvement in interactions”, which repeats the warning of the section on main effects.
The experimental unit
Section titled “The experimental unit”Every row of this table is a different mouse, and the 36 residual degrees of freedom count mice. If the table held three wells or three blood draws per mouse, the same model would count 120 independent values, and every interval above would be too narrow. Average to one value per mouse, or keep the rows and give each mouse a random effect as the mixed models page describes. The same rule applies one level up: when a whole cage receives the drug in its water, the cage is the unit.
Report the result
Section titled “Report the result”Give the four cell means with their counts, the interaction with its interval, and the simple effects: “The drug lowered fasting glucose by 42.3 mg/dL in wild-type mice and by 13.3 mg/dL in knockout mice (Bonferroni-adjusted 95% CI 25.7 to 59.0 and −5.5 to 32.0; n = 7 to 12 per cell). The difference between the two effects was 29.1 mg/dL (95% CI 7.3 to 50.8, p = 0.01).” If you print an ANOVA table, state the type of sums of squares, and for Type III the contrast coding.
Three mistakes are specific to this analysis.
- An interaction p-value above 0.05 does not show that the two effects are equal. Report the interval of the interaction; a wide one says that the experiment could not tell.
- The default
anova()table in R is Type I, andanova_lm()in statsmodels defaults to Type I as well. On unbalanced data, swapping the factors in the formula changes the rows, as the genotype row did above. - The model assumes one residual variance for all four cells. The cell standard deviations run from 15.61 to 18.83 mg/dL here; the assumptions page shows how to inspect residuals when they differ more.
The one-way ANOVA page covers a single factor. When a factor has three or more levels, the simple effects become families of pairwise comparisons, and the post hoc tests page covers their adjustment.
Scientific references
Section titled “Scientific references”Fox and Weisberg, 2019, describe the car functions in An R Companion to Applied Regression.
The emmeans package by Lenth and Piaskowski computes estimated marginal means.
Yates, 1934 sets out the analysis of a multiple classification with unequal numbers in the classes, including the method of fitting constants and the method of weighted squares of means.
Langsrud, 2003 argues for Type II over Type III sums of squares in the analysis of unbalanced data.
Further reading
Section titled “Further reading”The car Anova reference defines the Type II and Type III tests that Anova() computes and warns about model formulation for Type III.
The statsmodels anova_lm reference states what each typ tests and notes that Type III results depend on the contrast coding of the factors.
The emmeans interactions vignette works through simple contrasts and interaction contrasts for factorial models, including designs with more than two levels per factor.
The factorial ANOVA figure page draws the grouped box plot of a two-factor design for publication, with the ANOVA result on the figure.