lm() gives a slope, a standard error and a p-value for any data, including data that break the LINE assumptions of the model. The p-values and intervals of Chapter 12 are correct only if the LINE assumptions are true. You can use the residuals to check these assumptions.
13.1 The problem
We use two simulated data sets. In each data set, 100 adults report the cups of coffee that they drink per day. We record their systolic blood pressure (SBP) minus 120 mmHg. Data set A follows a straight line with normal errors. Data set B follows a curve.
set.seed(2026)n <-100coffee <-tibble(cups =runif(n, 0, 4),A =-4/3+2* cups +rnorm(n, 0, 2), # straight lineB =0.5* cups^2+rnorm(n, 0, 0.5)) # a curvefit_A <-lm(A ~ cups, data = coffee)fit_B <-lm(B ~ cups, data = coffee)rbind(A =coef(summary(fit_A))[2, ], B =coef(summary(fit_B))[2, ])
Estimate Std. Error t value Pr(>|t|)
A 2.150268 0.18113661 11.87097 1.128740e-20
B 1.943454 0.07050373 27.56527 5.808568e-48
Show code
coffee |>pivot_longer(c(A, B), names_to ="set", values_to ="sbp") |>mutate(set =paste("Data set", set)) |>ggplot(aes(cups, sbp)) +geom_point(colour ="steelblue", alpha =0.7, size =1.5) +geom_smooth(method ="lm", formula = y ~ x, se =FALSE, colour ="firebrick") +facet_wrap(~ set) +labs(x ="cups of coffee per day", y ="SBP - 120 (mmHg)")
Figure 13.1: Two simulated data sets: SBP minus 120 mmHg against cups of coffee per day. The red lines are the least-squares fits. The two lines are almost the same.
Both fits give almost the same slope in mmHg per cup: 2.15 for A and 1.94 for B. Both p-values are small, and B has the larger \(R^2\): 0.89 against 0.59 for A.
The two fits give the same line and both are “significant”. Can we trust both?
13.2 Intuitive solution
The model says that the residuals are random noise around zero. If the model is correct, the residuals have no pattern. If we plot each residual against its fitted value, we see a band of points with no shape.
Show code
bind_rows(tibble(set ="Data set A", fitted =fitted(fit_A), resid =residuals(fit_A)),tibble(set ="Data set B", fitted =fitted(fit_B), resid =residuals(fit_B))) |>ggplot(aes(fitted, resid)) +geom_hline(yintercept =0, linetype ="dashed", colour ="grey60") +geom_point(colour ="steelblue", alpha =0.7, size =1.5) +geom_smooth(method ="loess", formula = y ~ x, se =FALSE, colour ="firebrick") +facet_wrap(~ set, scales ="free_y") +labs(x ="fitted value", y ="residual")
Figure 13.2: Residuals against fitted values for the two coffee data sets (simulated). The red curve is a smooth (loess) through the residuals. A gives a flat band. B gives a U shape.
The residuals of A form a flat band. The residuals of B form a U. The line is too high in the middle and too low at both ends. So the mean of \(Y\) is not a straight line in \(x\), and assumption L is false.
For B, the slope of 1.94 is an average over a curve. It overstates the effect of the first cup and understates the effect of the fourth. The scatter plot hides this. The residual plot shows it, because it removes the trend and magnifies what is left.
13.3 Formal solution
plot(fit) in base R draws four diagnostic plots. Each plot checks a different assumption. We draw the same four plots with ggplot for both data sets.
Show code
diag4(fit_A, "Data set A") /diag4(fit_B, "Data set B")
Figure 13.3: The four diagnostic plots for data set A (top) and data set B (bottom), both simulated. Red curves are loess smooths. In the last panel, the Cook’s distance contours at 0.5 and 1 lie outside the plotted area, because no point has high leverage.
Plot
Checks
Good
Bad
Residuals vs fitted
L
A flat band around 0
A curve or a U
Normal Q-Q
N
Points on the line
Curved ends or a bend
Scale-location
E
A flat band
A rising or falling trend
Residuals vs leverage
Influence
All points inside \(D = 0.5\)
A point outside \(D = 1\)
None of the plots checks I. Independence comes from the design of the study. If you measure the same patient many times, or patients in clusters, the errors are correlated, and the plots do not show it.
13.3.1 Residuals vs fitted
This plot checks linearity. With one predictor, it shows the same information as residuals against \(x\). With many predictors, fitted values give one plot for the whole model. For data set A the smooth is flat. For data set B it is a U.
13.3.2 Construction of the Q-Q plot
The normal quantile-quantile (Q-Q) plot compares the residuals with a normal distribution. We build it by hand for the estriol model of Chapter 11.
# A tibble: 4 × 3
r p q
<dbl> <dbl> <dbl>
1 -2.24 0.0161 -2.14
2 -1.93 0.0484 -1.66
3 -1.32 0.0806 -1.40
4 -1.16 0.113 -1.21
To see why the points form a straight line, suppose that the residuals are normal with mean \(\mu\) and standard deviation (SD) \(\sigma\). Then \(r_i = \mu + \sigma Z_i\) with \(Z_i \sim N(0, 1)\). The \(i\)-th smallest residual is close to the \(p_i\) quantile of that normal distribution:
So the points fall on a line with intercept \(\mu\) and slope \(\sigma\). qqnorm() draws the points and qqline() draws a line through the first and third quartiles.
Show code
qq <-tibble(i =seq_along(r_sorted), r = r_sorted, p = p_i, q = q_i)g1 <-ggplot(qq, aes(i, r)) +geom_segment(aes(xend = i, yend =0), colour ="grey70") +geom_point(colour ="steelblue") +labs(title ="1. sort", x ="rank i", y ="residual")g2 <-ggplot() +stat_function(fun = pnorm, xlim =c(-2.6, 2.6), colour ="steelblue", linewidth =1) +geom_segment(data = qq, aes(x =-2.6, xend = q, y = p, yend = p), colour ="firebrick", alpha =0.3) +geom_segment(data = qq, aes(x = q, xend = q, y = p, yend =0), colour ="firebrick", alpha =0.3) +labs(title ="2. map through the normal CDF", x ="normal quantile q", y ="p = (i - 0.5)/n")g3 <-ggplot(qq, aes(q, r)) +geom_abline(intercept =0, slope =1, linetype ="dashed", colour ="grey50") +geom_point(colour ="steelblue") +labs(title ="3. plot r against q", x ="normal quantile q", y ="residual")g1 + g2 + g3
Figure 13.4: Building a Q-Q plot from the 31 standardised residuals of the estriol model (Greene and Touchstone, via Rosner). The left panel shows the sorted residuals. In the middle panel, the normal CDF maps each rank to a normal quantile. The right panel plots the residuals against the normal quantiles.
13.3.3 Shapes of the Q-Q plot
In most samples, the middle of a Q-Q plot follows the line. Departures from normality show in the two ends. Figure 13.5 shows four simulated samples of 100 values.
Figure 13.5: Q-Q plots of four simulated samples of 100 values. Normal data lie on the line. With heavy tails (t with 3 degrees of freedom), both ends move away from the line. Right skew (exponential) gives a bend, and light tails (uniform) give an S with flat ends.
If both ends move away from the line in opposite directions, the tails are heavier than normal. A bend over the whole range means skew. A few isolated points at one end are outliers. With small \(n\), some wiggle at the ends is normal.
The normality assumption matters least of the four. For large \(n\), the central limit theorem makes \(\hat\beta\) approximately normal even if the errors are not. Normality matters most for small samples and for prediction intervals, which are about one new observation.
13.3.4 Scale-location
This plot checks equal variance. It shows \(\sqrt{|r_i|}\) against the fitted values, where \(r_i\) is the standardised residual. If the variance is the same everywhere, the smooth is flat.
In Figure 13.3 the smooth for A is almost flat. For B it has a W shape. The straight line crosses the curve twice, so the residuals are small near the two crossings and large at the ends and in the middle. A funnel-shaped spread gives a rising trend.
Show code
set.seed(7)het <-tibble(x =runif(100, 0, 10), y =2+3* x +rnorm(100, 0, x))fit_het <-lm(y ~ x, data = het)d_het <-tibble(fitted =fitted(fit_het), resid =residuals(fit_het), std =rstandard(fit_het))h1 <-ggplot(d_het, aes(fitted, resid)) +geom_hline(yintercept =0, linetype ="dashed", colour ="grey60") +geom_point(colour ="steelblue", alpha =0.7) +labs(x ="fitted value", y ="residual")h2 <-ggplot(d_het, aes(fitted, sqrt(abs(std)))) +geom_point(colour ="steelblue", alpha =0.7) +geom_smooth(method ="loess", formula = y ~ x, se =FALSE, colour ="firebrick") +labs(x ="fitted value", y =expression(sqrt("|standardised residual|")))h1 + h2
Figure 13.6: A simulated data set in which the SD of the error grows with x. Left: residuals against fitted values fan out. Right: the scale-location smooth rises.
Unequal variance leaves \(\hat\beta\) unbiased. It makes the standard errors wrong, and so also the p-values and intervals.
13.3.5 Leverage
Some points have more power over the fitted line than others. With one predictor, the leverage of point \(i\) is
Leverage depends only on \(x\). A point far from \(\bar x\) has high leverage. In general, the fitted values are \(\hat{\mathbf y} = \mathbf H \mathbf y\), with the hat matrix\(\mathbf H = \mathbf X(\mathbf X^\top \mathbf X)^{-1}\mathbf X^\top\). The leverage \(h_{ii}\) is the \(i\)-th diagonal element of \(\mathbf H\).
It is the share of a point’s own \(y\) in its own fitted value. If you move \(y_i\) up by 1, \(\hat y_i\) moves up by \(h_{ii}\). We try this on the estriol data. We move the birthweight of one baby up by 4 units and refit.
h_e <-hatvalues(fit_e)nudge <-function(i, by =4) { d <- estriol_df d$birthweight[i] <- d$birthweight[i] + byunname(fitted(lm(birthweight ~ estriol, data = d))[i] -fitted(fit_e)[i])}far <-which.max(h_e) # most extreme estriolmid <-which.min(abs(estriol_df$estriol -mean(estriol_df$estriol))) # closest to the meantibble(point =c(far, mid), estriol = estriol_df$estriol[c(far, mid)],leverage = h_e[c(far, mid)], move =c(nudge(far), nudge(mid)), four_h =4* h_e[c(far, mid)])
The mother with 7 mg/24 h has leverage 0.187. When we nudge her baby by 4, her fitted value moves by 0.746, which is exactly \(4 \times h_{ii}\). A mother near the mean estriol has leverage 0.032, and her fitted value moves by only 0.129.
Show code
lev <-ggplot(tibble(estriol = estriol_df$estriol, h = h_e), aes(estriol, h)) +geom_hline(yintercept =2*2/nrow(estriol_df), linetype ="dashed", colour ="grey50") +geom_point(colour ="steelblue", size =2) +labs(x ="estriol (mg/24 h)", y ="leverage h")nudge_plot <-function(i, title) { d <- estriol_df; d$birthweight[i] <- d$birthweight[i] +4 f2 <-lm(birthweight ~ estriol, data = d)ggplot(estriol_df, aes(estriol, birthweight)) +geom_abline(intercept =coef(fit_e)[1], slope =coef(fit_e)[2], colour ="grey50", linetype ="dashed") +geom_abline(intercept =coef(f2)[1], slope =coef(f2)[2], colour ="firebrick") +geom_point(colour ="steelblue", size =1.5) +annotate("point", x = d$estriol[i], y = d$birthweight[i], shape =21, size =3, colour ="firebrick") +labs(title = title, x ="estriol (mg/24 h)", y ="birthweight (100 g)") +theme(plot.title =element_text(size =10))}lev +nudge_plot(mid, "nudge a central point") +nudge_plot(far, "nudge the far point")
Figure 13.7: Leverage of each pregnancy in the estriol data (Greene and Touchstone, via Rosner) against estriol (left), and the nudge test (middle and right). The dashed line is the 2p/n flag. The open circle is the nudged baby. The fitted line moves from grey (before) to red (after).
The leverages are between \(1/n\) and 1, and they add to \(p\), the number of coefficients. So the average leverage is \(p/n\). A common flag is \(h_{ii} > 2p/n\).
c(sum =sum(h_e), mean =mean(h_e), flag =2*2/nrow(estriol_df))
sum mean flag
2.00000000 0.06451613 0.12903226
which(h_e >2*2/nrow(estriol_df))
1 2 3 19
1 2 3 19
The leverages add to 2, because \(p\) = 2. The flag \(2p/n\) = 0.129 marks 4 pregnancies. These are the mothers with the lowest and highest estriol. High leverage alone means only that the point can move the line.
13.3.6 Standardised residuals
A point with high leverage pulls the line towards itself. So its raw residual is small, even if the point is unusual. The variance of the \(i\)-th residual is \(\sigma^2(1 - h_{ii})\). The standardised residual corrects for this:
If the model is correct, each \(r_i\) has a variance of approximately 1. Values beyond \(\pm 2\) need a check, and values beyond \(\pm 3\) are rare. R gives them with rstandard().
Here \(\hat y_{j(i)}\) is the fitted value for point \(j\) when we fit the model without point \(i\). The second form shows that a point needs both a large standardised residual and a high leverage to move the fit. We check the two forms on the estriol point with the largest \(D_i\).
The largest Cook’s distance in the estriol data is 0.279, for pregnancy 14. The usual flag is \(D_i > 1\). Some analysts use \(4/n\) as a screen. Figure 13.8 shows why both parts are necessary. The data are simulated: 14 points on a line, plus one red point.
Figure 13.8: Cook’s distance combines residual and leverage (simulated data). The grey dashed line is the fit without the red point, and the red line is the fit with it. Only a point with both high leverage and a large residual moves the line.
cook_stats |> dplyr::select(case, h, r, D)
# A tibble: 3 × 4
case h r D
<chr> <dbl> <dbl> <dbl>
1 outlier in y, low leverage 0.0667 3.42 0.418
2 high leverage, on the trend 0.726 -0.208 0.0574
3 high leverage, off the trend 0.726 -3.41 15.4
The outlier in \(y\) has a large residual (3.4) but low leverage, so \(D\) = 0.42. The far point on the trend has high leverage but a tiny residual, so \(D\) = 0.06. The far point off the trend has both, and \(D\) = 15.4. Only this point changes the line.
13.3.8 Reading the residuals-vs-leverage plot
The fourth diagnostic plot shows the standardised residual against the leverage. The \(x\) axis tells you how unusual a point’s \(x\) is. The \(y\) axis tells you how unusual its \(y\) is, given the fit. Cook’s distance combines the two axes. From the formula, the contour for a fixed \(D\) is
\[
r = \pm\sqrt{\frac{D\,p\,(1 - h)}{h}} .
\]
The contours curve towards the \(x\) axis. The higher the leverage, the smaller the residual that a point needs to be influential. Points outside the \(D = 1\) contour need attention. A point far out on only one axis is usually harmless.
We add one bad point to data set A: a person who drinks 12 cups a day and has an SBP of 120 mmHg (simulated).
Show code
coffee_bad <-bind_rows(coffee |> dplyr::select(cups, A), tibble(cups =12, A =0))fit_bad <-lm(A ~ cups, data = coffee_bad)rl_plot <-function(fit, title, highlight =NULL) { p <-length(coef(fit)) d <-tibble(h =hatvalues(fit), r =rstandard(fit), id =seq_along(h)) hh <-seq(min(d$h) *0.9, max(d$h) *1.05, length.out =200) cont <-expand_grid(D =c(0.5, 1), sign =c(-1, 1), h = hh) |>mutate(r = sign *cook_curve(D, p, h), grp =paste(D, sign))ggplot(d, aes(h, r)) +geom_hline(yintercept =0, colour ="grey60", linetype ="dashed") +geom_line(data = cont, aes(group = grp, linetype =factor(D)), colour ="firebrick", linewidth =0.5) +geom_point(colour ="steelblue", alpha =0.7) +geom_point(data =filter(d, id %in% highlight), colour ="firebrick", size =3) +scale_linetype_manual(values =c(`0.5`="dashed", `1`="solid"), name ="Cook's D") +coord_cartesian(ylim =range(c(d$r, -3, 3))) +labs(title = title, x ="leverage", y ="standardised residual")}(rl_plot(fit_e, "estriol") +rl_plot(fit_bad, "coffee A + one point", highlight =nrow(coffee_bad))) +plot_layout(guides ="collect")
Figure 13.9: Residuals against leverage, with Cook’s distance contours at 0.5 (dashed) and 1 (solid). Left: the estriol model (Greene and Touchstone, via Rosner). Right: data set A (simulated) plus one person with 12 cups a day and SBP 120 mmHg (red).
k <-nrow(coffee_bad)c(leverage =hatvalues(fit_bad)[k], r =rstandard(fit_bad)[k], D =cooks.distance(fit_bad)[k])
(Intercept) cups
without -1.6776867 2.150268
with 0.1606889 1.129912
In the estriol model, every point is inside the \(D = 0.5\) contour. No one pregnancy drives the fit. In the coffee data, the added point has leverage 0.43 and a standardised residual of -6.5. Its Cook’s distance is 16.2. This one person out of 101 changes the slope from 2.15 to 1.13 mmHg per cup.
13.4 Diagnostics by hand
plot(fit), hatvalues(), rstandard() and cooks.distance() give the diagnostic values. You can also calculate each value by hand. We take six pregnancies from the estriol data and fill a table, one column at a time.
six <- estriol_df[c(1, 4, 10, 24, 29, 19), ]x <- six$estriol; y <- six$birthweightn6 <-length(x); p6 <-2six
13.4.2 Step 2: fitted values, residuals and \(\hat\sigma\)
Each fitted value is \(\hat y_i = b_0 + b_1 x_i\), and each residual is \(e_i = y_i - \hat y_i\). The residual variance is \(\hat\sigma^2 = \sum e_i^2/(n - p)\), with \(n - p\) = 4 degrees of freedom.
Figure 13.10: Residuals against leverage for six pregnancies from the estriol data (Greene and Touchstone, via Rosner), with Cook’s distance contours at 0.5 (dashed) and 1 (solid). Each point is labelled with its estriol value. The red point lies outside D = 1.
13.4.4 Reading the table
The leverages add to 2, which is \(p\). The two mothers at the ends of the estriol range, 7 and 27 mg/24 h, have the highest leverage. The mother with estriol 27 has leverage 0.546 and a standardised residual of -1.75. Neither number is extreme alone. Together they give \(D\) = 1.85, outside the \(D = 1\) contour.
With 6 points, the average leverage \(p/n\) is 0.333. The \(2p/n\) flag is 0.667, so it marks no point. Cook’s distance finds this mother. If we remove her, the slope changes from 0.629 to 0.97.
With more than one predictor, only the leverage needs a new formula. The leverages are the diagonal of the hat matrix \(\mathbf H = \mathbf X(\mathbf X^\top \mathbf X)^{-1}\mathbf X^\top\). The residuals, \(r_i\) and \(D_i\) follow from the same formulas, with \(p\) the number of coefficients.
X <-cbind(1, x) # one column per coefficientH <- X %*%solve(t(X) %*% X) %*%t(X)all.equal(unname(diag(H)), unname(h))
[1] TRUE
13.5 What to do about each problem
What you see
What it means
What you can do
Curve in residuals vs fitted
The mean is not linear in \(x\) (L)
Add \(x^2\) or a spline, or transform \(x\) (for example log)
Funnel, or a trend in scale-location
The variance changes with \(x\) (E)
Transform \(Y\) (log or square root), or use weighted least squares or robust (sandwich) standard errors
Curved ends or a bend in the Q-Q plot
The errors are not normal (N)
Accept it for large \(n\), transform \(Y\), or use bootstrap intervals
A point outside \(D = 1\)
One point drives the fit
Check for a data error, report the fit with and without it, or use robust regression
Repeated measures or clusters
The errors are correlated (I)
Use mixed models or GEE (the plots do not show this)
Do not delete an influential point by default. The first step is to find out why the point is unusual. It can be a typing error, a patient from a different population, or a real observation that the model does not explain.
For data set B, the residual plot showed a curve. A linear model can still fit a curve, because “linear” means linear in the coefficients. We add a squared term:
fit_B2 <-lm(B ~ cups +I(cups^2), data = coffee)coef(summary(fit_B2))
f1 <-ggplot(coffee, aes(cups, B)) +geom_point(colour ="steelblue", alpha =0.7) +geom_line(aes(y =fitted(fit_B2)), colour ="firebrick", linewidth =1) +labs(x ="cups of coffee per day", y ="SBP - 120 (mmHg)")f2 <-ggplot(tibble(fitted =fitted(fit_B2), resid =residuals(fit_B2)), aes(fitted, resid)) +geom_hline(yintercept =0, linetype ="dashed", colour ="grey60") +geom_point(colour ="steelblue", alpha =0.7) +geom_smooth(method ="loess", formula = y ~ x, se =FALSE, colour ="firebrick") +labs(x ="fitted value", y ="residual")f1 + f2
Figure 13.11: Data set B (simulated) with a quadratic term added. Left: the fitted curve. Right: the residuals now form a flat band.
The coefficient of the squared term is 0.54, close to the 0.5 that we used to simulate the data. The residuals are now a flat band. The residual standard error falls from 0.82 to 0.46. With a curve, the effect of one extra cup depends on how many cups a person already drinks.
13.6 Summary
The p-value of a fitted model is correct only when the LINE assumptions hold, so the residual plots come before the p-value.
Residuals vs fitted checks linearity, the Q-Q plot checks normality, and scale-location checks equal variance. No plot checks independence.
Leverage \(h_{ii} = \partial \hat y_i / \partial y_i\) depends only on \(x\). Its average is \(p/n\).
Cook’s distance \(D_i = (r_i^2/p)\,h_{ii}/(1 - h_{ii})\) is large only for a point with both high leverage and a large residual.