R/multiplot.R

#' @title Allows for multiple plots (generated by ggplot2)
#' @export
multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
        library(grid)

        plots <- c(list(...), plotlist)

        numPlots = length(plots)

        if (is.null(layout)) {
                layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
                                 ncol = cols, nrow = ceiling(numPlots/cols))
        }

        if (numPlots==1) {
                print(plots[[1]])

        } else {
                # Set up the page
                grid.newpage()
                pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))

                # Make each plot, in the correct location
                for (i in 1:numPlots) {
                        # Get the i,j matrix positions of the regions that contain this subplot
                        matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))

                        print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
                                                        layout.pos.col = matchidx$col))
                }
        }
} #multiplot
elijahedmondson/HZE documentation built on May 16, 2019, 3 a.m.