Side-by-side plots with ggplot2

后端 未结 13 2627
轮回少年
轮回少年 2020-11-22 02:06

I would like to place two plots side by side using the ggplot2 package, i.e. do the equivalent of par(mfrow=c(1,2)).

For example, I would like to have t

13条回答
  •  执念已碎
    2020-11-22 02:39

    You can use the following multiplot function from Winston Chang's R cookbook

    multiplot(plot1, plot2, cols=2)
    

    multiplot <- function(..., plotlist=NULL, cols) {
        require(grid)
    
        # Make a list from the ... arguments and plotlist
        plots <- c(list(...), plotlist)
    
        numPlots = length(plots)
    
        # Make the panel
        plotCols = cols                          # Number of columns of plots
        plotRows = ceiling(numPlots/plotCols) # Number of rows needed, calculated from # of cols
    
        # Set up the page
        grid.newpage()
        pushViewport(viewport(layout = grid.layout(plotRows, plotCols)))
        vplayout <- function(x, y)
            viewport(layout.pos.row = x, layout.pos.col = y)
    
        # Make each plot, in the correct location
        for (i in 1:numPlots) {
            curRow = ceiling(i/plotCols)
            curCol = (i-1) %% plotCols + 1
            print(plots[[i]], vp = vplayout(curRow, curCol ))
        }
    
    }
    

提交回复
热议问题