Home > Software design >  Optional facets as a function parameter
Optional facets as a function parameter

Time:10-02

How can you specify a facet parameter that is optional for facet_wrap(), without a weird additional label showing up?

For facet_wrap(), it works as expected when facets are specified. But if it's NULL, there is a weird (all) facet. Is it possible to get rid of that facet label without adding another parameter to the function?

foo_wrap <- function(x) {
  ggplot(mtcars)  
    aes(x = mpg, y = disp)  
    geom_point()  
    facet_wrap(vars({{ x }}))
}
foo_wrap (cyl) # cylinder facets
foo_wrap (NULL) # how to get rid of "(all)"?

foo_wrap (cyl) as expected foo_wrap (NULL) how to get rid of "(all)"?

How can you get rid of "(all)"?


Adding these examples as references in case people find this by searching

Below is an example function with optional facets for facet_grid(), where it works as expected:

foo_grid <- function(x) {
  ggplot(mtcars)  
    aes(x = mpg, y = disp)  
    geom_point()  
    facet_grid(rows=NULL, cols=vars({{ x }}))
}
foo_grid (cyl) # cylinder facets
foo_grid (NULL) # no facets, as expected

foo_grid (cyl) foo_grid (NULL). No facets, as expected.

Here is an example with hard coded rows facetting. Note that you need to call vars():

foo_grid_am <- function(x) {
  ggplot(mtcars)  
    aes(x = mpg, y = disp)  
    geom_point()  
    facet_grid(rows=vars(am), cols=vars({{ x }}))
}
foo_grid_am (cyl) # automatic-manual x cylinder facets

enter image description here

CodePudding user response:

One option would be to add a conditional facet layer where I use rlang::quo_is_null(rlang::enquo(x)) to check whether a faceting variable was provided or not:

Note: I made NULL the default.

library(ggplot2)
library(rlang)

foo_wrap <- function(x = NULL) {
  facet_layer <- if (!rlang::quo_is_null(rlang::enquo(x))) facet_wrap(vars({{ x }}))
  ggplot(mtcars)  
    aes(x = mpg, y = disp)  
    geom_point()  
    facet_layer
}
foo_wrap(cyl)

foo_wrap(NULL)

  • Related