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

zx8754
  • 52,746
  • 12
  • 114
  • 209
HOSS_JFL
  • 765
  • 2
  • 9
  • 24

2 Answers2

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
mfalco
  • 428
  • 3
  • 14
  • Thanks, but the other answer fits my real problem better than your answer, therefore I accpeted it - and not yours. – HOSS_JFL May 06 '21 at 09:34
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.

Limey
  • 10,234
  • 2
  • 12
  • 32
  • Your code works for my special problem! In my search I did not find those link that you provided. "<<-" ... again something learned. – HOSS_JFL May 06 '21 at 09:33