简体   繁体   中英

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.

Lets say for example, we consider the below 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. 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.

The problem here is that ggplot looks for a column named xcol in the data object. I would recommend to switch to using aes_string and passing the column names you want to map using a string, eg:

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:

  1. Personal preference, I use a lot of spaces around eg x = 1 , for me this greatly improves the readability. Without spaces the code looks like a big block.
  2. If you return the plot to outside the function, I would not print it inside the function, but just outside the function.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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