【问题标题】:Alternative way to call a variable in ggplot2 (R)? [duplicate]在 ggplot2 (R) 中调用变量的替代方法? [复制]
【发布时间】:2021-02-15 17:12:16
【问题描述】:

有没有办法使用 ggplot2 从列表中调用变量?我正在尝试为同事创建一个交互式/通用脚本。

这就是我通常的绘图方式:

ggplot(df, aes(x = variable1)) + geom_histogram()

但是对于这个脚本,我想要这样的东西:

plot_this_variable <- "variable1"
ggplot(df, aes(x = plot_this_variable)) + geom_histogram()

这可能吗?如果有,怎么做?

编辑:

解决方法,使用 aes_string() 代替 aes()。

【问题讨论】:

  • 您可以使用 aes_string(),它采用字符串作为变量名而不是纯表达式。

标签: r ggplot2


【解决方案1】:

aes_string 已被弃用,您可以将sym!! 一起使用或使用.data 代词。

library(ggplot2)
#Using `sym`
ggplot(df, aes(x = !!sym(plot_this_variable)) + geom_histogram()

#Using .data
ggplot(df, aes(x = .data[[plot_this_variable]])) + geom_histogram()

不过,.data 现在是首选方式。

【讨论】:

    猜你喜欢
    • 2020-10-18
    • 2016-04-23
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多