gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:02:37 25 4
gpt4 key购买 nike

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

最佳答案

这里的问题是 ggplot 寻找 column命名 xcol在数据对象中。我建议改用 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)
}

一些备注:
  • 个人喜好,我在周围使用了很多空格,例如x = 1 ,对我来说这大大提高了可读性。没有空格,代码看起来像一个大块。
  • 如果您将绘图返回到函数外部,我不会在函数内部打印它,而是在函数外部打印它。
  • 关于r - 在包装器中将参数传递给 ggplot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16295234/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com