svgresidual-panel
Regression diagnostics panel
Do a model's residuals show non-linearity, non-normality, unequal spread or influential points?
How to read it
- Top left: residuals should scatter evenly around zero with no curve.
- Top right: points should follow the line if residuals are near normal.
- Bottom left: a flat smooth means equal spread. Bottom right: look for high leverage plus a large residual.
- Callout 1: A curved smooth: the model may miss non-linearity.
- Callout 2: Departures from the line at the ends: heavy tails.
- Callout 3: A rising smooth: spread grows with the fit.
- 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
# Regression diagnostics panel — Codesplash Chart Lab (recipe "residual-panel")
# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from scipy import stats
from plotly.subplots import make_subplots
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("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)
text = d[LAB].astype(str) if LAB else None
fig = make_subplots(rows=2, cols=2, subplot_titles=["Residuals vs fitted", "Normal Q–Q", "Scale–location", "Residuals vs leverage" if LEV else ""])
pt = dict(mode="markers", marker=dict(color=PALETTE[0], size=6, opacity=0.75), showlegend=False)
fig.add_scatter(x=d[FIT], y=d[RES], text=text, row=1, col=1, **pt)
fig.add_hline(y=0, line=dict(color=REF, dash="dash", width=1), row=1, col=1)
qs = np.sort(std.to_numpy())
th = stats.norm.ppf(ppoints(len(qs)))
q1, q3 = np.quantile(qs, [0.25, 0.75]), stats.norm.ppf([0.25, 0.75])
slope = (q1[1] - q1[0]) / (q3[1] - q3[0])
fig.add_scatter(x=th, y=qs, row=1, col=2, **pt)
fig.add_scatter(x=th, y=q1[0] + slope * (th - q3[0]), mode="lines", line=dict(color=REF, dash="dash", width=1), showlegend=False, row=1, col=2)
fig.add_scatter(x=d[FIT], y=np.sqrt(np.abs(std)), text=text, row=2, col=1, **pt)
if LEV:
fig.add_scatter(x=d[LEV], y=std, text=text, row=2, col=2, **pt)
p = d[LEV].sum()
h = np.linspace(max(d[LEV].min(), 1e-3), d[LEV].max(), 100)
for D in (0.5, 1):
r = np.sqrt(D * p * (1 - h) / h)
for sign in (1, -1):
fig.add_scatter(x=h, y=sign * r, mode="lines", line=dict(color="#ce5342", dash="dot", width=1), showlegend=False, row=2, col=2)
fig.update_yaxes(range=[min(std.min(), -3) * 1.1, max(std.max(), 3) * 1.1], row=2, col=2)
fig.update_xaxes(title_text=FIT, row=1, col=1)
fig.update_xaxes(title_text="theoretical quantiles", row=1, col=2)
fig.update_xaxes(title_text=FIT, row=2, col=1)
fig.update_yaxes(title_text="√|standardized residuals|", row=2, col=1)
fig.show()Needs pandas, numpy, plotly, scipy · reads residual-panel-demo.csv · app theme from the optional codesplash helper
# Regression diagnostics panel — Codesplash Chart Lab (recipe "residual-panel")
# 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("residual-panel-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
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
arrange <- function(plots, layout, widths = NULL, heights = NULL) {
# layout: matrix of plot indices (NA = empty cell). patchwork aligns the panels when it is
# installed; otherwise base grid viewports place the plots (axes may not line up exactly).
widths <- if (is.null(widths)) rep(1, ncol(layout)) else widths
heights <- if (is.null(heights)) rep(1, nrow(layout)) else heights
if (requireNamespace("patchwork", quietly = TRUE)) {
design <- paste(apply(layout, 1, function(r) paste(ifelse(is.na(r), "#", LETTERS[r]), collapse = "")), collapse = "\n")
print(patchwork::wrap_plots(plots, design = design, widths = widths, heights = heights, guides = "collect"))
return(invisible())
}
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(nrow(layout), ncol(layout),
widths = grid::unit(widths, "null"), heights = grid::unit(heights, "null"))))
for (i in seq_along(plots)) {
at <- which(layout == i, arr.ind = TRUE)
print(plots[[i]], vp = grid::viewport(layout.pos.row = unique(at[, 1]), layout.pos.col = unique(at[, 2])))
}
}
fit_col <- "fitted"
res_col <- "residual"
std_col <- "standardized residual"
lev_col <- "leverage"
cook_col <- "Cook's D"
lab_col <- NULL
d <- df[!is.na(df[[fit_col]]) & !is.na(df[[res_col]]), ]
d <- data.frame(fit = d[[fit_col]], res = d[[res_col]],
std = if (is.null(std_col)) (d[[res_col]] - mean(d[[res_col]])) / sd(d[[res_col]]) else d[[std_col]],
lev = if (is.null(lev_col)) NA_real_ else d[[lev_col]], cook = if (is.null(cook_col)) NA_real_ else d[[cook_col]],
lab = if (is.null(lab_col)) as.character(seq_len(nrow(d))) else as.character(d[[lab_col]]))
pt <- geom_point(colour = cs_cat[1], alpha = 0.75, size = 1.6)
p1 <- ggplot(d, aes(fit, res)) + geom_hline(yintercept = 0, linetype = "dashed", colour = ref_col) + pt +
labs(title = "Residuals vs fitted", x = fit_col, y = res_col) + theme_cs
p2 <- ggplot(d, aes(sample = std)) + stat_qq(colour = cs_cat[1], alpha = 0.75, size = 1.6) + stat_qq_line(linetype = "dashed", colour = ref_col) +
labs(title = "Normal Q–Q", x = "theoretical quantiles", y = "standardized residuals") + theme_cs
p3 <- ggplot(d, aes(fit, sqrt(abs(std)))) + pt + labs(title = "Scale–location", x = fit_col, y = "√|standardized residuals|") + theme_cs
p_coef <- sum(d$lev, na.rm = TRUE) # trace of the hat matrix = number of coefficients
h <- seq(max(min(d$lev, na.rm = TRUE), 1e-3), max(d$lev, na.rm = TRUE), length.out = 100)
contours <- do.call(rbind, lapply(c(0.5, 1), function(D) { r <- sqrt(D * p_coef * (1 - h) / h); rbind(data.frame(h = h, r = r, k = paste(D, "+")), data.frame(h = h, r = -r, k = paste(D, "-"))) }))
top <- head(d[order(-(if (all(is.na(d$cook))) abs(d$std) else d$cook)), ], 3)
p4 <- ggplot(d, aes(lev, std)) + geom_hline(yintercept = 0, linetype = "dashed", colour = ref_col) +
geom_line(data = contours, aes(h, r, group = k), colour = "#ce5342", linetype = "dotted") + pt +
geom_text(data = top, aes(label = lab), size = 2.6, hjust = -0.2, vjust = -0.4) +
coord_cartesian(ylim = c(min(d$std, -3), max(d$std, 3)) * 1.1) +
labs(title = "Residuals vs leverage", x = lev_col, y = "standardized residuals") + theme_cs
arrange(list(p1, p2, p3, p4), layout = matrix(1:4, 2, byrow = TRUE))Needs ggplot2 · reads residual-panel-demo.csv · app theme from the optional codesplashr helper