如何将ggplot的AES参数传递给函数 [英] How to pass aes parameters of ggplot to function
问题描述
我正在使用gapminder并尝试编写一个简单的函数,以显示lifeExp
对gdpPercap
的图形.但是,当我将参数放入函数中时,参数不会被识别.
I am using gapminder and trying to write a simple function showing graphs of lifeExp
against gdpPercap
. However, when I put the arguments in the function, the arguments are not recognised.
我尝试了几个答案,但都没有结果.
I have tried several answers, with no results yet.
plotting <- function (input, xx, yy){
library (ggplot2)
library (gapminder)
ggplot (input, aes (xx, yy, size = pop, color = country)) + geom_point(show.legend = FALSE)
}
当我运行plotting (gampinder, lifeExp, gdpPercap)
用作输入xx
和yy
时,结果为
When I run plotting (gampinder, lifeExp, gdpPercap)
to be used as input, xx
and yy
, the result is
"FUN(X [[i]],...)中的错误:找不到对象'gdpPercap'""
"Error in FUN(X[[i]], ...) : object 'gdpPercap' not found"`
这是我被卡住的地方,gdpPercap
在这里,但是在代码中找不到!
你能帮忙吗?
This is where I am stuck and gdpPercap
is there but not found by the code!
Could you please help.
推荐答案
您需要使用卷曲的卷发)可以工作.另请参见此答案和整洁的评估部分.
You need to use tidy evaluation inside aes()
. Either .data[[ ]]
or {{ }}
(curly curly) would work. See also this answer and Tidy evaluation section in Hadley Wickham's Advanced R book.
library(gapminder)
library(rlang)
library(ggplot2)
plotting <- function(input, xx, yy) {
ggplot(input, aes(.data[[xx]], .data[[yy]], size = pop, color = country)) +
geom_point(show.legend = FALSE)
}
plotting(gapminder, "lifeExp", "gdpPercap")
plotting2 <- function(input, xx, yy) {
ggplot(input, aes({{xx}}, {{yy}}, size = pop, color = country)) +
geom_point(show.legend = FALSE)
}
plotting2(gapminder, lifeExp, gdpPercap)
由 reprex软件包(v0.3.0)创建于2019-11-09 sup>
Created on 2019-11-09 by the reprex package (v0.3.0)
这篇关于如何将ggplot的AES参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!