12

I'm using the ggforce package to generate facetted plots over several pages:

library(ggforce) 

for(i in 1:6){
  ggplot(diamonds) +
    geom_point(aes(carat, price), alpha = 0.1) +
    facet_wrap_paginate(~cut:clarity, ncol = 2, nrow = 2, page = i)

  ggsave(paste0("~/diamonds_", i, ".pdf"))
}

which is generating the expected 6 PDF files:
enter image description here

What is the easiest way have the output in one single pdf with 6 pages?

I understand this can be done with the reports and pdftools packages, but I'm wondering if there's a more direct way to accomplish this. I'd expect ggforce to provide the functionality for the output to be single-paged, but it looks like that's not the case?

Dan
  • 1,711
  • 2
  • 24
  • 39

2 Answers2

27

You don't even need to use ggsave you can put all these plots into one pdf by:

pdf("~/diamonds_all.pdf")
for(i in 1:6){
  print(ggplot(diamonds) +
          geom_point(aes(carat, price), alpha = 0.1) +
          facet_wrap_paginate(~cut:clarity, ncol = 2, nrow = 2, page = i))

}
dev.off()
Mike H.
  • 13,960
  • 2
  • 29
  • 39
  • Woah! I didn't know I could do that with `pdf()`, that's a simple and elegant solution. Thank you, @MikeH. I believe you meant `ggsave` on your answer, BTW – Dan Jan 31 '18 at 14:25
11

I'm facing a similar question and here's my solution, basically an extension of Mike H. answer.

Typically you want to plot all the pages and you don't know beforehand how many pages you have, also, you may want to print on standard A4 size paper. So:

library(ggforce) 

gg <- ggplot(diamonds) + 
    geom_point(aes(carat, price)) +
    facet_wrap_paginate(~cut:clarity, ncol = 2, nrow = 2, page = 1)
n <- n_pages(gg)

pdf('diamonds.pdf', paper= 'A4', w= 210/25.4, 297/25.4)
for(i in 1:n){
    print(gg + facet_wrap_paginate(~cut:clarity, ncol = 2, nrow = 2, page = i))
}
dev.off()

Code should be self-explanatory. The ugly thing is that you have to repeat facet_wrap_paginate(...) twice or wrap it into a dedicated function. I'd like to hear of a better solution...

dariober
  • 8,240
  • 3
  • 30
  • 47