How to make your Facet Wrap / Facet Grid ggplots span across multiple pages in PDF

while rendering from RMarkdown (Rmd)

This is going to be a very short post. It’s a problem I faced a few days back and after some DDGing, Github Issues scanning and some SOing - I found the answer. So, I thought to share it - for archival and also my future reference.

Problem

The problem here is when you use facet_grid() or facet_wrap() of ggplot inside an R chunk of an Rmd (Rmarkdown) file. The rendered PDF wouldn’t show those faceted multiple plots in multiple pages instead just embedded one on top another in the same page. That’s kind of annoying.

Solution

ggforce by Thomas Lin Pedersen. It was quite a shame on me that I hadn’t used this package before I faced this problem and I hope to explore this further in future. It seems to be an excellent addon to the ggplot2 ecosystem to fill in the missing holes.

Sample Code

First, we have to find the required number of pages, using n_pages()


 ggplot(df) + 
    geom_bar(aes(respondent,n, fill = answers), 
             stat = "identity") +
     scale_fill_manual(values = c("#fdb924","#00ccff")) +
  coord_flip() +
  theme_minimal() +
  labs(title = paste0("District-wise Question & Response") ,
       subtitle = "To identify Balance between responses") +
     facet_wrap_paginate(~district,
                     nrow = 1, 
                     ncol = 1, 
                     scales = "free") +
    theme( strip.text = element_text(size = 30)) -> p
    
    required_n_pages <- n_pages(p)
    

Once we have the required number of pages, we can use that in a for-loop (or you may use lapply or map) tp iterate the plotting with facet_wrap_paginate() instead of facet_wrap() adding the argument page = i where i is index of loop iteration denoting the current page in which the respective facet to be plotted.



for(i in 1:required_n_pages){

  ggplot(df) + 
    geom_bar(aes(respondent,n, fill = answers), 
             stat = "identity") +
     scale_fill_manual(values = c("#fdb924","#00ccff")) +
  coord_flip() +
  theme_minimal() +
  labs(title = paste0("District-wise Question & Response") ,
       subtitle = "To identify Balance between responses") +
     facet_wrap_paginate(~district,
                     nrow = 1, 
                     ncol = 1, 
                     scales = "free",
                     page = i) +
    theme( strip.text = element_text(size = 30)) -> p
  
  print(p)

Summary

These functions of ggforce should be quite handy if you are someone who prefers documenting the output of your Analysis with Rmarkdown (which is definitely one of the reasons why you should work on R).

 
comments powered by Disqus