Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - Strange behaviour of ggplot2

I simply want to draw multiple arrows on a scatterplot using ggplot2. In this (dummy) example, an arrow is drawn but it moves as i is incremented and only one arrow is drawn. Why does that happen?

library(ggplot2)
a <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
b <- data.frame(x1=c(2,3),y1=c(10,10),x2=c(3,4),y2=c(15,15))
for (i in 1:nrow(b)) {
        a <- a + geom_segment(arrow=arrow(), 
          mapping = aes(x=b[i,1],y=b[i,2],xend=b[i,3],yend=b[i,4]))
         plot(a)
 }

Thanks.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

This isn't strange behavior, this is exactly how aes() is supposed to work. It delays evaluation of the parameters until the plotting actually runs. This is problematic if you include expressions to variable outside your data.frame (like i) and functions (like [,]). These are only evaulated when you actually "draw" the plot.

If you want to force evaulation of your parameters, you can use aes_. This will work for you

for (i in 1:nrow(b)) {
  a <- a + geom_segment(arrow=arrow(), 
    mapping = aes_(x=b[i,1],y=b[i,2],xend=b[i,3],yend=b[i,4]))
 }
plot(a)

Now within the loop the parameters for x= and y=, etc are evaluated in the environment and their value are "frozen" in the layer.

Of course, it would be better not to build layers in loops and just procide a proper data object as pointed out in @eipi10's answer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...