The code presents a sample data set, plots it, calls the linear model of regression, calculates predicted values and plots the residuals.
library(ggplot2) x=c(7,8,10,7,6,10,11,4) y=c(5,8,18,10,7,12,16,2) d = data.frame(x,y) knitr::kable(head(d)) plot(x,y,xlab = "x", ylab = "y", pch = 19, lwd=1.5, cex=1.5) fm <- lm(formula = y ~ x, data = d) d$predicted = predict(fm) d$residuals = residuals(fm) knitr::kable(head(d)) ggplot(d, aes(x = x, y = y)) + geom_smooth(method = "lm", se = FALSE, color = "red") + geom_segment(aes(xend = x, yend = predicted), alpha = .2) + geom_point() + geom_point(aes(y = predicted), shape = 1) + theme_bw()