I have a list of plots that I would like to pass to patchwork::wrap_plots:
library(tidyverse)
library(patchwork)
# plots with na
dummy_plot <- ggplot() + theme_void()
p <- ggplot(mtcars, aes(mpg, cyl)) + geom_point()
plots <- list(p, p, NA)
patchwork::wrap_plots(plots)
Gives error:
Error: Only know how to add ggplots and/or grobs
I would therefore like to preprocess my list of plots to replace any NA with the blank dummy plot from above.
Desired outcome:
plots <- list(p, p, NA)
... some magic r code here to replace NA with dummy plot ...
# now plots looks like this
plots <- list(p, p, dummy_plot)
I can now pass to wrap plots without error:
How can I replace instances of NA in a list to be my dummy plot?
You can loop over plots
and check if the elements are identical
to NA
. If so, replace with dummy_plot
plots[sapply(plots, function(x) identical(x, NA))] <- list(dummy_plot)
patchwork::wrap_plots(plots)
# grid.rect(gp = gpar(fill = NA))
Result