1

I want to add to an existing ggplot in a loop. It works fine as shown in a minimal example below when I add points to a list not using a loop (left plot). When I do the same in a loop, the final result only contains the last point that I added (right plot).

library(ggplot2) 

p <- list(); pl <- list()
x0 <- c(-1,1); y0 <- c(-3,3); q <- c(-5,5)

#no loop
p[[1]] <- ggplot() + coord_fixed(xlim = q, ylim = q)
p[[2]] <- p[[1]] +geom_point(aes(x=x0[1], y=y0[1])) 
p[[3]] <- p[[2]] + geom_point(aes(x=x0[2], y=y0[2])) 

#loop
pl[[1]] <- ggplot() + coord_fixed(xlim = q, ylim = q)
for (i in 1:2)
{
  pl[[i+1]] <- pl[[i]] + geom_point(aes(x=x0[i], y=y0[i]))
}

p[[3]]
pl[[3]]

enter image description here

2 Answers 2

3

This is due to what is called "lazy evaluation", explained in several posts (like this). You don't need to add the plots into lists you just overwrite and get the same result. As for the loop you need to put your data into a data.frame and feed it to the geom_point() function:

p <- list(); pl <- list()
x0 <- c(-1,1); y0 <- c(-3,3); q <- c(-5,5)

#no loop
p <- ggplot() + coord_fixed(xlim = q, ylim = q)
p <- p +geom_point(aes(x=x0[1], y=y0[1])) 
p <- p + geom_point(aes(x=x0[2], y=y0[2])) 

#loop
pl <- ggplot() + coord_fixed(xlim = q, ylim = q)
for (i in 1:2){
  data<-cbind.data.frame(x=x0[i], y=y0[i])
  pl <- pl + geom_point(data=data,aes(x=x, y=y))
}

p
pl
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, but the other answer fits my real problem better than your answer, therefore I accpeted it - and not yours.
2

You're a victim of lazy evaluation. [See, for example, here.] A for loop uses lazy evaluation. Fortunately, lapply does not. So,

p <- ggplot() + coord_fixed(xlim = q, ylim = q)
lapply(
  1:2,
  function(i) p <<- p + geom_point(aes(x=x0[i], y=y0[i]))
)

gives you what you want.

Note the use of <<- as a quick and dirty fix.

1 Comment

Your code works for my special problem! In my search I did not find those link that you provided. "<<-" ... again something learned.

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.