2013-04-30 23 views
10

我需要将ggplot2包装到另一个函数中,并且希望能够以接受它们的相同方式解析变量,是否有人能够让我以正确的方向操作。例如:将参数传递给包装器中的ggplot

例如,我们考虑下面的MWE。

#Load Required libraries. 
library(ggplot2) 

##My Wrapper Function. 
mywrapper <- function(data,xcol,ycol,colorVar){ 
    writeLines("This is my wrapper") 
    plot <- ggplot(data=data,aes(x=xcol,y=ycol,color=colorVar)) + geom_point() 
    print(plot) 
    return(plot) 
} 

伪数据:

##Demo Data 
myData <- data.frame(x=0,y=0,c="Color Series") 

现有用法,其执行没有麻烦:

##Example of Original Function Usage, which executes as expected 
plot <- ggplot(data=myData,aes(x=x,y=y,color=c)) + geom_point() 
print(plot) 

目的使用语法:

##Example of Intended Usage, which Throws Error ----- "object 'xcol' not found" 
mywrapper(data=myData,xcol=x,ycol=y,colorVar=c) 

上面给出了ggplot2包的'原始'用法的示例,以及我想如何将它包装到另一个函数中。但是,包装引发错误。

我相信这也适用于许多其他应用程序,它可能已经回答了一千遍,但是,我不知道这个问题是“所谓的”内R.

回答

9

这里的问题是,ggplot在数据对象中查找名为xcolcolumn。我会建议改用aes_string并通过列名,你想用一个字符串,如来图:

mywrapper(data = "myData", xcol = "x", ycol = "y", colorVar = "c") 

,并相应修改您的包装:

mywrapper <- function(data,xcol,ycol,colorVar){ 
    writeLines("This is my wrapper") 
    plot <- ggplot(data=data, aes_string(x = xcol, y = ycol, color = colorVar)) + geom_point() 
    print(plot) 
    return(plot) 
} 

一些言论:

  1. 个人喜好,我在周围使用了很多空间x = 1,对我来说这大大提高了可读性。没有空格的代码看起来像一个大块。
  2. 如果您将绘图返回到函数外部,我不会在函数内部打印它,而是在函数外部打印。
+0

谢谢,不知道是否有aes_string选项,但没有办法传递'name',我的意思是,ggplot2函数怎么知道参数的含义。 – 2013-04-30 09:02:30

+0

有一些获取对象名称的方法,ggplot2使用'aes'中的引用,但为了传递这样的参数,'aes_string'要容易得多。 – 2013-04-30 09:05:44

+0

嗨,这是非常有用的答案。我正在使用此解决方案来开发直方图的包装。然而,在我的代码中,我已经生成了中间行'geom_vline(aes(xintercept = mean(histogramVariable)),color ='red''的代码。'histogramVariable'作为'data $ histogramVariable'巧妙地传递给了这个吗? – Konrad 2015-11-11 12:22:18