1

Although this might be a duplicate, I would like to know the solution for my question. I tried to run the code from question Multiple graphs over multiple pages using ggplot but I don't know how the data is strucured and therefore could not run it. I want to plot multiple graphs and print them on multiple pages in a pdf. I tried it with mtcars:

library(ggplot2)
library(reshape2)
library(plyr)
library(gridExtra)

mtcars2 = melt(mtcars, id.vars='mpg')
mtcars2$group[mtcars2$variable  %in% c("cyl", "disp", "hp", "drat")] <- "A"
mtcars2$group[mtcars2$variable  %in% c("wt", "qsec", "vs", "am")] <- "B"
mtcars2$group[mtcars2$variable  %in% c("gear", "cyl")] <- "C"


p = ggplot(mtcars2) +
  geom_jitter(aes(value,mpg, colour=variable)) + 
  geom_smooth(aes(value,mpg, colour=variable), method="lm", se=FALSE) +
  scale_y_continuous(limits = c(0, 60))+
  labs(x = "Percentage cover (%)", y = "Number of individuals (N)")

plots = dlply(mtcars2, "group", `%+%`, e1 = p)
ml = do.call(marrangeGrob, c(plots, list(nrow=2, ncol=2)))
ggsave("multipage.pdf", ml)

produces error Error in (function (grobs, ncol, nrow, ..., top = quote(paste("page", : argument "grobs" is missing, with no default. How do I get this script running?

aosmith
  • 34,856
  • 9
  • 84
  • 118
yPennylane
  • 760
  • 1
  • 9
  • 27

2 Answers2

2

instead of do.call() which was required in a previous version of gridExtra, try marrangeGrob(grobs = plots, nrow=2, ncol=2)

baptiste
  • 75,767
  • 19
  • 198
  • 294
1

You can use the ggplus package:

https://github.com/guiastrennec/ggplus

I particularly find it easier than messing with the ArrageGrobs/gridExtra; it automagically puts the facets in several pages for you.

Since you saved your initial plot as "p", your code would then look like:

# Plot on multiple pages
facet_multiple(plot = p, 
           facets = 'group', #**** 
           ncol = 2, 
           nrow = 1)
Dan
  • 1,711
  • 2
  • 24
  • 39
  • Thank you. It works. If I use `pdf("your_path/testforum.pdf", width=18, height=9) ml = facet_multiple(plot = p, facets = 'variable', #**** ncol = 2, nrow = 2) ggsave("multipage.pdf", ml) dev.off()` then it shows empty plots on the last pdf page, where there are only 2 plots left (instead of 4). Do you know, why this happens? – yPennylane Jul 24 '17 at 11:17
  • Glad to hear it works! Check how many plots you are expecting to see, before anything. Let me know if I can contribute with anything more to make this answer marked as accepted. – Dan Jul 24 '17 at 11:41
  • I would like to have a pdf with multiple pages with the graphs plotted in 2 columns and 2 rows, an when there are only 2 graphs left, then plotted only 2 on the last page. – yPennylane Jul 24 '17 at 12:18
  • Is there also a parameter `scales = free`? I have very different ranges of the data... – yPennylane Jul 24 '17 at 13:29