Skip to content

Instantly share code, notes, and snippets.

@rubenarslan
Forked from masverba/ggprplots.R
Last active December 17, 2015 10:58
Show Gist options
  • Save rubenarslan/5598382 to your computer and use it in GitHub Desktop.
Save rubenarslan/5598382 to your computer and use it in GitHub Desktop.
new ggplot 2 syntax, return data object, print plot, fix wrong name for first argument
ggprplots <- function(fit, alpha=0.1) {
design <- model.matrix(fit)
# Skip the intercept term, if any.
m0 <- if (colnames(design)[1] == '(Intercept)') { 2 } else { 1 }
M <- ncol(design)
data <- do.call(rbind, lapply(m0:M, function(m) {
var <- colnames(design)[m]
value <- design[,m]
coef <- fit$coef[m]
data.frame(var=var, value=value, coef=coef, residual=fit$residuals)
}))
p <- ggplot(data, aes(x=value, y=coef*value + residual))
p <- p + facet_wrap(~ var, ncol=2, scale='free')
p <- p + geom_point(alpha=alpha)
p <- p + geom_smooth(method='lm', color='black', lty=2)
# p <- p + geom_smooth(color='green')
p <- p + labs(title="Component + Residual Plots")
p <- p + theme_bw()
print(p)
invisible(data)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment