将层添加到ggplots是可行的,但不能添加循环 [英] Adding layers to ggplots works but adding in a loop does not
本文介绍了将层添加到ggplots是可行的,但不能添加循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想循环添加到现有的ggplot中.当我将点添加到不使用循环的列表中时,它的工作原理如下面的最小示例所示(左图).当我在循环中执行相同操作时,最终结果仅包含我添加的最后一点(右图).
I want to add to an existing ggplot in a loop. It works fine as shown in a minimal example below when I add points to a list not using a loop (left plot). When I do the same in a loop, the final result only contains the last point that I added (right plot).
library(ggplot2)
p <- list(); pl <- list()
x0 <- c(-1,1); y0 <- c(-3,3); q <- c(-5,5)
#no loop
p[[1]] <- ggplot() + coord_fixed(xlim = q, ylim = q)
p[[2]] <- p[[1]] +geom_point(aes(x=x0[1], y=y0[1]))
p[[3]] <- p[[2]] + geom_point(aes(x=x0[2], y=y0[2]))
#loop
pl[[1]] <- ggplot() + coord_fixed(xlim = q, ylim = q)
for (i in 1:2)
{
pl[[i+1]] <- pl[[i]] + geom_point(aes(x=x0[i], y=y0[i]))
}
p[[3]]
pl[[3]]
推荐答案
您是惰性评估的受害者.[例如,请参见此处.] 代码>循环使用惰性评估.幸运的是, lapply
不会.所以,
You're a victim of lazy evaluation. [See, for example, here.] A for
loop uses lazy evaluation. Fortunately, lapply
does not. So,
p <- ggplot() + coord_fixed(xlim = q, ylim = q)
lapply(
1:2,
function(i) p <<- p + geom_point(aes(x=x0[i], y=y0[i]))
)
为您提供想要的东西.
请注意使用<<-
作为快速而肮脏的修复程序.
Note the use of <<-
as a quick and dirty fix.
这篇关于将层添加到ggplots是可行的,但不能添加循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文