2026-10-20

Linear Regression

Linear Regression is the process of finding a “best fit” line for a data set. This line may not directly pass through any data points, but it can be used as a somewhat reliable tool to predict values in the data by going to the corresponding \(x\) or \(y\) value and seeing where that point falls on the best fit line.

Benefits of Linear Regression

  • Easy to compute, can often be done on a calculator and does not need much computing power

  • Allows extrapolation based on the best fit line to imagine what other data points might look like

  • Can be done with any amount of data points, however more points will produce a more accurate best fit line

-Generates an easy to follow line using the formula \(y=mx+b\) where m is the slope, and b is the y-intercept.

Code for Plot_ly plot

#This code generates a plotly plot showing the best fit line between city 
#mileage and cylinders in the engine as a scatter plot.
mod = lm(mpg$cty~mpg$cyl)
x = mpg$cyl
y = mpg$cty

xax = list(
  title = "Cylinders"
)

yax = list(
  title = "MPG (City)"
)

plot_ly(x = x, y = y, type = "scatter", mode = "markers", name = "data") %>%
  add_lines(x = x, y = fitted(mod), name = "fitted") %>%
  layout(xaxis = xax, yaxis = yax)

Slide with Plotly Plot

Slide 6

ggplot(data = mpg, aes(x = cyl, y = hwy)) + geom_smooth()
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'

Slide 7

## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'

Slide 8

Interestingly, the best fit line between the number of cylinders a car has in its engine and the miles per gallon it gets stays almost the exact same shape whether talking about the city or the highway.