2

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?

Gmichael
  • 526
  • 1
  • 5
  • 16
  • have you thought about using RMarkdown instead of Rscripts? There you can easily mix up code, written text and images. Also you can edit the size of images with the arguments fig.height and fig.width – Edo Nov 05 '21 at 11:18
  • 1
    Are you looking for [this](https://stackoverflow.com/questions/39736655/plot-over-multiple-pages)? – Rui Barradas Nov 05 '21 at 11:20
  • @Edo: Yeah, but that is not quite what I wanted either. I actually do use RMarkdown just for the ability to have separate code chunks and take notes with a nicer formatting, good suggestions! – Gmichael Nov 05 '21 at 12:39
  • @Rui Barradas: not quite, as this only specifies the number of plots per page but not really their arrangement. – Gmichael Nov 05 '21 at 12:40

1 Answers1

2

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!

Gmichael
  • 526
  • 1
  • 5
  • 16