### Basic Plot with lm()

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# Convert cyl to factor mtcars$cyl <- as.factor(mtcars$cyl) # Basic Plot plot(mtcars$wt, mtcars$mpg, col = mtcars$cyl) # Linear model on all data abline(lm(mpg ~ wt, data = mtcars), lty = 2) # Linear Model on subset per cylinder (mtcars$cyl) 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") |

### ggplot2 with geom_smooth() method lm

1 2 3 4 5 6 7 |
# ggplot version library(ggplot2) 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, linetype = 2) |

In ggplot the lm() is being composed within the geom_smooth() element, and choosing “lm” (linear model).

Graphs in R / Basic Plot vs ggplot2