thomasp85/patchwork

Make patchwork arithmetic operators extendable

ddsjoberg opened this issue · 0 comments

Hej hej @thomasp85 !

Thank you for the wonderful pkg. I use it often and it's super helpful 🥇

The first line of code in the arithmetic operator functions is if (should_autowrap(e2)) e2 <- wrap_elements(full = e2). The should_autowrap() function is simple, and makes it possible to apply the wrap_elements() function to gobs that require it.

should_autowrap <- function(x) {
  is.grob(x) || inherits(x, 'formula') || is.raster(x) || inherits(x, 'nativeRaster')
}

I maintain a ggplot-based package for creating survival curves (https://github.com/ddsjoberg/ggsurvfit), and I would love to be able to utilize the patchwork arithmetic operators. To make this work, I would need to perform some pre-processing for my class of plot. To make the patchwork arithmetic operators extendable, we could update this line if (should_autowrap(e2)) e2 <- wrap_elements(full = e2) to be a generic instead.

Here's what I had in mind:

#' @export
#' @rdname arithmetic_prep
arithmetic_prep <- function(x, ...) {
  UseMethod("arithmetic_prep")
}

#' @importFrom grid is.grob
#' @importFrom grDevices is.raster
#' @export
#' @rdname arithmetic_prep
arithmetic_prep.default <- function(x, ...) {
  # wrap input plot as needed
  if (is.grob(x) || inherits(x, 'formula') || is.raster(x) || inherits(x, 'nativeRaster')) {
    x <- wrap_elements(full = x)
  }
  x
}

By making this a generic function, other package authors could write their own methods to properly handle plots of other classes. If you're amenable to this, I can prepare a pull request. Thanks! 🐟