Home > OS >  plotting multiple ggplots in a several page pdf (one or several plots per page)
plotting multiple ggplots in a several page pdf (one or several plots per page)

Time:11-10

I am trying to generate a dashboard-like pdf (one page per species) that contains 3 different plots (per species) and I would like to save this output as a pdf. I have tried around with several ideas and the reprex was taken from this link and seems like it should apply to what I need in the long run. But I can't get it to work

making up some data and plots

df = data.frame(x = seq(1:30), y = rnorm(30), z = runif(30, 1, 10))

# Example plots
p.1 = ggplot(df, aes(x = x, y = y))  
  geom_point()
p.2 = ggplot(df, aes(x = x, y = z))  
  geom_point()
p.3 = ggplot(df, aes(x = y, y = z))  
  geom_point()
p.4 = ggplot(df, aes(x = y))  
  geom_histogram()

plots.list = list(p.1, p.2, p.3, p.4)  # Make a list of plots

My dumb solution works fine (i.e. looping over every species and then printing them into a pdf, then closing the pdf) except for the fact, that the plot then isn't using the entire space which looks dumb ;-).

pdf("myname.pdf", paper="a4r")
for (i in 1:length(plot.list)){print(plot.list[[i]])}
dev.off()

so here's the rest of the reprex

original version

# Generate plots to be saved to pdf, warning the argument to marrangeGrob
# have to be passed using do.call
# nrow (ncol) gives the number of rows (columns) of plots per page
# nrow and ncol have to be specificed inside a list
# Here, we'll obtain 2 plots in rows by page
plots = do.call(marrangeGrob, c(plots.list, list(nrow = 2, ncol = 1)))

# To save to file, here on A4 paper
ggsave("multipage_plot.pdf", plots, width = 21, height = 29.7, units = "cm")

Error in `$<-.data.frame`(`*tmp*`, "wrapvp", value = list(x = 0.5, y = 0.5,  : 
  replacement has 33 rows, data has 30

What am I missing?

CodePudding user response:

The solution was actually pretty simple in the end...

### create a layout matrix (nrow and ncol will do the trick too, but you have less options)

layout_mat<-rbind(c(1,1,2),
                  c(1,1,3))

plots<-marrangeGrob(plot.list, layout_matrix=layout_mat)


ggsave( filename="mypdf.pdf", plots, width=29.7, height=21, units="cm")

This version actually gives you full control over plot sizes and uses the entire page!

  • Related