2/8/2025

data("Orange")
library(ggplot2)
tree_data <- data.frame(
  Age=Orange$age,
  Circumference=Orange$circumference
)
data("faithful")

Simple Linear Regression

  • Used to find patterns of scatter plots
  • Simple linear regression uses only 1 line with 1 independent variable

Observing the Data to be Used

head(Orange)
##   Tree  age circumference
## 1    1  118            30
## 2    1  484            58
## 3    1  664            87
## 4    1 1004           115
## 5    1 1231           120
## 6    1 1372           142

This data looks at the circumference at breast height of a series of Orange trees, and looks at how they grow as days go by.

Graph Example

Suppose we have a scatterplot where there appears to be a trend with the data…
Orange Tree Age (days) vs. Circumference (millimeters)

Orange Tree Age (days) vs. Circumference (millimeters)

Linear Regression Equations

  • \(a=\) y-intercept
  • \(a=\overline{y}-bx\)
  • \(b=\) slope
  • \(b=\frac{S_{xy}}{S_{xx}}\)
  • \(S_{xy}=\sum(x_i-\overline{x})(y_i-\overline{y})\)
  • \(S_{xx}=\sum(x_i-x)^2\)
  • \(n=\)Amount of Data Points

Linear Regression on Graph

Let’s add the linear regression line to the graph

## `geom_smooth()` using formula = 'y ~ x'
Orange Tree Age (days) vs. Circumference (millimeters)

Orange Tree Age (days) vs. Circumference (millimeters)

Explaining the Linear Regression Equation

  • By taking the average of all the points on the graph, we can determine a line of best fit for the points (linear regression).
  • In our Orange Tree example, this gets us the equation \(y=0.1068x+17.3997\).

Linear Regression in R (Plotly)

  • Using base plotly packages, you can easily implement a line of best fit on your scatterplot using the “lm” function.
  • The lm function is used to find a linear model from a data frame.
  • After the lm function is used, you can use abline to add that line of best fit to your plot.
  • The “faithful” dataset talks about the wait times between eruptions at the Old Faithful geyser, and how long the eruptions last.

Linear Regression Plotly Graph

plot(faithful$waiting,faithful$eruptions, main="Old Faithful Eruptions", xlab="Wait Time (in minutes)", ylab="Eruption Length (in minutes")
linear_model <- lm(faithful$eruptions ~ faithful$waiting)
abline(linear_model, col="forestgreen")

Linear Regression in R (Ggplot2)

  • On ggplot2, a scatterplot with a linear regression line can be done all in one line.
  • Using ggplot, geom_point and geom_line a quick plot could be made.

Linear Regression Ggplot Graph

ggplot(data=faithful, mapping=aes(x=waiting,y=eruptions))+
  geom_point()+geom_smooth(method="lm",se=FALSE)
## `geom_smooth()` using formula = 'y ~ x'

Sources