Understanding Simple Linear Regression

How car weight relates to fuel efficiency

What is linear regression?

Our example: the mtcars dataset

Weight (1,000 lb) MPG
Mazda RX4 2.620 21.0
Mazda RX4 Wag 2.875 21.0
Datsun 710 2.320 22.8
Hornet 4 Drive 3.215 21.4
Hornet Sportabout 3.440 18.7
Valiant 3.460 18.1

The regression equation

We estimate a straight-line relationship:

\[\widehat{y} = b_0 + b_1 x\]

The slope tells us how predicted MPG changes when weight increases by 1,000 pounds.

Scatterplot: weight vs. MPG

Fit the model in R

This code estimates the line using ordinary least squares.

fit <- lm(mpg ~ wt, data = mtcars)
round(coef(fit), 2)
## (Intercept)          wt 
##       37.29       -5.34
round(summary(fit)$r.squared, 3)
## [1] 0.753

The lm() function chooses the line that minimizes squared residuals.

A prediction with the fitted equation

From our sample, the fitted model is approximately:

\[\widehat{\mathrm{MPG}} = 37.29 - 5.34\,\mathrm{wt}\]

For a car weighing 3,000 pounds (wt = 3):

\[\widehat{\mathrm{MPG}} = 37.29 - 5.34(3) \approx 21.27\]

That is a predicted 21.3 miles per gallon, not an exact outcome.

Residuals and squared error

A residual is observed MPG minus predicted MPG:

\[e_i = y_i - \widehat{y}_i\]

Ordinary least squares minimizes:

\[\mathrm{SSE}=\sum_{i=1}^{n}(y_i-\widehat{y}_i)^2\]

Small residuals mean the model fits those observations more closely.

Residual plot (second ggplot)

Patterns in residuals can suggest that a straight-line model misses part of the relationship.

Interactive scatterplot: weight vs. MPG (Plotly)

Move your mouse over each dot to see the car model, weight, and fuel efficiency. You can also zoom in on the plot.

How well does the line explain MPG?

Takeaways

Data: built-in R dataset mtcars. Plots created with ggplot2 and Plotly.