ggplot2:在for循环中创建绘图时不保存手动缩放值

时间:2017-07-20 12:59:47

标签: r list ggplot2 save scale

我想通过循环遍历不同的数据集来创建线段图,并手动设置线型的比例值。但是,使用for循环,尽管为每个绘图定义了一个单独的比例,但只有循环中最后一个绘图的比例用于所有其他绘图。

此行为显示在以下最小示例中:

library(ggplot2)

DF <- list(
  DF1 = data.frame(x=1:10, y=1:10, type=as.factor(c(rep(0,5),rep(1,5)))),
  DF2 = data.frame(x=1:10, y=1:10, type=as.factor(sort(rep(1:5,2))))
)

linetype <- list(
  linetype1 <- 4:5,
  linetype2 <- 1:5
)

plotlist <- list()

for(i in 1:2){
plotlist[[i]] <- ggplot(DF[[i]], aes(x, y, linetype=type)) +
  geom_line() +
  scale_linetype_manual(values=linetype[[i]])
}

然后,打印情节时

plotlist[[1]]

它显示第一个绘图的线条与第二个绘图的线型值。

Plot 1 created within the for loop: it uses the scale linetype2.

我追求的情节是:

Plot 1 as I would like to appear: using the scale linetype1.

可以使用for循环外的相同代码创建:

i <- 1

plotlist[[i]] <- ggplot(DF[[i]], aes(x, y, linetype=type)) +
  geom_line() +
  scale_linetype_manual(values=linetype[[i]])

这种行为来自哪里?它有什么办法吗?我在这里感到茫然,谢谢你的帮助!

修改

我可以使用lapply获得预期的列表:

plotlist <- lapply(1:2, function(i){
  ggplot(DF[[i]], aes(x, y, linetype=type)) +
  geom_line() +
  scale_linetype_manual(values=linetype[[i]]
})

但我仍然不明白为什么在for循环中没有发生预期的行为。我的猜测是,仅在打印图形时评估比例值;那时,只有最后一个比例在环境中可用。这根本不是一个很好的解释,我想知道这种行为的细节。

0 个答案:

没有答案