Search code examples
rlistggplot2subset

Remove blank ggplots from a list of ggplots


I have a list of ggplots below. Some are blank using theme_void(), while others display data. How can I selectively filter out or remove the blank ggplots and make a new list containing only the plots containing data? I am not looking for something like ggplot_list[c(-1, -4)] because I have very long lists of ggplots with many blank plots.

library(ggplot2)

 p1 <- ggplot(mtcars)+
  theme_void()
 
 p2 <- ggplot(mtcars)+
   geom_point(aes(x = mpg, y = wt))
 
 p3 <- ggplot(mtcars)+
   geom_point(aes(x = mpg, y = cyl, ))
 
 p4 <- ggplot(mtcars)+
   theme_void()
 
 ggplot_list <- list(p1, p2, p3, p4)

Solution

  • I assume your question is not about the theme but about (data) layers. Given this list:

    # naming the elements so we can easily follow the result    
    ggplot_list <- list(p1 = p1, p2 = p2, p3 = p3, p4 = p4)
    

    You could filter ggplot_list and keep only those entries for which the layers element is not an empty list.

    tmp <- Filter(\(i) !identical(i$layers, list()), ggplot_list)
    

    Result

    tmp
    #
    #$p2
    #
    #$p3
    

    Examples:

    p1$layers
    # list()
    
    p2$layers
    #[[1]]
    #mapping: x = ~mpg, y = ~wt 
    #geom_point: na.rm = FALSE
    #stat_identity: na.rm = FALSE
    #position_identity