Skip to content
svgbrushableinteraction

Interaction plot

Does the effect of one factor depend on another?

Demo data · seed 20261101 · 120 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Follow each line: it shows the mean across one factor at one level of the other.
  2. Parallel lines: the first factor's effect is the same at both levels.
  3. Non-parallel or crossing lines: the effect depends on the other factor.
  1. Callout 1: The lines spread apart here: the factors interact.
  2. Callout 2: The lines start close together at this level.
  3. 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