The multiplot() Function
Winston Chang’s R Graphical Cookbook provides a useful function to simplify the creation of layouts with multiple plots. The function accepts ggplot objects as inputs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# Multiplot creates a layout structure for multiple plots in one # window. The function accepts ggplot objects via "..." or as a # list of objects. Use input "cols" to define the number of # columns in the plot layout. Alternatively, input "layout" to # define the row/col matrix of plot elements. If "layout" is # present, "cols" is ignored. For example, given a layout defined # by matrix(c(1,2,3,3), nrow=2, byrow=TRUE), then plot #1 goes in # the upper left, #2 goes in the upper right, and #3 will cross # the entire bottom row, utilizing both columns. multiplot <- function(..., plotlist = NULL, file, cols = 1, layout = NULL) { # launch the grid graphical system require(grid) # make a list from the "..." arguments and/or plotlist plots <- c(list(...), plotlist) numPlots = length(plots) # if layout = NULL, then use 'cols' to determine layout if (is.null(layout)) { # make the panel using ncol; nrow is calculated from ncol 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)))) # put each plot, in the correct location for (i in 1:numPlots) { # get the i,j matrix position of the 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)) } } } |
Use of the function is straightforward. First, multiplot() needs to be sourced and available in memory. Then the plots need to be coded with variable assignments to create plot objects. Finally, multiplot() is used to call the plot objects for placement in the predefined plot layout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Plot1: Stacked bar chart black outline p1 <- ggplot(mtcars, aes(x = factor(cyl), fill = factor(gear))) + geom_bar(color = "black") # Plot2: Stack bar chart manual fill p2 <- ggplot(mtcars, aes(x = factor(cyl), fill = factor(gear))) + geom_bar(color = "green") + scale_fill_manual(values=c("grey35", "grey50", "grey65")) # Plot3: Dodged bar short p3 <- ggplot(mtcars, aes(x = factor(cyl), fill = factor(gear))) + geom_bar(color = "black", position=position_dodge()) multiplot(p1, p2, p3, layout = matrix(c(1,2,3,3), nrow=2, byrow=TRUE)) |