0

I saw that ggplot v3.0.0 now supports tidy evaluation. However, this apparently doesn't allow passing string objects as variable names to ggplot as I can do with dplyr.

y_var <- "drat"

This works:

mtcars %>% select(!!y_var)

This doesn't:

ggplot(mtcars) + geom_point(aes(x = disp, y = !!y_var))

Any idea what I'm doing wrong?

1 Answers1

2

You are unquoting, but it just yields a character vector.

This works:

mtcars %>% select(!!y_var)

Because this works:

mtcars %>% select('drat')

The ?select help actually states this as an exception:

# For convenience it also supports strings and character
# vectors. This is unlike other verbs where strings would be
# ambiguous.
vars <- c(var1 = "cyl", var2 ="am")
select(mtcars, !!vars)
rename(mtcars, !!vars)

It cannot be taken as a general working rule for tidy evaluation in the tidyverse.

Case in point, in ggplot character vectors in aes have a different meaning, you can't just give:

ggplot(mtcars) + geom_point(aes(x = disp, y = 'drat'))

Try for example:

ggplot(mtcars) + geom_point(aes(x = disp, y = !!as.name(y_var)))
Axeman
  • 32,068
  • 8
  • 81
  • 94