svgemm-plot
Estimated marginal means
What does the model predict for each group (and does the effect of one factor depend on another)?
How to read it
- Read each point as the model's estimated mean at that level, adjusted for other terms.
- Read the bars as their intervals.
- With a second factor, compare the lines: non-parallel lines suggest an interaction.
- Callout 1: An adjusted mean and its interval.
- Callout 2: The gap between lines changes across levels.
- 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
# Estimated marginal means — Codesplash Chart Lab (recipe "emm-plot")
# controls: lines=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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("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
d = df.dropna(subset=[X, M])
xs = levels_of(d[X])
traces = levels_of(d[TR]) if TR else [None]
fig = go.Figure()
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)) for v in g[X]]).sort_values("_p")
err = dict(type="data", symmetric=False, array=g[HI] - g[M], arrayminus=g[M] - g[LO]) if LO and HI else None
fig.add_scatter(x=g[X].astype(str), y=g[M], mode="lines+markers" if LINES else "markers", name=str(t) if t is not None else M,
error_y=err, marker=dict(color=PALETTE[j % len(PALETTE)], size=8), line=dict(color=PALETTE[j % len(PALETTE)]))
fig.update_xaxes(categoryorder="array", categoryarray=xs, title=X)
fig.update_layout(yaxis_title=M, legend_title_text=TR or "")
fig.show()Needs pandas, numpy, plotly · reads emm-plot-demo.csv · app theme from the optional codesplash helper
# Estimated marginal means — Codesplash Chart Lab (recipe "emm-plot")
# controls: lines=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("emm-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["dose"]] <- factor(df[["dose"]], levels = c("0.5 mg", "1 mg", "2 mg"))
df[["supplement"]] <- factor(df[["supplement"]], levels = c("orange juice", "ascorbic acid"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
x_col <- "dose"
m_col <- "tooth length (EMM)"
lo_col <- "lower"
hi_col <- "upper"
tr_col <- "supplement"
show_lines <- TRUE
d <- df[!is.na(df[[x_col]]) & !is.na(df[[m_col]]), ]
d <- data.frame(x = factor(as.character(d[[x_col]]), levels = levels_of(d[[x_col]])), m = d[[m_col]],
lo = if (is.null(lo_col)) NA_real_ else d[[lo_col]], hi = if (is.null(hi_col)) NA_real_ else d[[hi_col]],
tr = if (is.null(tr_col)) "" else factor(as.character(d[[tr_col]]), levels = levels_of(d[[tr_col]])))
dodge <- position_dodge(width = 0.25)
p <- ggplot(d, aes(x, m, colour = tr, group = tr)) +
{ if (!all(is.na(d$lo))) geom_errorbar(aes(ymin = lo, ymax = hi), width = 0.12, position = dodge) } +
{ if (show_lines) geom_line(position = dodge) } +
geom_point(size = 2.6, position = dodge) +
scale_colour_manual(values = cs_cat, guide = if (is.null(tr_col)) "none" else "legend") +
labs(x = x_col, y = m_col, colour = tr_col) + theme_cs
print(p)Needs ggplot2 · reads emm-plot-demo.csv · app theme from the optional codesplashr helper