An Explanation of Linear Regression

Parker Flint

2026-10-19

Definition

Example

Example (contd)

Without a linear regression, it’s hard to tell if there is a clear correlation:

ggplot(mtcars, aes(x = wt, y = mpg))+ geom_point(col="red")+
  labs(title = "Fuel Efficiency vs Car Weight",
       x = "Car Weight (1000 lbs)",y = "Fuel Efficiency (mpg)")

Example (contd)

With a linear regression, the correlation is more clear.

ggplot(mtcars, aes(x = wt, y = mpg))+ geom_point(col="red")+
  labs(title = "Fuel Efficiency vs Car Weight",
       x = "Car Weight (1000 lbs)",
       y = "Fuel Efficiency (mpg)") + geom_smooth(method="lm")
## `geom_smooth()` using formula = 'y ~ x'

Calculating Linear Regression

Calculating Linear Regression in R

example = lm(mpg ~ wt,data = mtcars)
q = plot_ly(data = mtcars, x= ~wt, y= ~mpg,
        type="scatter",mode="markers", name = "data")
q = q%>%
  add_lines(x=mtcars$wt, y=fitted(example), name= "Linear Regression")
q

Understanding the Graphs

For the data-set example used here:

coef(lm(mpg ~ wt, data=mtcars))
## (Intercept)          wt 
##   37.285126   -5.344472

The slope is: -5.344, making the regression equation: \[y = 37.285 - 5.344x\] - For every 1000 lbs, the predicted fuel efficiency decreases by 5.344 mpg - At 0 lbs, the predicted fuel efficiency is 37.285 (though this isn’t practically possible)

Caveats

\[ e = y-y_g\] Where ‘e’ is the error for a given prediction, ‘y’ is the observed value, and ‘y_g’ is the predicted value from regression