gpt4 book ai didi

r - 在循环中使用多个 geom_segment 丰富 ggplot2 图?

转载 作者:行者123 更新时间:2023-12-02 08:40:04 30 4
gpt4 key购买 nike

我使用以下命令成功创建了一个绘图:

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

但是如果我这样做:

values <- c(1, 5)
for (i in values) {
p <- p + geom_segment(aes(x=i,y=103,xend=i,yend=107))
}

它不起作用,只创建了最后一个段。任何人都可以建议这里出了什么问题吗?

最佳答案

这与 aes() 值的惰性求值有关。您绑定(bind)到变量 i 但实际上并未在循环中对其执行任何操作。在您实际 print(p) 之前,映射不会被解析。本质上,这意味着它们都绑定(bind)到 i ,并且在循环退出后,i 将具有最终循环期间的值。

所以问题确实是你不应该在这里使用 aes() 因为你并不真正想要主动绑定(bind)。只需在 aes() 之外设置 xxend 值即可。 (并且由于 y 是常量,因此它们也应该位于 aes() 之外)。

values <- c(1, 5)
for (i in values) {
p <- p + geom_segment(x=i, y=103, xend=i, yend=107)
}

关于r - 在循环中使用多个 geom_segment 丰富 ggplot2 图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24617414/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com