Strange ggplot2 behavior

I just want to draw some arrows on a scatter plot using ggplot2. In this (fictitious) example, the arrow is drawn, but it moves as I increases and only one arrow is drawn. Why is this happening?

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)
 }

Thank.

+4
source share
2 answers

This is not weird behavior, this is exactly how it should work aes(). This delays the evaluation of the parameters until the actual execution of the graph. This is problematic if you include expressions for a variable outside of your data.frame (for example, i) and a function (for example, [,]). It only shows up when you actually “draw” the plot.

evaulation , aes_.

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)

x= y= .. , "" .

, , @eipi10.

+3

@Roland , , geom_segment(arrow=arrow(), mapping = aes(x=b[i,1],y=b[i,2],xend=b[i,3],yend=b[i,4])) a. i a. , i=1 i=2. , i 2. , . i=1:2, . , i -, 1 / 2, .

:

ggplot(mtcars, aes(wt, mpg)) + 
  geom_point() +
  geom_segment(data=b, arrow=arrow(), aes(x=x1,y=y1,xend=x2,yend=y2))

@Roland : a , geom_segment? , OP a,

a = a + geom_segment(arrow=arrow(), aes(x=b[1,1],y=b[1,2],xend=b[1,3],yend=b[1,4])) 

, ,

a = a + geom_segment(arrow=arrow(), aes(x=b[1,1],y=b[1,2],xend=b[1,3],yend=b[1,4])) + 
        geom_segment(arrow=arrow(), aes(x=b[2,1],y=b[2,2],xend=b[2,3],yend=b[2,4])) 

a a . a , a ?

+2

Source: https://habr.com/ru/post/1651896/


All Articles