[英]Passing arguments to ggplot in a wrapper
I need to wrap ggplot2 into another function, and want to be able to parse variables in the same manner that they are accepted, can someone steer me in the correct direction. 我需要将ggplot2包装到另一个函数中,并希望能够以接受变量的相同方式解析变量,有人可以引导我朝正确的方向前进。
Lets say for example, we consider the below MWE. 例如,让我们考虑以下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)
}
Dummy Data: 虚拟数据:
##Demo Data
myData <- data.frame(x=0,y=0,c="Color Series")
Existing Usage which executes without hassle: 现有用法可以轻松执行:
##Example of Original Function Usage, which executes as expected
plot <- ggplot(data=myData,aes(x=x,y=y,color=c)) + geom_point()
print(plot)
Objective usage syntax: 目标用法语法:
##Example of Intended Usage, which Throws Error ----- "object 'xcol' not found"
mywrapper(data=myData,xcol=x,ycol=y,colorVar=c)
The above gives an example of the 'original' usage by the ggplot2 package, and, how I would like to wrap it up in another function. 上面给出了ggplot2软件包“原始”用法的示例,以及我想如何将其包装在另一个函数中。 The wrapper however, throws an error.
但是,包装器将引发错误。
I am sure this applies to many other applications, and it has probably been answered a thousand times, however, I am not sure what this subject is 'called' within R. 我确信这适用于许多其他应用程序,它可能已经被回答了上千次,但是,我不确定在R中该主题被称为“什么”。
The problem here is that ggplot looks for a column
named xcol
in the data object. 这里的问题是
xcol
在数据对象中查找名为xcol
的column
。 I would recommend to switch to using aes_string
and passing the column names you want to map using a string, eg: 我建议切换到使用
aes_string
并使用aes_string
传递要映射的列名,例如:
mywrapper(data = myData, xcol = "x", ycol = "y", colorVar = "c")
And modify your wrapper accordingly: 然后相应地修改包装器:
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)
}
Some remarks: 一些说明:
x = 1
, for me this greatly improves the readability. x = 1
周围使用了很多空格,这对我来说大大提高了可读性。 Without spaces the code looks like a big block. This is just an addition to the original answer, and I do know that this is quite an old post, but just as an addition: 这只是原始答案的补充,我确实知道这是一篇很老的文章,但只是补充:
The original answer provides the following code to execute the wrapper: 原始答案提供了以下代码来执行包装程序:
mywrapper(data = "myData", xcol = "x", ycol = "y", colorVar = "c")
Here, data
is provided as a character string. 在此,
data
作为字符串提供。 To my knowledge this will not execute correctly. 据我所知,这将无法正确执行。 Only the variables within the
aes_string
are provided as character strings, while the data
object is passed to the wrapper as an object. 仅将
aes_string
中的变量作为字符串提供,而将data
对象作为对象传递给包装器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.