簡體   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