Arranging multiple plot in different layouts on multiple pages

68 Views Asked by At

I'm using R and trying to create a pdf file in the following structure:

Given two lists of plots - reportMain, reportExtra, I would like to create one pdf file, where at the first pages appears reportMain's plots, 4 plots in page in 2X2 matrix. and at the last files appears reportExtra's plots, each plot on its own page.

I don't know the length of these plots lists. Also, one of my plots is actually a tableGrob object, so I use as.grob() for all the other plots before I entered them into the list.

for example, this is how my data looks:

#perpare table
a <- c("pens","papers","computers", "chairs", "tables")
b <- c("5","300","40","20","15")
dat_table <- as.data.frame(a,b)
tt <- ttheme_minimal(core = list(bg_params = list(fill = blues9[1:4], col=NA),
fg_params = list(fontface=3)), colhead = list(fg_params=list(col="navyblue", fontface=4L)))

#table
tbl <- tableGrob(dat_table, theme= tt)
#plot(tbl)

#prepare data for plots
x <- c(1,2,3,4,5,6,7,8,9,10)
y <- c(23,7,5,35,38,22,64,14,44,31)
z <- c(2,5,7,4,7,5,9,4,3,6)
w <- c(2,5,1,0,7,5,0,4,3,7)
data <- as.data.frame("x" =x,"y"=y,"z"=z,"w"=w)

# plot 1
p1 <- ggplot(data,aes(x,y)) + geom_point(color = "blue")

# plot 2
p2 <- ggplot(data,aes(x,z)) + geom_point(color = "red")

# plot 3
p3 <- ggplot(data,aes(y,z)) + geom_point(color = "green")

# plot 4
p4 <- ggplot(data,aes(y,w)) + geom_point(color = "yellow")

# plot 5
p5 <- ggplot(data,aes(x,w)) + geom_point(color = "pink")

# plot 6   
p6 <- ggplot(data,aes(w,z)) + geom_point(color = "orange")

reportMain = list()
reportMain$p1 <- p1
reportMain$p2 <- p2
reportMain$p3 <- p3
reportMain$p4 <- p4
reportMain$q <- asgrob(tbl)

reportExtra = list()
reportExtra$p4 <- p4
reportExtra$p5 <- p5
reportExtra$p6 <- p6

I'm getting reportMain and reportExtra as input, and want to create one pdf file as I decribed above.

The solution I find is to create two different pdf files using

marrangeGrob(reportMain, top = name, nrow = rowsInPage, ncol = colsInPage) and ggsave(), and then combined them with qpdf::pdf_combine()

But I'm looking for solutions that don't require temp files. thank you!

0

There are 0 best solutions below