繁体   English   中英

在包装器中将参数传递给ggplot

[英]Passing arguments to ggplot in a wrapper

我需要将ggplot2包装到另一个函数中,并希望能够以接受变量的相同方式解析变量,有人可以引导我朝正确的方向前进。

例如,让我们考虑以下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中该主题被称为“什么”。

这里的问题是xcol在数据对象中查找名为xcolcolumn 我建议切换到使用aes_string并使用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. 如果将图返回到函数外部,则不会在函数内部打印,而仅在函数外部打印。

这只是原始答案的补充,我确实知道这是一篇很老的文章,但只是补充:

原始答案提供了以下代码来执行包装程序:

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

在此, data作为字符串提供。 据我所知,这将无法正确执行。 仅将aes_string中的变量作为字符串提供,而将data对象作为对象传递给包装器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM