Unrelated
Unrelated

Reputation: 457

Adding points after the fact with ggplot2; user defined function

I believe the answer to this is that I cannot, but rather than give in utterly to depraved desperation, I will turn to this lovely community.

How can I add points (or any additional layer) to a ggplot after already plotting it? Generally I would save the plot to a variable and then just tack on + geom_point(...), but I am trying to include this in a function I am writing. I would like the function to make a new plot if plot=T, and add points to the existing plot if plot=F. I can do this with the 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 would like to run this function numerous times with different dataframes, resulting in a plot with 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 is that because functions in R don't have side-effects, I cannot access the plot made in the first command. I cannot save the plot to -> p, and then recall p in the later functions. At least, I don't think I can.

Upvotes: 1

Views: 216

Answers (1)

mts
mts

Reputation: 2190

have a ggplot plot object be returned from your function that you can feed to your next function call like 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 to assign the plot object returned to a variable:

cur.plot = ggfun(...)

Upvotes: 1

Related Questions