Soon
Soon

Reputation: 501

(R)Making a list of ggplot objects

My goal it to get a list p which contains two graphs p[[1]] and p[[2]]. p[[1]] and p[[2]] are supposed to be a plot with point(10,10) and point(20,20) for each. But after executing below, in the list p, only p[[2]] shows expected graph. P[[1]] graph does not appear. How to correct to make p[[1]] in the list have point(10,10)? (It seemd that the variable cordx and cordy are tightly coupled to p[[1]], so whenever the cordx, cordy are changed, the alredy made p[[1]] is revised everytime.)

library(ggplot2)
xx<-list(10,20);yy<-list(10,20)
p<-list()
for (i in (1:2) ) {
cordy<-yy[[i]];cordx<-xx[[i]] #But,at 2nd loop(that is when i=2),after executing this line, my p[[1]] is affected unexpectedly, containning point (20,20))
p<-ggplot()+geom_point(aes(x=cordx,y=cordy))
p[[i]]<-p # at 1st loop(that is i=1), p[[1]] contains point (10,10) as expected.
}
print(p[[1]])
print(p[[2]])

Upvotes: 0

Views: 347

Answers (1)

Paul
Paul

Reputation: 2977

May I suggest using mapply() to avoid looping?

Here is the code:

library(ggplot2)

xx <- list(10,20)
yy <- list(10,20)

p <- mapply(function(cordx, cordy) { ggplot() + geom_point(aes(x = cordx, y = cordy)) }, xx, yy, SIMPLIFY = FALSE)

print(p[[1]])
print(p[[2]])

What it does: mapply pass each element of xx and yy in the function that creates the plot. The outputs of the function are stored in the object p. SIMPLIFY = FALSE forces p to be a list.

Outputs:

enter image description here

enter image description here

Upvotes: 1

Related Questions