r - Adding points after the fact with ggplot2; user defined function -


i believe answer cannot, rather give in utterly depraved desperation, turn lovely community.

how can add points (or additional layer) ggplot after plotting it? save plot variable , tack on + geom_point(...), trying include in function writing. function make new plot if plot=t, , add points existing plot if plot=f. can basic plotting package:

fun <- function(df,plot=true,...) { ... if (!plot) { points(dydx~time.dec,data=df2,col=col) } else { plot(dydx~time.dec,data=df2,...) }} 

i run function numerous times different dataframes, resulting in plot multiple series plotted.

for example,

fun(df.a,plot=t) fun(df.b,plot=f) fun(df.c,plot=f) fun(df.d,plot=f) 

the problem because functions in r don't have side-effects, cannot access plot made in first command. cannot save plot -> p, , recall p in later functions. @ least, don't think can.

have ggplot plot object returned function can feed next function call this:

ggfun = function(df, oldplot, plot=t){   ...   if(plot){     outplot = ggplot(df, ...) + geom_point(df, ...)   }else{     outplot = oldplot + geom_point(data=df, ...)   }   print(outplot)   return(outplot) } 

remember assign plot object returned variable:

cur.plot = ggfun(...) 

Comments