patchwork icon indicating copy to clipboard operation
patchwork copied to clipboard

Extend `/` to allow for NULL on terms

Open DanChaltiel opened this issue 2 years ago • 0 comments

Hi Thomas,

In some algorithms, you need to set a plot to NULL.

For instance, if you are making plots in a loop, the current plot may have no sense for current parameters, in some limit-cases.

When adding ggplot layers with +, you can add NULL with no error, returning the original object. Would this be possible with patchwork also?

In my current task, I'm using patchwork to make a 2x2 plot table. For that, I have to make two 1x2 horizontal patches and then stack them using /. Either patch can be NULL.

I've been confronted with 2 cases:

  • the lower patch is NULL, yielding the error "Only knows how to fold ggplot objects together"
  • the upper patch is NULL, yielding the error "non-numeric argument to binary operator"

I'm not sure it is even doable (especially for the upper patch), but I'd think extending patchwork operators to allow for NULL would make sense, and it would also allow more flexibility in making algorithms.

Here is a reproducible example (simpler than my task):

library(ggplot2)
library(patchwork)
p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
patch <- p1+p1
p2 <- NULL

p1/p2 #works, returns only p1

patch/p2
#> Error: Only knows how to fold ggplot objects together
p2/p1
#> Error in e1 + e2 + plot_layout(ncol = 1): non-numeric argument to binary operator

Created on 2022-01-31 by the reprex package (v2.0.1)

DanChaltiel avatar Jan 31 '22 09:01 DanChaltiel