r - 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_
也没有谈到这一点。
谢谢。
解决方案
如果要传入字符串,则需要使用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()
继续工作。
推荐阅读
- android - Dagger2 为 Android 中的 ViewModel 提供 ApplicationContext
- r - 在 Linux Mint LMDE4 上安装 R.4.0
- c - 是否有不应用作命令行参数的标志?
- javascript - 如何让文本突出显示跨多个元素工作?
- python-3.x - 在嵌套字典中添加新的(键,值)对 - python3
- javascript - ASP.NET Core - AJAX 数组看起来没有填充并传递给控制器
- google-sheets - Google表格中的堆积柱形图从多列中获取数据
- javascript - 当元素高度取决于该元素内的文本时为元素高度设置动画
- flutter - 单击按钮更改 TextField 中的文本格式
- java - 查找会员类别的 java 程序