rgraphicsggpubrupsetr

error when trying to join many upset plots in only one plot using grid.arrange in r


I'm trying to join many upset plots in only one image in r, I can generate the plots individually but when I use grid.arrange (from gridExtra) to join them like this:

grid.arrange(plot1, plot2)

it gives this error:

Error in gList(...): only 'grobs' allowed in 'gList'

I think this is happening because the plot is an 'upset' class, I tried to transform them into a ggplot using ggplotGrob() but it gives:

Error in UseMethod("ggplot_build"): no applicable method for 'ggplot_build' applied to an object of class upset"

Solution

  • upsetR makes a custom object that combines ggplot2 elements but is not itself a ggplot2 object. I'm curious if there's a better way, but the only approach I could get to work was to go

    upsetR object -> render image -> convert image to ggplot2 with magick -> combine using gridExtra or patchwork.

    # make upsetR object
    library(UpSetR)
    movies <- read.csv(system.file("extdata", "movies.csv", package = "UpSetR"), 
                       header = T, sep = ";")
    
    up <- upset(movies, sets = c("Action", "Adventure", "Comedy", "Drama", "Mystery", 
                                 "Thriller", "Romance", "War", "Western"), mb.ratio = c(0.55, 0.45), order.by = "freq")
    

    Then:

    # render as image
    up_img <- ragg::agg_png("up_ragg.png", width = 800, height = 500)
    print(up)
    dev.off()
    
    # put image in ggplot2 object
    library(magick)
    up_gg <- image_read("up_ragg.png") |> image_ggplot()
    
    # compose ggplot2 object(s) 
    library(patchwork)
    up_gg | up_gg
    

    enter image description here