I am trying to create some functions based on ggplot to create custom plots. The creation of functions is very easy and straight forward, but I cannot figure out the way to share information between the functions to help in the plot creation.
Here is a simplified example
library(ggplot2)
my_ggplot <- function(dat, x, y, cols) {
ggplot(dat, aes(!!sym(x), !!sym(y))) +
geom_point(color = cols$dots)
}
my_geom <- function(dat, x, cols) {
xmean <- mean(dat[[x]], na.rm = T)
exit <- list(
geom_smooth(aes(color = cols$line), method = "loess", se = FALSE),
geom_vline(xintercept = xmean, color = cols$line)
)
}
mycolors <- list(dots = "blue", line = "red")
Here, my_plot creates the base plot and, if I want to, I can add couple of lines to it using my_geom. I need a way to control the colors so, I have defined an S3 class object, which in this example is simply the list mycolors.
So, when passing all the parameters to each function, the result is perfectly fine:
my_ggplot(mpg, 'displ', 'hwy', mycolors) +
my_geom(mpg, "displ", mycolors)
But I want to be able to "inherit" values from my_ggplot to my_geom so that the following code could work:
my_ggplot(mpg, 'displ', 'hwy', mycolors) +
my_geom()
But still, my_geom keeps certain level of independence in case I want to use it with different ggplot() functions. Especially important for me is to be able to pass the dataset between functions, in the example I calculate the mean and use it later in geom_vline to keep it simple, but in practice I need to do some data wrangling and calculations before I can pass the values to the geom.

One possible approach to remove the dependency on the
datand thexargument would be to usestat_summaryto compute the mean of the variable mapped on thexaes and to add thevlinesimilar to my answer on this post. Second, for the colors one option would be to map on thecoloraes and to set the color palette viascale_color_manual. This way the colors would be available inmy_geomtoo. Of course does this only work when you create your plot viamy_ggplot. Not perfect.Finally here is an example of applying
my_geomto aggplotcreated from scratch: