【问题标题】:Passing arguments to ggplot in a wrapper在包装器中将参数传递给 ggplot
【发布时间】:2013-04-24 02:21:41
【问题描述】:

我需要将 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 中被“称为”什么。

【问题讨论】:

标签: r function ggplot2


【解决方案1】:

这里的问题是 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. 如果将绘图返回到函数外部,我不会在函数内部打印它,而是在函数外部打印。

【讨论】:

  • 谢谢,不知道有 aes_string 选项,但没有办法传递“名称”,我的意思是,ggplot2 函数如何知道参数的含义。
  • 有一些方法可以获取对象的名称,ggplot2 在 aes 的底层使用它,但是对于像这样传递参数,aes_string 更容易。
  • 嗨,这是非常有用的答案。我正在使用这个解决方案来开发直方图的包装器。但是,在我的代码中,我编写了用于生成中线geom_vline(aes(xintercept = mean(histogramVariable)), colour = 'red' 的代码。将histogramVariable 作为data$histogramVariable 传递到这里有多巧妙?
【解决方案2】:

这只是对原始答案的补充,我知道这是一篇相当老的帖子,但只是作为补充:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-05
    • 2019-09-22
    • 2017-07-13
    • 1970-01-01
    • 2014-11-17
    • 2018-08-05
    • 1970-01-01
    相关资源
    最近更新 更多