Search code examples
rggplot2r-packagepatchwork

Best practice for use of Patchwork and ggplot2 library inside a package


What is the best practice when including ggplot2 and patchwork in a function that is part of a custom library? Usually I wouldn't load a complete library but only the required function, e.g. MLmetrics::RMSE(). But for ggplot I have a lot of ggplot functions, maybe around 10+ per plot. Of course it's not an impossible task to add a ggplot2:: in front of all of those, I was just wondering what is generally considered the best practice here. As for the patchwork library this is a bit different because I don't know how to call the specific plot assembly function. My code would look like this:

library(patchwork)
assembled_plot <- plot1/plot2/plot3

I think this doesn't work:

assembled_plot <- patchwork::plot1/plot2/plot3

Solution

  • Try using patchwork::wrap_plots(plot1, plot2, plot3, ncol = 1). 
    See documentation for formatting plot layout. 
    
    library(patchwork)
    library(ggplot2)
    
    plot1 <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
    plot2 <- ggplot(mtcars, aes(gear)) + geom_bar()
    plot3 <- ggplot(mtcars, aes(hp)) + geom_histogram(bins = 10)
    
    wrap_plots(plot1, plot2, plot3, ncol = 1)
    

    Created on 2023-10-20 with reprex v2.0.2