【问题标题】:Tidyeval splice operator !!! fails with ggplot's aesTidyeval 拼接运算符!!! ggplot 的 aes 失败
【发布时间】:2019-04-23 16:49:49
【问题描述】:

The article discussing tidy evaluation in ggplot2 给人的印象是aes() 现在支持拟定。但是,我无法让它与 unquote-splice 运算符 !!! 一起使用。

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

(也许不足为奇)如果将美学映射移动到几何图形,也会发生同样的事情:

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

我是否遗漏了一些明显的东西?

【问题讨论】:

    标签: r ggplot2 tidyeval


    【解决方案1】:

    这是因为aes() 接受x 和y 参数,而!!! 仅在点内有效。我们将在未来尝试解决这个特殊问题。在此期间,您需要单独取消引用 x 和 y,或使用以下解决方法:

    aes2 <- function(...) {
      eval(expr(aes(!!!enquos(...))))
    }
    
    ggplot(mtcars, aes2(!!!v)) + geom_point()
    

    【讨论】:

    • 谢谢你,@lionel。
    【解决方案2】:

    作为一种解决方法 (first described by Hadley),以下代码使用空参数来跳过 aes 中的命名参数。这样,!!! 在 aes 内部工作:

    ggplot(mtcars) + geom_point(aes(, , !!! v))
    

    【讨论】:

      【解决方案3】:

      随着新的 rlang 更新,我认为您可以使用 {{}} 在 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 )
      

      我面临的唯一问题是使用 facet_wrap。我已经尝试过 quo_name,但这似乎不适用于 facet_wrap(~ quo_name(by))。否则,其他一切都正常。虽然这作为一种解决方法也有帮助,但我更喜欢坚持使用 facet_grid 和 varsworkaround。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-09
        • 1970-01-01
        • 2023-02-02
        • 2021-03-22
        • 1970-01-01
        • 2013-06-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多