在循环中用多个geom_segment丰富ggplot2图? [英] Enriching a ggplot2 plot with multiple geom_segment in a loop?
问题描述
我使用以下方法成功创建了一个图:
#假设我有ap< - ggplot(data = df, ...),那么下面的工作
#我得到正确绘制的这两个片段
p <-p + geom_segment(aes(x = 1,y = 103,xend = 1,yend = 107))
p <-p + geom_segment(aes(x = 5,y = 103,xend = 5,yend = 107))
然而,如果我这样做: 它不起作用,只创建最后一个段。任何人都可以建议这里有什么问题吗? 它与 所以这个问题真的是你没有在这里使用
$ p $ 值< - c(1,5)
$($ in $)$ $ b $ p }
和 aes )
值。你绑定了变量 i
,但实际上并没有在循环中对它做任何事情。除非你真的 print(p)
,否则映射不会被解析。基本上这意味着它们都被绑定到 i
并且在循环退出之后, i
将具有它在最后一个循环。
aes()
真的不想要主动绑定。只需在 aes()
x xend
>。 (既然 y
是常量,它们也应该在 aes()
之外)。
值<-c(1,5)
for(i in values){
p < - p + geom_segment(x = i,y = 103,xend = i,yend = 107)
}
I successfully create a plot using the following:
# suppose I have a p <- ggplot(data=df, ...) then the following works
# I get those two segments plotted correctly
p <- p + geom_segment(aes(x=1,y=103,xend=1,yend=107))
p <- p + geom_segment(aes(x=5,y=103,xend=5,yend=107))
However if I do:
values <- c(1, 5)
for (i in values) {
p <- p + geom_segment(aes(x=i,y=103,xend=i,yend=107))
}
It doesn't work, only the last segment is created. Can anyone advice what's wrong here?
It has to do with the lazy evaluation of the aes()
values. You are binding to the variable i
but not actually doing anything with it in the loop. The mappings aren't resolved till you actually print(p)
. Essentially this means they are all being bound to i
and after the loop exits, i
will have the value it had during the final loop.
So the problem really is you shounld't be using aes()
here as you don't really want active binding. Just set the x
and xend
values outside the aes()
. (And since the y
's are constant they should be outside the aes()
as well).
values <- c(1, 5)
for (i in values) {
p <- p + geom_segment(x=i, y=103, xend=i, yend=107)
}
这篇关于在循环中用多个geom_segment丰富ggplot2图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!