2024-03-21

Linear Regression

  • Car Weight vs MPG (GGPlot)
  • Car Weight vs MPG (Plotly)
  • Car Horsepower vs MPG (GGPlot)

Car Weight vs MPG

ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point(aes(color = factor(cyl)), size = 3) +
geom_smooth(method = “lm”, color = “red”, se = FALSE) +
labs(title = “MPG vs Weight”,
x = “Weight [1000 lbs]”,
y = “Miles per Gallon”,
color = “Cylinders”)

Car Weight vs MPG

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

Car Weight vs MPG (Plotly)

p <- plot_ly(data = mtcars, x = ~wt, y = ~mpg, type = ‘scatter’, mode = ‘markers’,
marker = list(color = ~cyl),
text = ~paste(‘MPG:’, mpg, ‘Weight:’, wt, ‘Cylinders:’, cyl)) %>%
layout(title = ‘MPG vs Weight’,
xaxis = list(title = ‘Weight [1000 lbs]’),
yaxis = list(title = ‘Miles per Gallon’))

fit <- lm(mpg ~ wt, data = mtcars)

p <- p %>%
add_trace(x = ~wt, y = fitted(fit), mode = ‘lines’, type = ‘scatter’,
line = list(color = ‘red’, width = 2))

p

Car Weight vs MPG (Plotly)

## A marker object has been specified, but markers is not in the mode
## Adding markers to the mode...

Car Horsepower vs MPG

ggplot(mtcars, aes(x = hp, y = mpg)) +
geom_point(aes(color = factor(cyl)), size = 3) +
geom_smooth(method = “lm”, color = “red”, se = FALSE) +
labs(title = “MPG vs Horsepower”,
x = “Horsepower”,
y = “Miles per Gallon”,
color = “Cylinders”)

Car Horsepower vs MPG

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