Skip to content
svgresidual-panel

Regression diagnostics panel

Do a model's residuals show non-linearity, non-normality, unequal spread or influential points?

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

How to read it

  1. Top left: residuals should scatter evenly around zero with no curve.
  2. Top right: points should follow the line if residuals are near normal.
  3. Bottom left: a flat smooth means equal spread. Bottom right: look for high leverage plus a large residual.
  1. Callout 1: A curved smooth: the model may miss non-linearity.
  2. Callout 2: Departures from the line at the ends: heavy tails.
  3. Callout 3: A rising smooth: spread grows with the fit.
  4. Callout 4: Far right, beyond the Cook's lines: an influential point.

Watch out

  • Don't read plots of residuals against the outcome: they always trend, by construction.

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 statistical.
  • Layout and reference lines follow R `plot.lm` (which = 1, 2, 3, 5); smooths are LOESS (span 2/3, degree 1) instead of lowess.
  • Cook's contours at D = 0.5 and 1: |r| = √(D·p·(1 − h)/h), with p (number of coefficients) recovered from the engine's Cook's D, leverage and standardized residuals.
  • Without standardized residuals the chart uses residual / SD; without leverage the fourth panel shows residuals in data order (independence).
  • The three largest |standardized residuals| are labelled (row number unless a label column is given).
# Regression diagnostics panel — Codesplash Chart Lab (recipe "residual-panel")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("residual-panel-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")
def ppoints(n):
    a = 3 / 8 if n <= 10 else 0.5
    return (np.arange(1, n + 1) - a) / (n + 1 - 2 * a)
FIT = "fitted"
RES = "residual"
STD = "standardized residual"
LEV = "leverage"
COOK = "Cook's D"
LAB = None
d = df.dropna(subset=[FIT, RES]).reset_index(drop=True)
std = d[STD] if STD else (d[RES] - d[RES].mean()) / d[RES].std(ddof=1)  # standardized residuals
fig, axes = plt.subplots(2, 2, figsize=(9, 7))
a = axes[0, 0]
a.scatter(d[FIT], d[RES], s=14, color=PALETTE[0], alpha=0.75)
a.axhline(0, color=REF, linestyle="--", linewidth=1)
a.set(title="Residuals vs fitted", xlabel=FIT, ylabel=RES)
a = axes[0, 1]
qs = np.sort(std.to_numpy())
th = stats.norm.ppf(ppoints(len(qs)))
a.scatter(th, qs, s=14, color=PALETTE[0], alpha=0.75)
q1, q3 = np.quantile(qs, [0.25, 0.75]), stats.norm.ppf([0.25, 0.75])  # qqline through the quartiles
slope = (q1[1] - q1[0]) / (q3[1] - q3[0])
a.plot(th, q1[0] + slope * (th - q3[0]), color=REF, linestyle="--", linewidth=1)
a.set(title="Normal Q–Q", xlabel="theoretical quantiles", ylabel="standardized residuals")
a = axes[1, 0]
a.scatter(d[FIT], np.sqrt(np.abs(std)), s=14, color=PALETTE[0], alpha=0.75)
a.set(title="Scale–location", xlabel=FIT, ylabel="√|standardized residuals|")
a = axes[1, 1]
if LEV:
    a.scatter(d[LEV], std, s=14, color=PALETTE[0], alpha=0.75)
    a.axhline(0, color=REF, linestyle="--", linewidth=1)
    p = d[LEV].sum()  # trace of the hat matrix = number of coefficients
    h = np.linspace(max(d[LEV].min(), 1e-3), d[LEV].max(), 100)
    for D in (0.5, 1):  # Cook's distance contours
        r = np.sqrt(D * p * (1 - h) / h)
        a.plot(h, r, color="#ce5342", linestyle=":", linewidth=1)
        a.plot(h, -r, color="#ce5342", linestyle=":", linewidth=1)
    a.set_ylim(min(std.min(), -3) * 1.1, max(std.max(), 3) * 1.1)
    if COOK or LAB:
        top = d.assign(_c=d[COOK] if COOK else np.abs(std)).nlargest(3, "_c")
        for i, row in top.iterrows():
            a.annotate(str(row[LAB]) if LAB else str(i + 1), (row[LEV], std[i]), fontsize=7, xytext=(3, 3), textcoords="offset points")
    a.set(title="Residuals vs leverage", xlabel=LEV, ylabel="standardized residuals")
else:
    a.axis("off")
fig.tight_layout()
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads residual-panel-demo.csv · app theme from the optional codesplash helper