# Convert cyl to factor (don't need to change) mtcars$cyl <- as.factor(mtcars$cyl) # Example from base R (don't need to change) plot(mtcars$wt, mtcars$mpg, col = mtcars$cyl) abline(lm(mpg ~ wt, data = mtcars), lty = 2) lapply(mtcars$cyl, function(x) { abline(lm(mpg ~ wt, mtcars, subset = (cyl == x)), col = x) }) legend(x = 5, y = 33, legend = levels(mtcars$cyl), col = 1:3, pch = 1, bty = "n") # Plot 1: add geom_point() to this command to create a scatter plot ggplot(mtcars, aes(x = wt, y = mpg, col = cyl)) + geom_point() # Plot 2: include the lines of the linear models, per cyl ggplot(mtcars, aes(x = wt, y = mpg, col = cyl)) + geom_point() + geom_smooth(method = "lm", se = FALSE) # Plot 3: include a lm for the entire dataset in its whole ggplot(mtcars, aes(x = wt, y = mpg, col = cyl)) + geom_point() + geom_smooth(method = "lm", se = FALSE) + geom_smooth(aes(group = 1), method = "lm", se = FALSE, linety...
A Blog where I add my content