7

I want to create a function that produces a ggplot plot and provide an optional argument for a facetting variable to facet_grid().

In particular, if possible, I want to incorporate the conditional logic inside facet_grid. I also want to use the tidy evaluation framework - so no formula strings!

However, all of my attempts have failed.

library(tidyverse)
iris <- iris %>% add_column(idx = rep(1:2, 75))

My first attempt fails, as facet_grid tries to find a variable named NULL (with backticks).

plot_iris <- function(df_in, facet_var = NULL){
  ggplot(df_in) +
    geom_point(aes(Sepal.Length, Sepal.Width)) +
    facet_grid(vars(!!enquo(facet_var)), vars(idx))
}

plot_iris(iris)

#> Error: At least one layer must contain all faceting variables: `NULL`.
#> * Plot is missing `NULL`
#> * Layer 1 is missing `NULL`

Running plot_iris(iris, Species), however, works as expected.

My second attempt also fails, but with a different error message.

plot_iris2 <- function(df_in, facet_var = NULL){
  facet_quo <- enquo(facet_var)

  ggplot(df_in) +
    geom_point(aes(Sepal.Length, Sepal.Width)) +
    facet_grid(rows = ifelse(identical(facet_quo, quo(NULL)), NULL,
                             vars(!!facet_quo)),
               cols = vars(idx))
}

plot_iris2(iris)

#> Error in ans[test & ok] <- rep(yes, length.out = length(ans))[test & ok] : 
#>   replacement has length zero
#> In addition: Warning message:
#> In rep(yes, length.out = length(ans)) :

Running this attempt with a non-NULL optional argument also fails:

plot_iris2(iris, Species)

#> Error: `rows` must be `NULL` or a `vars()` list if `cols` is a `vars()` list

My third attempt also fails, with the same error message but a different warning:

plot_iris3 <- function(df_in, facet_var = NULL){
  facet_quo <- enquo(facet_var)

  ggplot(df_in) +
    geom_point(aes(Sepal.Length, Sepal.Width)) +
    facet_grid(rows = vars(ifelse(identical(facet_quo, quo(NULL)), NULL,
                                  !!facet_quo)))
}

plot_iris3(iris)

#> Error in ans[test & ok] <- rep(yes, length.out = length(ans))[test & ok] : 
#>   replacement has length zero
#> In addition: Warning message:
#> In rep(yes, length.out = length(ans)) :
#>   'x' is NULL so the result will be NULL

Using a non-NULL optional argument returns a plot faceted by idx but not Species - there is a facet label for the single row, labelled by "1".

plot_iris3(iris, Species)

Are there any alternatives that use conditional logic inside a single facet_grid call, and that work when the optional argument is NULL?

Tung
  • 26,371
  • 7
  • 91
  • 115

2 Answers2

3

Maybe we should remove NULL elements from vars specs to make this easier. I have opened an issue: https://github.com/tidyverse/ggplot2/issues/2986

You can use rlang::quo_is_null() to check for quo(NULL). I would do it in a separate step for clarity.

plot_iris <- function(df_in, facet_var = NULL){
  facet_quo <- enquo(facet_var)

  if (rlang::quo_is_null(facet_quo)) {
    rows <- vars()
  } else {
    rows <- vars(!!facet_quo)
  }

  ggplot(df_in) +
    geom_point(aes(Sepal.Length, Sepal.Width)) +
    facet_grid(rows, vars(idx))
}
Lionel Henry
  • 6,652
  • 27
  • 33
1

I think you need your second approach. The key is that you'll need switch() to return NULL, not ifelse(). See the example here and discussion here.

plot_iris2 <- function(df_in, facet_var = NULL){
    facet_quo <- enquo(facet_var)

    ggplot(df_in) +
        geom_point(aes(Sepal.Length, Sepal.Width)) +
        facet_grid(rows = switch(identical(facet_quo, quo(NULL)) + 1, 
                                 vars(!!facet_quo),
                                 NULL),
                   cols = vars(idx))
}

plot_iris2(iris, facet_var = NULL)

enter image description here

plot_iris2(iris, facet_var = Species)

enter image description here

aosmith
  • 34,856
  • 9
  • 84
  • 118