问题
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