I am working on a wrapper function for ggplot that looks somewhat like this
plot_wrapper <- function(df, group_by, color_by=NULL) {
ggplot(df, aes(x=.data[[groupby]], y=value) +
geom_quasirandom()
}
Now I would like to conditionally pass color_by
to geom_quasirandom(aes(color=.data[[color_by]]))
if color_by
is not NULL. How can I do that without duplicating code and without using the deprecated aes_string
?
I tried
color_args = ifelse(is.null(color_by), list(), list(color=.data[[groupby]]))
ggplot(df, aes(x=.data[[groupby]], y=value) +
geom_quasirandom(aes(!!!color_args)
but it fails with
Error in `geom_quasirandom()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 2nd layer.
Caused by error:
! object '.data[[color_by]]' not found
Similarly
geom_quasirandom(aes(color = !!ifelse(is.null(color_by), NULL, .data[[color_by]])))
fails with
Error in `plot_comparison()`:
! Can't subset `.data` outside of a data mask context.
Run `rlang::last_trace()` to see where the error occurred.
I suspect it requires the right combination of quoting and unquoting but I haven’t found it yet.