Search code examples
rggplot2r-markdownpandoc

drawing multiple plots, 2 per page using ggplot


I have a list of dataframes and I would like to print them all in a .RMarkdown document with 2 per page. However, I have not been able to find a source for doing this. Is it possible to do this via a for loop?

What I would like to achieve is something with the following idea:


listOfDataframes <- list(df1, df2, df3, ..., dfn)

for(i in 1:){
   plot <- ggplot(listOfDataframes[i], aes(x = aData, y = bData)) + geom_point(color = "steelblue", shape = 19)

 #if two plots have been ploted break to a new page.

}

Is this possible to achieve with ggplot in rmarkdown? I need to print out a PDF document.


Solution

  • If you just need to output plots with two per page, then I would use gridExtra as was suggested above. You could do something like this if you were to put your ggplot objects into a list.

    library(ggplot2)
    library(shinipsum) # Just used to create random ggplot objects.
    library(purrr)
    library(gridExtra)
    
    # Create some random ggplot objects.
    ggplot_objects <- list(random_ggplot("line"), random_ggplot("line"))
    
    # Create a list of names for the plots.
    ggplot_objects_names <- c("This is Graph 1", "This is Graph 2")
    
    # Use map2 to pass the ggplot objects and the list of names to the the plot titles, so that you can change them.
    ggplot_objects_new <-
      purrr::map2(
        .x = ggplot_objects,
        .y = ggplot_objects_names,
        .f = function(x, y) {
          x + ggtitle(y)
        }
      )
    
    # Arrange each ggplot object to be 2 per page. Use marrangeGrob so that you can save two ggplot objects per page.
    ggplot_arranged <-
      gridExtra::marrangeGrob(ggplot_objects_new, nrow = 2, ncol = 1)
    
    # Save as one pdf. Use scale here in order for the multi-plots to fit on each page.
    ggsave("ggplot_arranged.pdf",
           ggplot_arranged, scale = 1.5)
    

    If you have a list of dataframes that you are wanting to create ggplots for, then you can use purrr::map to do that. You could do something like this:

    purrr::map(df_list, function(x) {
      ggplot(data = x, aes(x = aData, y = bData)) +
        geom_point(color = "steelblue", shape = 19)
    })