I ran into an interesting problem regarding how/when variables
are evaluated in ggplot constructs.
The simplest example I can think of to reproduce this is the
following (which is supposed to place the points 1 to 10 on a plot):
df=data.frame(x=1:10,y=1:10)
panel=ggplot() + xlim(-1,11) + ylim(-1,11)
for (i in c(1:10)) {
panel=panel+geom_point(aes(x=df$x[i],y=df$y[i]))
}
print(panel)
This will generate a plot with one point, i.e. the one for i=10
If I give i another value (in the range 1 to 10) and repeat the
print(panel) command then that particular point will be plotted.
And if I do i <- c(1:10) followed by print(panel) then all the ten points will be plotted, just as if I had issued the vectorized version:
ggplot(aes(x=x,y=x),data=df)+geom_point()
It seems to me that here i is only evaluated when the print(panel) command is issued.
I ran into this in a very complicated plot where i was looping through the elements of a list, and a vectorized version is not practical.
So, the question her is:
Is there a way to force ggplot to evaluate i for each step in the loop?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…