svgbrushableinteraction
Interaction plot
Does the effect of one factor depend on another?
How to read it
- Follow each line: it shows the mean across one factor at one level of the other.
- Parallel lines: the first factor's effect is the same at both levels.
- Non-parallel or crossing lines: the effect depends on the other factor.
- Callout 1: The lines spread apart here: the factors interact.
- Callout 2: The lines start close together at this level.
- Callout 3: Error bars: is the gap between the lines more than noise?
Watch out
- Non-parallel lines may be noise. Check the interaction term's test and interval before you interpret them.
Defaults
- Error bars
- Confidence interval (t)
- What the bars show: a confidence interval, a standard error or a standard deviation.
- Also: ± 1 SE · None
- Confidence level
- 0.95
- How often intervals built this way contain the true value, over repeated samples.
- Range 0.8 to 0.99, step 0.01
- Dodge traces
- On
- Nudge lines sideways so their error bars don't overlap.
Pinned in the code
- Each point is the mean of the outcome in one x × trace cell; error bars are per-cell t intervals x̄ ± t(1 − α/2, n − 1)·s/√n (no pooled error term) or ± SE.
- Lines connect cell means within a trace level; roughly parallel lines suggest additive effects. This is a descriptive plot — test the interaction (and get estimated marginal means) in Analyze.
- Traces are dodged horizontally so intervals do not overlap; x levels follow the dictionary order, else frequency.
# Interaction plot — Codesplash Chart Lab (recipe "interaction")
# controls: interval=ci, level=0.95, dodge=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]
df = pd.read_csv("interaction-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["fertilizer"] = pd.Categorical(df["fertilizer"].astype("string"), categories=["None", "Nitrogen", "Compost"])
df["irrigation"] = pd.Categorical(df["irrigation"].astype("string"), categories=["Low", "High"])
def levels(s):
"""Level order like the app: declared order (categorical dtype), else by descending frequency, ties alphabetical."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [str(c) for c in s.cat.categories]
counts = s.dropna().astype(str).value_counts()
return sorted(counts.index, key=lambda k: (-counts[k], k))
xl = levels(df["fertilizer"])[:10]
tl = levels(df["irrigation"])[:6]
d = df[["yield_t_ha", "fertilizer", "irrigation"]].dropna()
d = d.assign(_x=d["fertilizer"].astype(str), _t=d["irrigation"].astype(str))
d = d[d["_x"].isin(xl) & d["_t"].isin(tl)]
cells = d.groupby(["_t", "_x"])["yield_t_ha"].agg(["count", "mean", "std"])
cells["half"] = (stats.t.ppf(1 - (1 - 0.95) / 2, cells["count"] - 1) * cells["std"] / np.sqrt(cells["count"])).fillna(0) # per-cell t interval
DODGE = 0.08
fig, ax = plt.subplots(figsize=(7, 4.5))
for k, t in enumerate(tl):
if t not in cells.index.get_level_values(0):
continue
sub = cells.loc[t].reindex(xl).dropna(subset=["mean"])
xs = np.array([xl.index(v) for v in sub.index]) + (k - (len(tl) - 1) / 2) * DODGE
ax.errorbar(xs, sub["mean"], yerr=sub["half"], fmt="-o", capsize=3, color=PALETTE[k % len(PALETTE)], label=t)
ax.set_xticks(range(len(xl)), xl)
ax.set_xlabel("fertilizer")
ax.set_ylabel("Mean yield_t_ha")
ax.legend(title="irrigation")
plt.show()Needs pandas, numpy, matplotlib, scipy · reads interaction-demo.csv · app theme from the optional codesplash helper
# Interaction plot — Codesplash Chart Lab (recipe "interaction")
# controls: interval=ci, level=0.95, dodge=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from scipy import stats
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("interaction-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["fertilizer"] = pd.Categorical(df["fertilizer"].astype("string"), categories=["None", "Nitrogen", "Compost"])
df["irrigation"] = pd.Categorical(df["irrigation"].astype("string"), categories=["Low", "High"])
def levels(s):
"""Level order like the app: declared order (categorical dtype), else by descending frequency, ties alphabetical."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [str(c) for c in s.cat.categories]
counts = s.dropna().astype(str).value_counts()
return sorted(counts.index, key=lambda k: (-counts[k], k))
xl = levels(df["fertilizer"])[:10]
tl = levels(df["irrigation"])[:6]
d = df[["yield_t_ha", "fertilizer", "irrigation"]].dropna()
d = d.assign(_x=d["fertilizer"].astype(str), _t=d["irrigation"].astype(str))
d = d[d["_x"].isin(xl) & d["_t"].isin(tl)]
cells = d.groupby(["_t", "_x"])["yield_t_ha"].agg(["count", "mean", "std"])
cells["half"] = (stats.t.ppf(1 - (1 - 0.95) / 2, cells["count"] - 1) * cells["std"] / np.sqrt(cells["count"])).fillna(0) # per-cell t interval
DODGE = 0.08
fig = go.Figure()
for k, t in enumerate(tl):
if t not in cells.index.get_level_values(0):
continue
sub = cells.loc[t].reindex(xl).dropna(subset=["mean"])
xs = np.array([xl.index(v) for v in sub.index]) + (k - (len(tl) - 1) / 2) * DODGE
fig.add_scatter(x=xs, y=sub["mean"], mode="lines+markers", name=t, line_color=PALETTE[k % len(PALETTE)],
error_y=dict(type="data", array=sub["half"], width=4))
fig.update_layout(xaxis=dict(tickvals=list(range(len(xl))), ticktext=xl, title="fertilizer"), yaxis_title="Mean yield_t_ha", legend_title_text="irrigation")
fig.show()Needs pandas, numpy, plotly, scipy · reads interaction-demo.csv · app theme from the optional codesplash helper
# Interaction plot — Codesplash Chart Lab (recipe "interaction")
# controls: interval=ci, level=0.95, dodge=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("interaction-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["fertilizer"]] <- factor(df[["fertilizer"]], levels = c("None", "Nitrogen", "Compost"))
df[["irrigation"]] <- factor(df[["irrigation"]], levels = c("Low", "High"))
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
xl <- head(levels(df[["fertilizer"]]), 10)
tl <- head(levels(df[["irrigation"]]), 6)
d <- data.frame(y = df[["yield_t_ha"]], x = as.character(df[["fertilizer"]]), trace = as.character(df[["irrigation"]]))
d <- d[!is.na(d$y) & d$x %in% xl & d$trace %in% tl, ]
cells <- aggregate(y ~ x + trace, d, function(v) c(n = length(v), mean = mean(v), sd = if (length(v) > 1) sd(v) else NA))
cells <- data.frame(x = cells$x, trace = cells$trace, n = cells$y[, "n"], mean = cells$y[, "mean"], sd = cells$y[, "sd"])
cells$half <- qt(1 - (1 - 0.95) / 2, cells$n - 1) * cells$sd / sqrt(cells$n) # per-cell t interval (no pooled error term)
cells$half[is.na(cells$half)] <- 0
cells$x <- factor(cells$x, levels = xl)
cells$trace <- factor(cells$trace, levels = tl)
dodge <- position_dodge(width = 0.25)
p <- ggplot(cells, aes(x, mean, colour = trace, group = trace)) +
geom_line(position = dodge, linewidth = 0.9) +
geom_point(position = dodge, size = 2.5) +
geom_errorbar(aes(ymin = mean - half, ymax = mean + half), position = dodge, width = 0.12) +
scale_colour_manual(values = cs_cat, name = "irrigation") +
labs(x = "fertilizer", y = "Mean yield_t_ha") +
theme_cs
print(p)Needs ggplot2 · reads interaction-demo.csv · app theme from the optional codesplashr helper
-- Interaction plot — Codesplash Chart Lab (recipe "interaction")
-- controls: interval=ci, level=0.95, dodge=true
-- cell means of the outcome per x × trace with n, SD and SE (multiply SE by t(1 − α/2, n − 1) for the CI)
SELECT "fertilizer"::VARCHAR AS x, "irrigation"::VARCHAR AS trace, count(*) AS n, avg("yield_t_ha") AS mean,
stddev_samp("yield_t_ha") AS sd, stddev_samp("yield_t_ha") / sqrt(count(*)) AS se
FROM read_csv('interaction-demo.csv')
WHERE "fertilizer" IS NOT NULL AND "irrigation" IS NOT NULL AND "yield_t_ha" IS NOT NULL
GROUP BY 1, 2
ORDER BY trace, x;Needs duckdb · reads interaction-demo.csv