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
?