svgadded-variable
Added-variable plot
What does one predictor add once the others are accounted for, and which rows drive it?
How to read it
- Read one panel per term: what that predictor adds after the others have explained what they can.
- The line's slope is the term's coefficient in the full model.
- Look for labelled rows far along the x axis: they have the most pull on that slope.
- Callout 1: The line's slope equals this term's coefficient.
- Callout 2: A labelled row: a strong pull on the slope.
- Callout 3: One panel per term; a flat line means it adds little.
Watch out
- A strong slope isn't causal, and one row can create or hide it: refit without the labelled rows to check.
Defaults
- Label influential rows
- On
- Name the rows with the largest pull on each slope.
Pinned in the code
- Each panel plots the residuals of y on the other predictors against the residuals of this predictor on the other predictors.
- The fitted line has an intercept; by the Frisch–Waugh–Lovell theorem its slope equals the term's coefficient in the full model.
- Influential rows are those with the largest |x·y| after centring.
# Added-variable plot — Codesplash Chart Lab (recipe "added-variable")
# controls: labels=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.nonparametric.smoothers_lowess import lowess
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("added-variable-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_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")
X = "predictor residual"
Y = "sales residual"
T = "term"
d = df.dropna(subset=[X, Y])
terms = list(dict.fromkeys(d[T].astype(str))) if T else ["all rows"]
fig, axes = plt.subplots(1, len(terms), figsize=(4.5 * len(terms), 4), squeeze=False)
for ax, t in zip(axes[0], terms):
g = d[d[T].astype(str) == t] if T else d
x, y = g[X].to_numpy(float), g[Y].to_numpy(float)
b, a = np.polyfit(x, y, 1) # the least-squares line
ax.scatter(x, y, s=10, color=PALETTE[0], alpha=0.6)
grid = np.array([x.min(), x.max()])
ax.plot(grid, a + b * grid, color=REF, linewidth=1.6)
ax.set_title(f"{t} (slope {b:.3g})", fontsize=10)
ax.set_xlabel("predictor | others")
ax.set_ylabel("outcome | others")
plt.tight_layout()
plt.show()Needs pandas, numpy, matplotlib, statsmodels · reads added-variable-demo.csv · app theme from the optional codesplash helper
# Added-variable plot — Codesplash Chart Lab (recipe "added-variable")
# controls: labels=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from statsmodels.nonparametric.smoothers_lowess import lowess
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("added-variable-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_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")
from plotly.subplots import make_subplots
X = "predictor residual"
Y = "sales residual"
T = "term"
d = df.dropna(subset=[X, Y])
terms = list(dict.fromkeys(d[T].astype(str))) if T else ["all rows"]
fig = make_subplots(rows=1, cols=len(terms), subplot_titles=terms)
for k, t in enumerate(terms, start=1):
g = d[d[T].astype(str) == t] if T else d
x, y = g[X].to_numpy(float), g[Y].to_numpy(float)
b, a = np.polyfit(x, y, 1)
fig.add_scatter(x=x, y=y, mode="markers", marker=dict(color=PALETTE[0], size=5, opacity=0.6), showlegend=False, row=1, col=k)
grid = np.array([x.min(), x.max()])
fig.add_scatter(x=grid, y=a + b * grid, mode="lines", line=dict(color=REF), showlegend=False, row=1, col=k)
fig.update_xaxes(title_text="predictor | others")
fig.update_yaxes(title_text="outcome | others")
fig.show()Needs pandas, numpy, plotly, statsmodels · reads added-variable-demo.csv · app theme from the optional codesplash helper
# Added-variable plot — Codesplash Chart Lab (recipe "added-variable")
# controls: labels=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("added-variable-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["term"]] <- factor(df[["term"]])
df[["row"]] <- factor(df[["row"]])
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
X <- "predictor residual"
Y <- "sales residual"
T <- "term"
d <- data.frame(x = df[[X]], y = df[[Y]], term = if (is.null(T)) "all rows" else as.character(df[[T]]))
d <- d[is.finite(d$x) & is.finite(d$y), ]
p <- ggplot(d, aes(x, y)) +
geom_point(colour = cs_cat[[1]], size = 1, alpha = 0.6) +
geom_smooth(method = "lm", formula = y ~ x, se = FALSE, colour = ref_col) +
facet_wrap(~term, scales = "free") +
labs(x = "predictor | others", y = "outcome | others") + theme_cs
print(p)Needs ggplot2 · reads added-variable-demo.csv · app theme from the optional codesplashr helper