Skip to main content

16  The Linearity Assumption

“Non-linear means it’s hard to solve.” - Arthur Mattuck

16.1 Scatterplot Matrix

To check the linearity assumption in a multiple regression model, start by looking at how the predictors relate to the response with a scatterplot matrix. The matrix is a grid of scatterplots, one for each pair of variables. The plots we care about most are the ones that pair each predictor with the response.

In multiple regression, we expect the relationship between each predictor and the response to be roughly linear. If the scatterplot of a predictor against the response shows a straight-line trend, that fits the assumption. If the plot shows a clear curve, the linearity assumption may not hold for that predictor, and a transformation of the variable may describe the relationship better.

NoteWhat does linearity mean here?

In regression, “linear” means linear in the coefficients. The predictors themselves can be transformed.

For example,

\[ E(y)=\beta_0+\beta_1x \]

is linear in the coefficients, but so is

\[ E(y)=\beta_0+\beta_1\log(x) \]

and

\[ E(y)=\beta_0+\beta_1x+\beta_2x^2. \]

The second and third models can describe curved relationships and are still linear regression models, because the \(\beta\) coefficients enter the model linearly.

A scatterplot matrix lets you scan for nonlinearity quickly before you fit the model. The GGally package in R, which extends ggplot2, will draw one for you. Each panel shows how one variable changes with another, and from these panels you can decide whether any predictor needs a transformation before the regression model is fit.

ExampleScatterplot matrix for checking linearity
library(GGally)
library(tidyverse)

ggpairs(mtcars)

Here ggpairs draws a scatterplot matrix for the mtcars dataset, with one panel for each pair of variables. Look at the panels that involve the response (mpg in this case) to see whether its relationship with each predictor, such as wt or hp, looks linear. A curved trend in any of them suggests the predictor may need a transformation.

Doing this before fitting lets you catch problems with linearity early, which leads to a better fit and results that are easier to trust.

16.1.1 Discrete Predictors

Some predictors take only a few values, such as gear or cyl in the mtcars dataset. In the scatterplot matrix their points line up in vertical or horizontal stripes at those values, so linearity is harder to judge. There is no smooth trend to follow; instead, look at how the response changes from one level of the predictor to the next. A steady shift up or down across the levels can still point to a linear trend. If the pattern bends (for example, high values for the middle category and low values at both ends), a polynomial term or treating the predictor as categorical may improve the model.

For example, cyl in mtcars has only three values (4, 6, and 8). If mpg drops in a straight line as cyl goes up, that supports linearity. If the trend is irregular, a transformation or a different approach may be needed.

16.2 Identifying Transformations

When the scatterplot matrix shows a curved relationship between a predictor and the response, transforming the predictor can make the relationship closer to linear. Log, square root, and polynomial transformations are the usual choices. A good transformation captures the curve so the regression model gives accurate estimates.

In the tidyverse, you can apply a transformation with mutate() from the dplyr package and then use the new variable in a regression model in the Tidymodels framework.

TipChoosing a transformation

Pick a transformation that matches the pattern in the data. Do not pick one only because it raises \(R^2\).

Pattern in scatterplot Possible next step Interpretation caution
Curves that flatten out Try a log transformation such as \(\log(x)\). A one-unit change in \(\log(x)\) is not the same as a one-unit change in \(x\).
Counts or right-skewed positive predictors Try a square-root or log transformation. Log transformations require positive values.
U-shaped or inverted U-shaped pattern Try a polynomial term such as \(x^2\). Polynomial terms can behave strangely outside the observed range of the data.
Few distinct predictor values Consider treating the predictor as categorical. A numeric code may not represent equal spacing between levels.

After transforming, always refit the model and check the residual plots again.

Example 16.1  

ExampleLog transformation in mtcars

In the scatterplot matrix, mpg versus disp looked curved. Let’s try a log transformation of disp.

# Add a log-transformed variable for displacement (disp)
mtcars |>
  mutate(log_disp = log(disp)) |>
  select(mpg, log_disp, disp) |>
  ggpairs()

The scatterplot of mpg against log_disp looks more linear than the one against disp.

ExamplePolynomial terms are still linear regression

A model with a squared predictor can describe a curved relationship and still be a linear regression model.

quadratic_fit <- lm(mpg ~ wt + I(wt^2), data = mtcars)

broom::tidy(quadratic_fit)
# A tibble: 3 × 5
  term        estimate std.error statistic  p.value
  <chr>          <dbl>     <dbl>     <dbl>    <dbl>
1 (Intercept)    49.9      4.21      11.9  1.21e-12
2 wt            -13.4      2.51      -5.32 1.04e- 5
3 I(wt^2)         1.17     0.359      3.26 2.86e- 3

The term I(wt^2) makes a new predictor by squaring wt. As a function of wt the model is curved, but it is still linear in the coefficients.

16.3 Fitting the Model with Transformed Variables

Once you have chosen and applied the transformations, fit the multiple regression model with the transformed predictors. A model that meets the linearity assumption gives more reliable predictions and inferences. Here is an example.

Example 16.2  

ExampleComparing models with and without transformed predictors

We will fit two models, one with transformed variables and one without, and compare them using \(R^2\). We transform disp, hp, and wt, since these three looked nonlinear in the scatterplot matrix. The discrete variables are left out of this example.

library(tidymodels)

# Untransformed variables
untransformed_recipe <- recipe(
  mpg ~ disp + hp + drat + wt + qsec,
  data = mtcars
)

lm_model <- linear_reg() |>
  set_engine("lm")

untransformed_workflow <- workflow() |>
  add_recipe(untransformed_recipe) |>
  add_model(lm_model)

fit_untransformed <- untransformed_workflow |>
  fit(data = mtcars)

untransformed_metrics <- fit_untransformed |>
  glance() |>
  mutate(model = "Untransformed predictors")

untransformed_metrics |>
  select(model, r.squared, adj.r.squared, sigma, statistic, p.value)
# A tibble: 1 × 6
  model                    r.squared adj.r.squared sigma statistic  p.value
  <chr>                        <dbl>         <dbl> <dbl>     <dbl>    <dbl>
1 Untransformed predictors     0.849         0.820  2.56      29.2 6.89e-10

Now we fit the model with the transformed variables.

# Transformed variables
transformed_recipe <- recipe(
  mpg ~ disp + hp + drat + wt + qsec,
  data = mtcars
) |>
  step_mutate(
    log_disp = log(disp),
    log_hp = log(hp),
    log_wt = log(wt)
  ) |>
  step_rm(disp, hp, wt)

transformed_workflow <- workflow() |>
  add_recipe(transformed_recipe) |>
  add_model(lm_model)

fit_transformed <- transformed_workflow |>
  fit(data = mtcars)

transformed_metrics <- fit_transformed |>
  glance() |>
  mutate(model = "Transformed predictors")

bind_rows(untransformed_metrics, transformed_metrics) |>
  select(model, r.squared, adj.r.squared, sigma, statistic, p.value)
# A tibble: 2 × 6
  model                    r.squared adj.r.squared sigma statistic  p.value
  <chr>                        <dbl>         <dbl> <dbl>     <dbl>    <dbl>
1 Untransformed predictors     0.849         0.820  2.56      29.2 6.89e-10
2 Transformed predictors       0.892         0.871  2.16      43.0 9.14e-12

The coefficient of determination is higher with the transformed variables. The residual standard error, sigma, is also lower, so the typical residual in the transformed model is smaller.

WarningInterpreting coefficients after log transformations

After a predictor is log-transformed, its coefficient is no longer the change in \(y\) for a one-unit increase in the original predictor.

For example, in a model with

\[ E(y)=\beta_0+\beta_1\log(x), \]

\(\beta_1\) is the expected change in \(y\) for a one-unit increase in \(\log(x)\), not in \(x\). It is often more useful to interpret it in terms of percentage changes:

  • A 1% increase in \(x\) is associated with an approximate change of \(0.01\beta_1\) units in the mean response.
  • Doubling \(x\) is associated with a change of \(\beta_1\log(2)\) units in the mean response.

So a transformed predictor may improve the fit, but it also changes how you explain its coefficient.

WarningDo not rely on R-squared alone

A larger \(R^2\) can suggest that a transformed model fits better, but it does not prove the linearity problem is fixed. A model can have a larger \(R^2\) and still show a curved residual pattern.

Use numerical summaries to compare fit, and use residual plots to check whether the linearity assumption looks reasonable.

16.4 Transforming the Response Variable

So far we have transformed only predictors. Sometimes it helps to transform the response as well. This is most common when the response is positive and the relationship looks multiplicative, or when the residuals spread out more as the fitted values increase.

For example, we could model log(mpg) in place of mpg. That puts the response on a new scale, so the residuals, the fitted values, and the coefficient interpretations are all on the log scale.

ExampleTransforming the response variable

This model uses the same predictors as before, with the response transformed.

log_response_fit <- lm(
  log(mpg) ~ disp + hp + drat + wt + qsec,
  data = mtcars
)

broom::tidy(log_response_fit)
# A tibble: 6 × 5
  term          estimate std.error statistic     p.value
  <chr>            <dbl>     <dbl>     <dbl>       <dbl>
1 (Intercept)  3.11       0.482        6.45  0.000000787
2 disp         0.0000598  0.000492     0.121 0.904      
3 hp          -0.000923   0.000672    -1.37  0.181      
4 drat         0.0542     0.0576       0.940 0.356      
5 wt          -0.207      0.0547      -3.78  0.000821   
6 qsec         0.0247     0.0202       1.22  0.232      
broom::glance(log_response_fit) |>
  select(r.squared, adj.r.squared, sigma, statistic, p.value)
# A tibble: 1 × 5
  r.squared adj.r.squared sigma statistic  p.value
      <dbl>         <dbl> <dbl>     <dbl>    <dbl>
1     0.880         0.857 0.113      38.2 3.54e-11

The fitted values from this model estimate \(\log(mpg)\), not mpg. To get predictions on the original mpg scale, we have to back-transform.

log_response_predictions <- tibble(
  observed_mpg = mtcars$mpg,
  fitted_log_mpg = fitted(log_response_fit),
  fitted_mpg = exp(fitted(log_response_fit)),
  residual_log_scale = residuals(log_response_fit)
)

log_response_predictions |>
  head()
# A tibble: 6 × 4
  observed_mpg fitted_log_mpg fitted_mpg residual_log_scale
         <dbl>          <dbl>      <dbl>              <dbl>
1         21             3.09       22.0           -0.0483 
2         21             3.05       21.2           -0.00940
3         22.8           3.22       25.0           -0.0912 
4         21.4           3.00       20.2            0.0586 
5         18.7           2.85       17.3            0.0802 
6         18.1           2.96       19.3           -0.0628 

Back-transforming with exp() gives predictions in the original units, but the inference is still done on the log scale. That is one reason to use response transformations with care and to explain them carefully.

WarningInterpreting coefficients after transforming the response

When the response is log-transformed, the coefficient interpretations change again. In a model such as

\[ \log(y)=\beta_0+\beta_1x, \]

a one-unit increase in \(x\) is associated with multiplying the typical value of \(y\) by \(e^{\beta_1}\). For small values of \(\beta_1\), this is approximately a \(100\beta_1\%\) change in \(y\).

The phrase “typical value” is doing some work here. Because the model is fit on the log scale, exponentiating the fitted values does not automatically give the arithmetic mean of \(y\) on the original scale.

16.5 Checking Linearity After Fitting the Model

After fitting the model, check that the transformations actually made the relationship between the predictors and the response more linear. We do this by looking at the residuals.

If the linearity assumption holds, the residuals in a residual plot should be scattered randomly around zero with no obvious pattern. A systematic pattern, such as a curve, means some nonlinearity remains, and more transformations or a different model may be needed.

Example 16.3  

ExampleChecking residual plots after transforming predictors

First, let’s look at the residuals versus the fitted values for the untransformed model.

# Obtain the residuals and fitted values from the fit
predictions_untransformed <- extract_fit_engine(fit_untransformed) |>
  augment()

predictions_untransformed |>
  ggplot(aes(x = .fitted, y = .resid)) +
  geom_point() +
  geom_smooth(se = FALSE, color = "blue") +
  geom_hline(yintercept = 0, linetype = "dashed", color = "red") +
  labs(x = "Fitted Values",
       y = "Residuals",
       title = "Residuals vs. Fitted Values") +
  theme_minimal()

This residual plot has a nonlinear pattern: the residuals tend to be above 0 at the low end, below 0 in the middle, and above 0 again at the high end. When there are only a few predictors, you can plot the residuals against each one to find which needs a transformation.

Here are those plots for the untransformed model.

library(gridExtra)

p1 <- predictions_untransformed |>
  ggplot(aes(x = disp, y = .resid)) +
  geom_point() +
  geom_smooth(se = FALSE, color = "blue") +
  geom_hline(yintercept = 0, linetype = "dashed", color = "red") +
  labs(x = "disp", y = "Residuals")

p2 <- predictions_untransformed |>
  ggplot(aes(x = hp, y = .resid)) +
  geom_point() +
  geom_smooth(se = FALSE, color = "blue") +
  geom_hline(yintercept = 0, linetype = "dashed", color = "red") +
  labs(x = "hp", y = "Residuals")

p3 <- predictions_untransformed |>
  ggplot(aes(x = drat, y = .resid)) +
  geom_point() +
  geom_smooth(se = FALSE, color = "blue") +
  geom_hline(yintercept = 0, linetype = "dashed", color = "red") +
  labs(x = "drat", y = "Residuals")

p4 <- predictions_untransformed |>
  ggplot(aes(x = wt, y = .resid)) +
  geom_point() +
  geom_smooth(se = FALSE, color = "blue") +
  geom_hline(yintercept = 0, linetype = "dashed", color = "red") +
  labs(x = "wt", y = "Residuals")

p5 <- predictions_untransformed |>
  ggplot(aes(x = qsec, y = .resid)) +
  geom_point() +
  geom_smooth(se = FALSE, color = "blue") +
  geom_hline(yintercept = 0, linetype = "dashed", color = "red") +
  labs(x = "qsec", y = "Residuals")

grid.arrange(p1, p2, p3, p4, p5, nrow = 3)

Taken together with the scatterplot matrix, these plots show that disp, hp, and wt are clearly nonlinear.

Now let’s look at the residual plot for the model with transformed variables.

# Obtain the residuals and fitted values from the fit
predictions_transformed <- extract_fit_engine(fit_transformed) |>
  augment()

predictions_transformed |>
  ggplot(aes(x = .fitted, y = .resid)) +
  geom_point() +
  geom_smooth(se = FALSE, color = "blue") +
  geom_hline(yintercept = 0, linetype = "dashed", color = "red") +
  labs(x = "Fitted Values",
       y = "Residuals",
       title = "Residuals vs. Fitted Values") +
  theme_minimal()

This residual plot has no obvious nonlinear pattern, so the transformations helped.

We can also put the two residual plots side by side, which makes it easier to see whether the transformation reduced the curve.

residual_comparison <- bind_rows(
  predictions_untransformed |>
    transmute(
      model = "Untransformed predictors",
      fitted = .fitted,
      residual = .resid
    ),
  predictions_transformed |>
    transmute(
      model = "Transformed predictors",
      fitted = .fitted,
      residual = .resid
    )
)

residual_comparison |>
  ggplot(aes(x = fitted, y = residual)) +
  geom_point() +
  geom_smooth(se = FALSE, color = "blue") +
  geom_hline(yintercept = 0, linetype = "dashed", color = "red") +
  facet_wrap(~model) +
  labs(
    x = "Fitted Values",
    y = "Residuals",
    title = "Residual plots before and after transformation"
  ) +
  theme_minimal()

Seen side by side, the point of the transformation is plain: we want residuals that look like random scatter around 0, not a systematic curve.

16.6 Recap

This chapter covered how to check the linearity assumption in multiple regression and what to do when it does not hold.

Idea Meaning
Linearity assumption The expected response should be approximately linear in the predictors included in the model.
Linear in the coefficients A regression model can include transformed predictors such as \(\log(x)\) or \(x^2\) and still be a linear regression model.
Scatterplot matrix A grid of pairwise plots used to look for curved relationships before fitting the model.
Discrete predictor A predictor with only a few possible values; it may need to be treated as categorical instead of quantitative.
Transformation A change to a predictor, such as using \(\log(x)\), \(\sqrt{x}\), or \(x^2\), to capture a nonlinear relationship.
Log-transformed predictor A predictor entered as \(\log(x)\); the coefficient is interpreted in terms of changes in \(\log(x)\) or approximate percentage changes in \(x\).
Transformed response A model that uses a response such as \(\log(y)\); fitted values and residuals are on the transformed scale.
Residual plot A plot used after fitting the model to check whether nonlinear patterns remain.
Residuals vs. fitted values A general diagnostic plot for checking whether residuals are randomly scattered around 0.
Residuals vs. predictors Diagnostic plots that can help identify which predictor may need a transformation.
Side-by-side residual plots A way to compare model diagnostics before and after transforming variables.
\(R^2\) caution A larger \(R^2\) may indicate better fit, but residual plots are needed to judge whether the linearity assumption is reasonable.

16.7 Check your understanding

NoteProblems
  1. What does the linearity assumption mean in a multiple regression model?

  2. Why can a model with \(\log(x)\) or \(x^2\) still be called a linear regression model?

  3. Why is a scatterplot matrix useful before fitting a multiple regression model?

  4. Why can predictors with only a few distinct values be hard to assess using scatterplots?

  5. Give one situation where a log transformation might be useful.

  6. Why should we check residual plots after transforming predictors?

  7. What pattern in a residual plot suggests that the linearity assumption may still be violated?

  8. Why should we avoid choosing transformations based only on \(R^2\)?

  9. In a model with \(E(y)=\beta_0+\beta_1\log(x)\), why should we avoid saying that \(\beta_1\) is the effect of a one-unit increase in \(x\)?

  10. What changes when we model \(\log(y)\) instead of \(y\)?

  11. Why is a side-by-side residual plot useful after transforming predictors?

  1. The mean response should follow the form the model specifies. In a model with untransformed predictors, this means the relationship between each predictor and the expected response should be close to a straight line after accounting for the other predictors.

  2. Linearity refers to the coefficients. A model such as \(E(y)=\beta_0+\beta_1\log(x)\) or \(E(y)=\beta_0+\beta_1x+\beta_2x^2\) is linear in the \(\beta\) coefficients, even though it may be curved as a function of \(x\).

  3. It shows possible nonlinear relationships early. Before fitting the model, we can scan the relationship between the response and each predictor and decide whether any transformations are needed.

  4. There are too few x-values to see a smooth pattern. With only a few distinct values, the points stack in vertical columns. It may be better to think about differences between groups or to treat the predictor as categorical.

  5. When the relationship bends and flattens out. A log transformation is often useful when increases in a positive predictor have a large effect at first and a smaller effect at larger values.

  6. A transformation is not guaranteed to work. After refitting the model, the residual plots show whether the curved pattern has really been reduced.

  7. A systematic curve. If the residuals tend to be positive in one region, negative in another, and positive again elsewhere, the model is missing curvature.

  8. \(R^2\) measures fit; it does not check assumptions. A transformed model may have a larger \(R^2\) and still show a nonlinear residual pattern. Residual diagnostics are needed to judge the form of the model.

  9. The predictor scale has changed. The coefficient \(\beta_1\) describes a one-unit increase in \(\log(x)\), not in \(x\). It is often more useful to describe the effect with percentage changes in \(x\).

  10. The model is now on the log scale of the response. The fitted values, residuals, and coefficient interpretations all refer to \(\log(y)\). To talk about predictions in the original units of \(y\), we have to back-transform carefully.

  11. It makes the improvement easier to see. Putting the plots next to each other lets us check whether the transformed model has less systematic curvature in its residuals than the untransformed model.