3

The article discussing tidy evaluation in ggplot2 gives the impression that aes() now supports quasiquoation. However, I'm having problems getting it to work with the unquote-splice operator !!!.

library( ggplot2 )

## Predefine the mapping of symbols to aesthetics
v <- rlang::exprs( x=wt, y=mpg )

## Symbol-by-symbol unquoting works without problems
ggplot( mtcars, aes(!!v$x, !!v$y) ) + geom_point()

## But unquote splicing doesn't...
ggplot( mtcars, aes(!!!v) ) + geom_point()
# Error: Can't use `!!!` at top level
# Call `rlang::last_error()` to see a backtrace

(Perhaps unsurprisingly) The same thing happens if the aesthetic mapping is moved to the geom:

ggplot( mtcars ) + geom_point( aes(!!v$x, !!v$y) )   # works
ggplot( mtcars ) + geom_point( aes(!!!v) )           # doesn't

Am I missing something obvious?

Artem Sokolov
  • 13,196
  • 4
  • 43
  • 74

3 Answers3

7

That's because aes() takes x and y arguments and !!! only works within dots. We'll try to solve this particular problem in the future. In the interim you'll need to unquote x and y individually, or use the following workaround:

aes2 <- function(...) {
  eval(expr(aes(!!!enquos(...))))
}

ggplot(mtcars, aes2(!!!v)) + geom_point()
Lionel Henry
  • 6,652
  • 27
  • 33
1

As a workaround (first described by Hadley), the following code uses empty arguments to skip the named parameters in aes. That way, !!! works inside aes:

ggplot(mtcars) + geom_point(aes(, , !!! v))
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
0

with the new rlang update, i think you can use {{}} to work inside ggplot

polo<- function(x,y, data, by) {

  ggplot({{data}}, aes(x = {{x}}, y = {{y}})) + 
    geom_point()  + 
    facet_grid(rows = vars({{by}}))
}
polo(data = mtcars, x = cyl, y = mpg, by = vs )

The only problem I face is with using facet_wrap. I have tried quo_name but that seems to not work with facet_wrap(~ quo_name(by)). Otherwise everything else just works. Although this as a workaround can also help, but I prefer to stick with facet_grid and varsworkaround.