绘图无法在for循环中使用 [英] Plots not working in for loop

查看:92
本文介绍了绘图无法在for循环中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

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

推荐答案

当我使用 print 时,它起作用:

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

这篇关于绘图无法在for循环中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆