【问题标题】:ggplot2 programmically using aes_ and ..x../stat(x) return errorggplot2 以编程方式使用 aes_ 和 ..x../stat(x) 返回错误
【发布时间】:2020-04-01 17:01:31
【问题描述】:

我想转这个代码:

library(ggplot2)
ggplot(mtcars, aes(x = cyl, fill = stat(x))) +
  geom_histogram(binwidth = 1) +
  scale_fill_gradient(low = 'blue', high = 'yellow')

变成这样的函数:

library(ggplot2)
plotfn <- function (data, col_interest) {
  g <- ggplot(data, aes_(x = col_interest, fill = stat(x))) +
       geom_histogram(binwidth = 1) +
       scale_fill_gradient(low = 'blue', high = 'yellow')
  return(g)
}

plotfn(mtcars, "cyl")

我想为此创建一个函数并自动化我的代码以减少错误和行数,但我不知道 aes_ 的等效 ..x..stat(x)aes_ 上的指南和注释也没有谈到这一点。

谢谢。

参考stat():https://ggplot2.tidyverse.org/reference/stat.html

参考aes_:https://ggplot2.tidyverse.org/reference/aes_.html

【问题讨论】:

  • 请注意,aes_() 已被软性弃用。建议您继续使用 tidy-evaluation。你到底想通过在这里使用aes_ 来完成什么?
  • 您能说明一下您的用例吗?例如,也许您正试图将它放在一个函数中,然后将 x 变量传递给它如果是这种情况,您不需要aes_()。相反,您可以将aes()ggplot(mtcars, aes(x = {{ var }}, fill = stat(x)) ) 之类的整洁评估一起使用。然后你可以将cyl 传递给该函数。
  • @MrFlick 我正在为 8 个数据集重用相同的 ggplot2 代码,每个数据集使用相似的 ggplot 参数和函数(aes、geom_histogram、scale_fill_gradient、guides、theme)。我想为此创建一个函数并仅传入参数并返回一个 ggplot2 函数,以便我可以在此基础上进行构建。
  • 你是如何传入参数的?字符串?符号?正如@aosmith 指出的那样,您可能希望使用标准aes() 和新的包含语法来弹出变量。
  • 你能举例说明你将如何使用你在函数中提出的建议吗?我想现在我们只是在猜测你可能会用这个做什么。如果您展示您尝试创建的函数类型以及传递给它的值类型,您可能会得到更具体的建议。

标签: r ggplot2


【解决方案1】:

如果要传入字符串,则需要使用 rlang::sym!!(bang-bang)运算符

library(ggplot2)
plotfn <- function (data, col_interest) {
  g <- ggplot(data, aes(x = !!rlang::sym(col_interest), fill = stat(x))) +
    geom_histogram(binwidth = 1) +
    scale_fill_gradient(low = 'blue', high = 'yellow')
  return(g)
}

或者您可以使用特殊的.data 变量

plotfn <- function (data, col_interest) {
  g <- ggplot(data, aes(x = .data[[col_interest]], fill = stat(x))) +
    geom_histogram(binwidth = 1) +
    scale_fill_gradient(low = 'blue', high = 'yellow')
  return(g)
}

plotfn(mtcars, "cyl")

符号你只需使用{{}}

plotfn <- function (data, col_interest) {
  g <- ggplot(data, aes(x = {{col_interest}}, fill = stat(x))) +
    geom_histogram(binwidth = 1) +
    scale_fill_gradient(low = 'blue', high = 'yellow')
  return(g)
}

plotfn(mtcars, cyl)

这样,您将 aes() 的其余部分保持不变,stat() 继续工作。

【讨论】:

  • 您可能还提到了字符串的代名词.dataaes(x = .data[[col_interest]], fill = stat(x))
  • 好点@aosmith。我总是忘记那个,因为它对我来说看起来并不“好”。我已经更新了答案(尽管此时肯定有一个重复)
猜你喜欢
  • 2012-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多