residualDensityPlot <- function(x){ stopifnot(class(x) == "lm") res <- resid(x) n <- length(res) res.sd <- sd(res) xx <- seq(-3, 3, length.out = n) x.den <- dnorm(xx, sd = res.sd) if (!require(ggplot2)){ plot(density(res), main = "Residual density plot") lines(xx, x.den, col = 'red') } else { dta <- data.frame(Residuals = res, X = xx, Density = x.den) p1 <- ggplot(dta, aes(x = Residuals)) + geom_density() + geom_line(aes(x = X, y = Density), colour = 'red') + theme_bw() + labs(y = "Density", title = "Residual density plot") print(p1) } }