svgnested-compare
Nested model comparison
Does each added block of predictors improve the model enough?
How to read it
- Read left to right as adding blocks of predictors.
- Lower deviance means a closer fit, and it always falls.
- Read the labels between points: does each drop beat its test?
- Callout 1: The simplest model.
- Callout 2: A big drop, with its test.
- Callout 3: A small drop that doesn't earn its complexity.
Watch out
- The order of adding blocks changes each step's test.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing inferential.
- Models are in the order given (smallest first); each annotation is the test of that model against the previous one (LR χ², Wald, score or partial F).
# Nested model comparison — Codesplash Chart Lab (recipe "nested-compare")
# controls: defaults
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("nested-compare-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["model"] = pd.Categorical(df["model"].astype("string"), categories=["intercept", "+ age", "+ age + sex", "+ age × sex"])
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
M = "model"
V = "deviance"
S = "LR chi2"
P = "p"
d = df.dropna(subset=[V]).drop_duplicates(subset=[M]).reset_index(drop=True)
x = np.arange(len(d))
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(x, d[V], color=GREY, marker="o", markerfacecolor=PALETTE[0], markeredgecolor=PALETTE[0])
for i in range(1, len(d)):
bits = ([f"stat {d[S][i]:.3g}"] if S and pd.notna(d[S][i]) else []) + ([("p < .001" if d[P][i] < 0.001 else f"p = {d[P][i]:.3f}".replace("0.", "."))] if P and pd.notna(d[P][i]) else [])
ax.annotate(", ".join(bits), ((x[i - 1] + x[i]) / 2, (d[V][i - 1] + d[V][i]) / 2), ha="center", va="top", xytext=(0, -6), textcoords="offset points", fontsize=8)
ax.set_xticks(x, d[M].astype(str))
ax.set_ylabel(V)
plt.show()Needs pandas, numpy, matplotlib · reads nested-compare-demo.csv · app theme from the optional codesplash helper
# Nested model comparison — Codesplash Chart Lab (recipe "nested-compare")
# controls: defaults
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("nested-compare-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["model"] = pd.Categorical(df["model"].astype("string"), categories=["intercept", "+ age", "+ age + sex", "+ age × sex"])
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
M = "model"
V = "deviance"
S = "LR chi2"
P = "p"
d = df.dropna(subset=[V]).drop_duplicates(subset=[M]).reset_index(drop=True)
fig = go.Figure()
fig.add_scatter(x=d[M].astype(str), y=d[V], mode="lines+markers+text", text=d[V].map(lambda v: f"{v:.4g}"), textposition="top center", line_color=GREY, marker=dict(color=PALETTE[0], size=10), showlegend=False)
for i in range(1, len(d)):
if P and pd.notna(d[P][i]):
fig.add_annotation(x=i - 0.5, y=(d[V][i - 1] + d[V][i]) / 2, xref="x", text="p < .001" if d[P][i] < 0.001 else f"p = {d[P][i]:.3f}", showarrow=False, yshift=-14)
fig.update_layout(yaxis_title=V)
fig.show()Needs pandas, numpy, plotly · reads nested-compare-demo.csv · app theme from the optional codesplash helper
# Nested model comparison — Codesplash Chart Lab (recipe "nested-compare")
# controls: defaults
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("nested-compare-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["model"]] <- factor(df[["model"]], levels = c("intercept", "+ age", "+ age + sex", "+ age × sex"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
m_col <- "model"
v_col <- "deviance"
s_col <- "LR chi2"
p_col <- "p"
d <- df[!is.na(df[[v_col]]), ]
d <- d[!duplicated(as.character(d[[m_col]])), ]
d <- data.frame(model = factor(as.character(d[[m_col]]), levels = unique(as.character(d[[m_col]]))), v = d[[v_col]], p = if (is.null(p_col)) NA_real_ else d[[p_col]])
mids <- data.frame(x = seq_len(nrow(d) - 1) + 0.5, y = (head(d$v, -1) + tail(d$v, -1)) / 2, p = d$p[-1])
mids$lab <- ifelse(is.na(mids$p), "", ifelse(mids$p < 0.001, "p < .001", sub("^0", "", sprintf("p = %.3f", mids$p))))
p <- ggplot(d, aes(model, v, group = 1)) + geom_line(colour = grey_col) + geom_point(size = 3, colour = cs_cat[1]) +
geom_text(aes(label = format(v, digits = 4)), vjust = -1, size = 3) +
geom_text(data = mids, aes(x, y, label = lab), vjust = 1.8, size = 3, inherit.aes = FALSE) +
labs(x = NULL, y = v_col) + theme_cs
print(p)Needs ggplot2 · reads nested-compare-demo.csv · app theme from the optional codesplashr helper