我使用以下方法成功创建了一个图:
# 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))
Run Code Online (Sandbox Code Playgroud)
但是,如果我这样做:
values <- c(1, 5)
for (i in values) {
p <- p + geom_segment(aes(x=i,y=103,xend=i,yend=107))
}
Run Code Online (Sandbox Code Playgroud)
它不起作用,只创建了最后一个段.任何人都可以在这里建议什么是错的吗?
MrF*_*ick 14
它与对aes()
值的惰性评估有关.您绑定到变量i
但实际上没有在循环中对它执行任何操作.实际上,映射不会得到解决print(p)
.基本上这意味着它们都被绑定到i
循环退出后,i
将具有它在最终循环期间具有的值.
所以问题实际上是你不能在aes()
这里使用,因为你真的不想要主动绑定.只需设置x
和xend
之外的值aes()
.(因为y
它们是不变的,所以它们也应该在外面aes()
).
values <- c(1, 5)
for (i in values) {
p <- p + geom_segment(x=i, y=103, xend=i, yend=107)
}
Run Code Online (Sandbox Code Playgroud)
小智 11
另一种方法是避免使用循环.您可以将段数据打包在主数据的单独data.frame中,并使用aes()一次性绘制所有内容,如下所示:
segment_data = data.frame(
x = c(1, 5),
xend = c(1, 5),
y = c(103, 103),
yend = c(107, 107)
)
p = ggplot(df, ...) +
geom_segment(data = segment_data, aes(x = x, y = y, xend = xend, yend = yend))
Run Code Online (Sandbox Code Playgroud)