首页 > 解决方案 > ggplot2 以编程方式使用 aes_ 和 ..x../stat(x) 返回错误

问题描述

我想把这段代码:

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

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

谢谢。

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

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

标签: rggplot2

解决方案


如果要传入字符串,则需要使用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()继续工作。


推荐阅读