Why does this aes tidyeval example from ggplot doc

2019-08-03 18:54发布

问题:

I am trying to write a wrapper function around ggplot, but I keep coming up with an error when unquoting a function parameter:

Error in !enquo(x) : invalid argument type

I have re-read the dplyr programming guide, and thought I understood it and have used tidyeval previously in implementing functions using dplyr verbs eg group_by and mutate. This brought me to the ggplot documentation for aes where I found this example:

scatter_by <- function(data, x, y) {
  ggplot(data) + geom_point(aes(!!enquo(x), !!enquo(y)))
}
scatter_by(mtcars, disp, drat)

When I run this in RStudio 1.1.383, I get the error:

Error in !enquo(x) : invalid argument type

I am using ggplot2 version 2.2.1 and dplyr 0.7.4

I have tried using rlang::UQ(enquo(x)) instead of !! but I still get an error.

回答1:

You can use aes_string and quo_name.

scatter_by <- function(data, x, y) {

  ggplot(data) + 
    geom_point(aes_string(x= quo_name(enquo(x)), y=quo_name(enquo(y))))

}
scatter_by(mtcars, disp, drat)

Here is quite substantial disscusion about this problem: How to use dplyr's enquo and quo_name in a function with tidyr and ggplot2



标签: r ggplot2 dplyr