绘图在 for 循环中不起作用

Plots not working in for loop

我需要制作一堆单独的图,并希望在 for 循环中完成。我正在使用 ggplot2。如果它可以将每个图形保存在一个单独的文件中,我只会使用 facet 选项,但我认为它做不到。

有些事情正在发生,因为绘图没有保存到文件中。虽然生成了文件,但是它们是空的。这是我的代码的一个想法:

for(i in 1:15) {    
pdf(paste("path/plot", i, ".pdf", sep=""), width=4, height=4)

abc <- ggplot(data[data[,3]==i,], 
              aes(variable, value, group=Name, color=Name)) + 
  geom_point(alpha=.6, size=3)+geom_line() + 
  theme(legend.position="none", axis.text.x = element_text(angle = -330)) + 
  geom_text(aes(label=Name),hjust=0, vjust=0, size=2.5) + 
  ggtitle("Title")

abc

dev.off()
}

如何将绘图保存到这些文件中?

请注意,如果我有一个数值并且我 运行 for 循环中的代码,一切正常。

当我使用 print 时它有效:

for(i in 1:15) {   
  pdf(paste("plot", i, ".pdf", sep=""), width=4, height=4)
  abc <- ggplot(mtcars, aes(cyl, disp)) + 
    geom_point(alpha=.6, size=3)
  print(abc)
  dev.off()
}

或者试试 ggsave:

for(i in 1:15) {   
Filename <- paste("plot", i, ".pdf", sep="")
abc <- ggplot(mtcars, aes(cyl, disp)) + 
    geom_point(alpha=.6, size=3)
ggsave(filename = Filename, abc, width=4, height=4)
}