Plots not working in for loop [duplicate]

血红的双手。 提交于 2021-02-04 12:16:12

问题


I need to make a bunch of individual plots and want to accomplish this in a for loop. I am using ggplot2. I would just use the facet option if it could save each graph in a separate file, which I don't think it can do.

There is something going on because the plots are not saved into the files. The files are generated, though, but are empty. Here is an idea of what my code looks like:

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()
}

How can I save the plots into these files?

Note that if I has a numeric value and I run the code inside the for loop, everything works.


回答1:


When I use print it works:

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()
}



回答2:


Or try 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)
}


来源:https://stackoverflow.com/questions/29053223/plots-not-working-in-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!