将参数传递给ggplot

gap*_*ppy 19 r ggplot2

想创建一个使用ggplot生成图形的函数.为简单起见,典型的图可以是

ggplot(car, aes(x=speed, y=dist)) + geom_point() 
Run Code Online (Sandbox Code Playgroud)

我想要创建的函数是类型

f <- function(DS, x, y) ggplot(DS, aes(x=x, y=y)) + geom_point()
Run Code Online (Sandbox Code Playgroud)

然而,这不起作用,因为x和y不是字符串.在以前的SO问题中已经注意到这个问题(例如,这个问题),但在我看来,没有提供令人满意的答案.如何修改上面的函数使其适用于任意数据帧?

Gre*_*ret 38

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

f <- function(DS, x, y) {    
  ggplot(DS, aes_string(x = x, y = y)) + geom_point()  
}
Run Code Online (Sandbox Code Playgroud)

然后将函数调用为:

f(cars, "speed", "dist")
Run Code Online (Sandbox Code Playgroud)

但是,似乎你不想要那个?您能举例说明为什么需要不同的功能吗?是因为您不希望在同一数据框中包含参数吗?


Tri*_*ou. 7

我认为以下类型的代码可能只构建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
Run Code Online (Sandbox Code Playgroud)

然而,这似乎是复杂的方法.

  • 更好的方法是跳过转换为文本,只构建aes组件:`xName < - substitute(x); yName < - substitute(y); eval(替代(aes(x,y),list(x = xName,y = yName)))` (6认同)