I want to use a function to modify a plot based on the parameters passed. However, I'm not sure what format I should convert the list of modifications parameters into, to be used as parameters within the respective 'geom'.
library(ggplot2)
data <- tibble(a = 1:3, b = 11:13)
p <- ggplot(data)
plot_modify <- function(p, geom = "", ...){
modifications <- list(...)
if(geom == "point"){
p <- p geom_point(aes(x = a, y = b), modifications)
}
return(p)
}
plot_modify(p, "point", alpha=0.1, size = 0.3)
P.s. I intend to validate the list of parameters based on each 'geom' later on.
CodePudding user response:
After you capture the values in the ellipse, you are responsible for passing them along. In order to inject those values into subsequent calls, you'll need to build the call using something like do.call
using base R methods
plot_modify <- function(p, geom = "", ...){
modifications <- list(...)
if(geom == "point"){
p <- p do.call("geom_point", c(list(aes(x = a, y = b)), modifications))
}
return(p)
}
But do note that list(...)
will force evaluation of all your parameters which is slightly different than how the function behaves normally.
If you wanted to use more of an rlang
strategy you can do
plot_modify <- function(p, geom = "", ...){
modifications <- list(...)
if(geom == "point"){
p <- p rlang::inject(geom_point(aes(x = a, y = b), !!!modifications))
}
return(p)
}