1 # Multiple plot function
3 # ggplot objects can be passed in ..., or to plotlist (as a list of ggplot objects)
4 # - cols: Number of columns in layout
5 # - layout: A matrix specifying the layout. If present, 'cols' is ignored.
7 # If the layout is something like matrix(c(1,2,3,3), nrow=2, byrow=TRUE),
8 # then plot 1 will go in the upper left, 2 will go in the upper right, and
9 # 3 will go all the way across the bottom.
11 multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
14 # Make a list from the ... arguments and plotlist
15 plots <- c(list(...), plotlist)
17 numPlots = length(plots)
19 # If layout is NULL, then use 'cols' to determine layout
20 if (is.null(layout)) {
22 # ncol: Number of columns of plots
23 # nrow: Number of rows needed, calculated from # of cols
24 layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
25 ncol = cols, nrow = ceiling(numPlots/cols))
34 pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))
36 # Make each plot, in the correct location
37 for (i in 1:numPlots) {
38 # Get the i,j matrix positions of the regions that contain this subplot
39 matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))
41 print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
42 layout.pos.col = matchidx$col))
47 # From https://sejohnston.com/2012/08/09/a-quick-and-easy-function-to-plot-lm-results-in-r/
48 ggplotRegression <- function (fit) {
52 ggplot(fit$model, aes_string(x = names(fit$model)[2], y = names(fit$model)[1])) +
54 geom_smooth(method = "lm", col = "red") +
55 labs(title = paste("Adj R2 = ",signif(summary(fit)$adj.r.squared, 5),
56 "Intercept =",signif(fit$coef[[1]],5 ),
57 " Slope =",signif(fit$coef[[2]], 5),
58 " P =",signif(summary(fit)$coef[2,4], 5))) +
59 theme(plot.title = element_text(size=12))