How can I arrange an arbitrary number of ggplots using grid.arrange?

后端 未结 3 1887
死守一世寂寞
死守一世寂寞 2020-11-28 01:31

This is cross-posted on the ggplot2 google group

My situation is that I\'m working on a function that outputs an arbitrary number of plots

3条回答
  •  遥遥无期
    2020-11-28 02:28

    Try this,

    require(ggplot2)
    require(gridExtra)
    plots <- lapply(1:11, function(.x) qplot(1:10,rnorm(10), main=paste("plot",.x)))
    
    params <- list(nrow=2, ncol=2)
    
    n <- with(params, nrow*ncol)
    ## add one page if division is not complete
    pages <- length(plots) %/% n + as.logical(length(plots) %% n)
    
    groups <- split(seq_along(plots), 
      gl(pages, n, length(plots)))
    
    pl <-
      lapply(names(groups), function(g)
             {
               do.call(arrangeGrob, c(plots[groups[[g]]], params, 
                                      list(main=paste("page", g, "of", pages))))
             })
    
    class(pl) <- c("arrangelist", "ggplot", class(pl))
    print.arrangelist = function(x, ...) lapply(x, function(.x) {
      if(dev.interactive()) dev.new() else grid.newpage()
       grid.draw(.x)
       }, ...)
    
    ## interactive use; open new devices
    pl
    
    ## non-interactive use, multipage pdf
    ggsave("multipage.pdf", pl)
    

提交回复
热议问题