### Basic Plot – linear model with abline()

#### Plot 1 – linear model all datapoints

1 2 3 4 5 6 7 8 9 |
# Build a linear model with lm() where wt (weight) relates to mpg (miles per gallon) carModel <- lm(mpg ~ wt, data = mtcars) # Basic plot ( factor the number of cylinders) mtcars$cyl <- as.factor(mtcars$cyl) plot(mtcars$wt, mtcars$mpg, col = mtcars$cyl) # Call abline() to overlay the basic plot with the linear model abline(carModel, lty = 2) |

#### Plot 2 – linear model per subset

Add library(graphics) to the code for the legend() function

1 2 3 4 5 6 7 8 9 |
# Calculate per cylinder a lineair model with lapply() plot(mtcars$wt, mtcars$mpg, col = mtcars$cyl) lapply(mtcars$cyl, function(x) { abline(lm(mpg ~ wt, mtcars, subset = (cyl == x)), col = x) }) # For better understanding add a legend. legend(x = 5, y = 33, legend = levels(mtcars$cyl), col = 1:3, pch = 1, bty = "n") |

Use of lapply –> take the vector mtcars$cyl and apply the abline() function. Within abline() the linear model is calculated per subset of cyl (cylinders)

Graphs in R / Basic Plot function – linear model