ggplot 会进行一些惰性求值,因此在您的for 循环示例中i 不会立即求值。如果我们查看这些层,我们可以看到i 仍然存在为i,而不是3 和4 在各自的迭代中。当您打印绘图时,即评估 i 时 - 在您打印绘图时采用的任何值。什么时候甚至可以在循环后更改i 导致问题:
aux <- 3:4
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
for (i in 1:2) {
p <- p + geom_segment(aes(x = aux[i], y = 0, xend = aux[i], yend = 35), colour = "purple")
}
p$layers
# [[1]]
# geom_point: na.rm = FALSE
# stat_identity: na.rm = FALSE
# position_identity
#
# [[2]]
# mapping: x = ~aux[i], y = 0, xend = ~aux[i], yend = 35
# geom_segment: arrow = NULL, arrow.fill = NULL, lineend = butt, linejoin = round, na.rm = FALSE
# stat_identity: na.rm = FALSE
# position_identity
#
# [[3]]
# mapping: x = ~aux[i], y = 0, xend = ~aux[i], yend = 35
# geom_segment: arrow = NULL, arrow.fill = NULL, lineend = butt, linejoin = round, na.rm = FALSE
# stat_identity: na.rm = FALSE
# position_identity
## changing `i` later can still cause problems:
i = 5
print(p)
# Warning messages:
# 1: Removed 32 rows containing missing values (geom_segment).
# 2: Removed 32 rows containing missing values (geom_segment).
所以,不,你不能真的像那样使用for 循环。可能有一些解决方法,但这感觉像是一个 XY 问题 - 这不是 ggplot 的用途,因此以这种方式使用它会很困难。
很难知道您的真实用例是什么,但在这种情况下,我们可以将aux 数据放入数据框中并像这样(ggplot 可用于数据框):
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
geom_segment(
data = data.frame(aux),
aes(x = aux, xend = aux),
y = 0, yend = 35, colour = "purple"
)
不过,对于垂直线的特殊情况,我们可以直接使用geom_vline 和aux 向量:
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
geom_vline(xintercept = aux, colour = "purple")