svgcomponent-residual
Component-plus-residual plot
Is a predictor's effect really a straight line?
How to read it
- Read the straight line as what the model assumes for this predictor.
- Read the smooth as what the data suggest.
- Where they part, the effect is curved: try a transformation or a spline.
- Callout 1: The smooth bends away from the line here.
- Callout 2: The line: the linear term in the model.
Watch out
- The smooth is unstable at the edges with few rows, so don't over-read its ends.
Defaults
- Smooth
- On
- Add a LOESS curve; a gap between it and the line suggests a curved effect.
Pinned in the code
- The partial residual is e + β̂ⱼxⱼ, so the least-squares line has the term's coefficient as its slope.
- LOESS with span 0.75 (local linear, tricube weights), as the scatter recipe uses.
# Component-plus-residual plot — Codesplash Chart Lab (recipe "component-residual")
# controls: smooth=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("component-residual-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 = "ad spend"
Y = "component + residual"
T = None
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)
s = lowess(y, x, frac=0.75, it=0)
ax.plot(s[:, 0], s[:, 1], color=PALETTE[1], linewidth=1.6)
ax.set_title(f"{t} (slope {b:.3g})", fontsize=10)
ax.set_xlabel("predictor")
ax.set_ylabel("component + residual")
plt.tight_layout()
plt.show()Needs pandas, numpy, matplotlib, statsmodels · reads component-residual-demo.csv · app theme from the optional codesplash helper
# Component-plus-residual plot — Codesplash Chart Lab (recipe "component-residual")
# controls: smooth=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("component-residual-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 = "ad spend"
Y = "component + residual"
T = None
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)
s = lowess(y, x, frac=0.75, it=0)
fig.add_scatter(x=s[:, 0], y=s[:, 1], mode="lines", line=dict(color=PALETTE[1]), showlegend=False, row=1, col=k)
fig.update_xaxes(title_text="predictor")
fig.update_yaxes(title_text="component + residual")
fig.show()Needs pandas, numpy, plotly, statsmodels · reads component-residual-demo.csv · app theme from the optional codesplash helper
# Component-plus-residual plot — Codesplash Chart Lab (recipe "component-residual")
# controls: smooth=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("component-residual-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
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 <- "ad spend"
Y <- "component + residual"
T <- NULL
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) +
geom_smooth(method = "loess", formula = y ~ x, span = 0.75, method.args = list(degree = 1, family = "gaussian", surface = "direct"), se = FALSE, colour = cs_cat[[2]]) +
facet_wrap(~term, scales = "free") +
labs(x = "predictor", y = "component + residual") + theme_cs
print(p)Needs ggplot2 · reads component-residual-demo.csv · app theme from the optional codesplashr helper