【问题标题】:How to use string variables with tidy evaluation in ggplot v3.0.0? [duplicate]如何在 ggplot v3.0.0 中使用具有整洁评估的字符串变量? [复制]
【发布时间】:2018-09-05 15:50:18
【问题描述】:

我看到 ggplot v3.0.0 现在支持 tidy 评估。但是,这显然不允许将字符串对象作为变量名传递给 ggplot,就像我对 dplyr 所做的那样。

y_var <- "drat"

这行得通:

mtcars %>% select(!!y_var)

这不是:

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

知道我做错了什么吗?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    你没有引用,但它只是产生一个字符向量。

    这行得通:

    mtcars %>% select(!!y_var)
    

    因为这行得通:

    mtcars %>% select('drat')
    

    ?select 帮助实际上将此声明为异常:

    # 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)
    

    不能作为tidyverse中tidy评估的一般工作规则。

    例如,aes 中的 ggplot 字符向量有不同的含义,你不能只给出:

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

    试一试:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-06
      • 2011-07-02
      • 2017-12-27
      • 1970-01-01
      • 1970-01-01
      • 2011-03-30
      • 2013-12-10
      相关资源
      最近更新 更多