1

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.

3
  • 1
    why don't you pass the plot variable to your function which then either returns the appended plot or a new plot depending on plot=T/F ? Commented Jul 10, 2015 at 8:10
  • Maybe! How do I pass the plot variable to my function if I am defining the plot variable in a function? Is there a way for a variable defined within a function to be used outside that function? Commented Jul 10, 2015 at 8:14
  • return it. if you want to return more than one object from your function to your working environment, stuff everything into a list. in the first iteration just pass an empty plot to your function Commented Jul 10, 2015 at 8:15

1 Answer 1

1

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(...)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.