use grid.arrange over multiple pages or marrangeGrob with a layout_matrix

ぃ、小莉子 提交于 2021-02-07 17:45:42

问题


i want to arrange plots with the following layout_matrix over multiple pages.

rep. e.g.

library(gridExtra)
library(ggplot2)

layout <- rbind(c(1,2,3,4),
                    c(1,2,3,4),
                    c(1,2,3,4),
                    c(5,5,5,5))
p <- list()
for(i in 1:15) {
    ifelse(i %% 5 > 0,
        p[[i]] <- ggplot(mtcars, aes(wt, mpg)) + geom_point() + ggtitle(paste("plot:",i)),
        p[[i]] <- tableGrob(mtcars[5:7,],rows = NULL)
    )
}

if i have only one page: (easy)

grid.arrange(grobs=p[1:5],layout_matrix=layout)

if i want multiple pages: (i loose all my pattern)

marrangeGrob(grobs=p,nrow=4,ncol=2)

pls help me with a general solution to have a layout_matrix on multiple pages.


回答1:


this seems to work,

marrangeGrob(grobs=p, nrow=1, ncol=5, layout_matrix=layout)

(admittedly by chance)

marrangeGrob is just a thin wrapper around a for loop and grid.arrange, so in case you need something more refined than this lucky workaround you should probably modify the code to your needs.




回答2:


Made my own function, that makes multiple grid.arrange files with layout and then marrangeGrob it into a multipage object.

m.grid.arrange <- function(p,topnames,layMat) {
    pdf(file = NULL) #invisible
    plotsPerPage <- length(unique(na.omit(c(layMat))))

    ml <- lapply(1:ceiling(length(p)/plotsPerPage), function(page_IND){
        ind <- (1+((page_IND-1)*plotsPerPage)):(page_IND*plotsPerPage)
        grid.arrange(grobs = p[ind], layout_matrix = layMat,top=topnames[page_IND])
    })

    return(marrangeGrob(grobs=ml,nrow=1,ncol=1,top=NULL))
    dev.off() #invisible
}

Then use:

ml <- m.grid.arrange(p=p,topnames=c("1 label","2 label","3 label"),layMat = layout)
ggsave("gridMeHard.pdf",width = 297, height =  210, units = "mm", ml)


来源:https://stackoverflow.com/questions/43491685/use-grid-arrange-over-multiple-pages-or-marrangegrob-with-a-layout-matrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!