R 将参数传递给ggplot

R 将参数传递给ggplot,r,ggplot2,R,Ggplot2,要创建一个函数,该函数使用ggplot生成图形。为了简单起见,典型的图形可能是 ggplot(car, aes(x=speed, y=dist)) + geom_point() 我想创建的函数是 f <- function(DS, x, y) ggplot(DS, aes(x=x, y=y)) + geom_point() f一种解决方案是将x和y作为数据帧DS中列的字符串名传递 f <- function(DS, x, y) { ggplot(DS, aes_st

要创建一个函数,该函数使用ggplot生成图形。为了简单起见,典型的图形可能是

ggplot(car, aes(x=speed, y=dist)) + geom_point() 
我想创建的函数是

f <- function(DS, x, y) ggplot(DS, aes(x=x, y=y)) + geom_point()

f一种解决方案是将x和y作为数据帧DS中列的字符串名传递

f <- function(DS, x, y) {    
  ggplot(DS, aes_string(x = x, y = y)) + geom_point()  
}

然而,你似乎不想这样?您能否举例说明为什么需要不同的功能?这是因为您不希望参数位于同一数据帧中吗?

我认为可能存在以下类型的代码,它们只构建
aes
组件

require(ggplot2)

DS <- data.frame(speed=rnorm(10), dist=rnorm(10))

f <- function(DS, x, y, geom, opts=NULL) {
  aes <- eval(substitute(aes(x, y),
    list(x = substitute(x), y = substitute(y))))
  p <- ggplot(DS, aes) + geom + opts
}

p <- f(DS, speed, dist, geom_point())
p
require(ggplot2)

DS另一个选项是使用do.call。以下是工作代码的一行复制粘贴:

gg <- gg + geom_rect( do.call(aes, args=list(xmin=xValues-0.5, xmax=xValues+0.5, ymin=yValues, ymax=rep(Inf, length(yValues))) ), alpha=0.2, fill=colors )

gg我能想到的一种方法是使用
match.call()
获取传递给自定义绘图函数的参数/参数所包含的变量名,然后对它们使用
eval()
。这样,如果您不喜欢,就可以避免将它们作为引号传递给自定义函数

library(ggplot2)

fun <- function(df, x, y) {
    arg <- match.call()
    ggplot(df, aes(x = eval(arg$x), y = eval(arg$y))) + geom_point()
} 
fun(mpg, cty, hwy) # no need to pass the variables (column names) as quoted / as strings
库(ggplot2)

有趣又漂亮。我根本不知道这个选项的存在。谢谢。没问题,很高兴我能帮上忙。谢谢你接受我的解决方案。知道了就忘了。多亏了你的回答才重新发现了它+1为什么DS不需要“”,而x和y需要“”?你能解释一下吗?太好了!直到我看到这篇文章,我才知道选项aes_string。更好的方法是跳过文本转换,只构建aes组件:
xName thanky you@hadley。我觉得这个方法比我的简单。谢谢。这对我帮助很大!你能解释一下match.call的论点吗?嗨,路易斯。Hadley Wickham在他的书的一节中写到了
match.call()
的一些用法。也许这有助于了解更多细节。
library(ggplot2)

fun <- function(df, x, y) {
    arg <- match.call()
    ggplot(df, aes(x = eval(arg$x), y = eval(arg$y))) + geom_point()
} 
fun(mpg, cty, hwy) # no need to pass the variables (column names) as quoted / as strings