Passing arguments to ggplot in a wrapper

前端 未结 2 712
野性不改
野性不改 2020-12-03 14:50

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

相关标签:
2条回答
  • 2020-12-03 15:26

    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, e.g.:

    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 e.g. 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.
    0 讨论(0)
  • 2020-12-03 15:26

    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.

    0 讨论(0)
提交回复
热议问题