2024-02-04

Homework 3

Throughout this assignment, I will be exploring Linear Regression and how to apply it to different plot libraries.

I will also be exploring LaTeX and how to visualize math text using it.

Slides containing all of the code for each of the plots will be added near the end of the presentation.

Plotting with the Plotly Library

3D Plotly Graph w/o Regression

ggplot2 Linear Regression

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

ggplot2 Linear Regression with Multiple regression lines

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

Linear Regression of the Plotly Graph (LaTeX)

Linear Regression:

\[ \hat{\beta_1} = \frac{\sum_{i=1}^n(x_i-\bar{x})(y_i-\bar{y})}{\sum_{i=1}^n(x_i-\bar{x})^2} \\ \hat{\beta _0} = \bar{y}-\hat{\beta_1}\bar{x} \\ y=\beta_0+\beta_1*x \]

With variable names replaced:

\[ \hat{\beta_1} = \frac{\sum_{i=1}^{32}(disp_i-\bar{disp})(mpg_i-\bar{mpg})}{\sum_{i=1}^{32}(disp_i-\bar{disp})^2} \\ \hat{\beta _0} = \bar{mpg}-\hat{\beta_1}\bar{disp} \\ mpg=\beta_0+\beta_1*disp \]

Linear Regression of the ggplot2 Graphs (LaTeX)

Both graphs used these functions as the base of their regressions:

\[ \hat{\beta_1} = \frac{\sum_{i=1}^{32}(disp_i-\bar{disp})(hp_i-\bar{hp})}{\sum_{i=1}^{32}(disp_i-\bar{disp})^2} \\ \hat{\beta _0} = \bar{hp}-\hat{\beta_1}\bar{disp} \\ hp=\beta_0+\beta_1*disp \]

For the multiple line regressions, 3 separate instances were done on each group of engines, one for 4, 6 and 8 cylinder engines.

R code used for each plot:

Plotly 2d:

p <- plot_ly(data=mtcars, x=~disp, y=~mpg, 
             type='scatter', mode='markers', name="MPG")
p <- p %>% layout(paper_bgcolor='transparent')

linReg <- lm(mpg~disp, data=mtcars)
xRange <- seq(min(mtcars$disp), max(mtcars$disp), length.out=100)
xRange <- matrix(xRange, nrow=100, ncol=1)

xDF <- data.frame(xRange)
colnames(xDF) <- c('disp')
yDF <- linReg %>% predict(xDF)
linDF <- data.frame(xDF,yDF)

p <- p %>% add_trace(data=linDF, x=~disp, y=~yDF,
                     name="Linear Regression", mode='lines')
p

Cont.

Plotly 3d:

p <- plot_ly(data=mtcars, x=~disp, y=~cyl,z=~mpg, name="MPG", 
             width=720, height=550)
p <- p %>% add_markers()
p <- p %>% layout(scene=list(xaxis=list(title='Displacement in^3'), 
                             yaxis=list(title='Cylinders'), 
                             zaxis=list(title='MPG')), paper_bgcolor='transparent')
p

ggplot2 Single Regression:

ggplot(data=mtcars, aes(x=disp, y=hp)) + geom_point() + geom_smooth(method=lm, se=FALSE)

ggplot2 Multi Regression:

mtcars$cyl <- as.factor(mtcars$cyl)
ggplot(data=mtcars, aes(x=disp, y=hp, shape=cyl, color=cyl)) + geom_point() + 
      geom_smooth(method=lm, se=FALSE, fullrange=TRUE)