Skip to content
svgcomponent-residual

Component-plus-residual plot

Is a predictor's effect really a straight line?

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

How to read it

  1. Read the straight line as what the model assumes for this predictor.
  2. Read the smooth as what the data suggest.
  3. Where they part, the effect is curved: try a transformation or a spline.
  1. Callout 1: The smooth bends away from the line here.
  2. 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