Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
610 views
in Technique[技术] by (71.8m points)

r - force ggplot to evaluate counter variable

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The aes() specifically prevents evaluation. If you want evaluation, you can use the standard-evaluation version aes_()

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...