Skip to content
svgemm-plot

Estimated marginal means

What does the model predict for each group (and does the effect of one factor depend on another)?

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

How to read it

  1. Read each point as the model's estimated mean at that level, adjusted for other terms.
  2. Read the bars as their intervals.
  3. With a second factor, compare the lines: non-parallel lines suggest an interaction.
  1. Callout 1: An adjusted mean and its interval.
  2. Callout 2: The gap between lines changes across levels.
  3. Callout 3: At this dose the lines meet.

Watch out

  • These are model estimates, not raw means: they depend on the model and which levels it averages over.

Defaults

Connect levels
On
Join the levels of the factor with lines, which makes interactions easier to see.

Pinned in the code

  • Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing statistical.
  • Means are estimated marginal means from the fitted model (balanced reference grid, emmeans semantics), not raw cell means.
  • Levels of the second factor are dodged horizontally so intervals do not overlap; non-parallel lines suggest an interaction.
# Estimated marginal means — Codesplash Chart Lab (recipe "emm-plot")
# controls: lines=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

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("emm-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["dose"] = pd.Categorical(df["dose"].astype("string"), categories=["0.5 mg", "1 mg", "2 mg"])
df["supplement"] = pd.Categorical(df["supplement"].astype("string"), categories=["orange juice", "ascorbic acid"])

def levels_of(s):
    """Declared level order (categoricals), else order of first appearance."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [v for v in s.cat.categories if (s == v).any()]
    return list(dict.fromkeys(s.dropna().astype(str)))
X = "dose"
M = "tooth length (EMM)"
LO = "lower"
HI = "upper"
TR = "supplement"
LINES = True  # join the means of each trace level
d = df.dropna(subset=[X, M])
xs = levels_of(d[X])
traces = levels_of(d[TR]) if TR else [None]
off = np.linspace(-0.12, 0.12, len(traces)) if len(traces) > 1 else [0.0]  # dodge
fig, ax = plt.subplots(figsize=(8, 4.5))
for j, t in enumerate(traces):
    g = d if t is None else d[d[TR].astype(str) == str(t)]
    g = g.assign(_p=[xs.index(str(v)) + off[j] for v in g[X]]).sort_values("_p")
    col = PALETTE[j % len(PALETTE)]
    if LO and HI:
        ax.errorbar(g["_p"], g[M], yerr=[g[M] - g[LO], g[HI] - g[M]], fmt="none", ecolor=col, capsize=3, linewidth=1.2)
    ax.plot(g["_p"], g[M], marker="o", color=col, linestyle="-" if LINES else "none", label=str(t) if t is not None else M)
ax.set_xticks(range(len(xs)), xs)
ax.set_xlabel(X)
ax.set_ylabel(M)
if TR:
    ax.legend(title=TR, fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads emm-plot-demo.csv · app theme from the optional codesplash helper