Multiple plots in a for loop with Sweave

自闭症网瘾萝莉.ら 提交于 2019-12-01 16:59:45

问题


My chunk in Sweave:

<<fig=TRUE,echo=FALSE>>=
for(i in 1:10) {
  plot(rep(i,10))
  dev.new()
}
@

In the resulting pdf I get only one plot (from the first iteration). I would like to have all of the 10 plots printed. What am I doing wrong? I tried replacing dev.new() with frame() and plot.new() but nothing happened.


回答1:


As @rawr suggests the easiest solution is to switch to knitr (there's really no reason at all not to!) and put fig.keep="all" in your code chunk options (if you switch to knitr you don't need fig=TRUE any more ... including figures works automatically, fig.keep="none" is the analogue of fig=FALSE)

Alternatively, if you want to stick with vanilla Sweave, check the Sweave manual p. 17:

A.9 Creating several figures from one figure chunk does not work

Consider that you want to create several graphs in a loop similar to

<<fig=TRUE>>
for (i in 1:4) plot(rnorm(100)+i)
@

This will currently not work, because Sweave allows only one graph per figure chunk. The simple reason is that Sweave opens a postscript device before executing the code and closes it afterwards. If you need to plot in a loop, you have to program it along the lines of

<<results=tex,echo=FALSE>>=
for(i in 1:4){
file=paste("myfile", i, ".eps", sep="")
postscript(file=file, paper="special", width=6, height=6)
plot(rnorm(100)+i)
dev.off()
cat("\\includegraphics{", file, "}\n\n", sep="")
}
@


来源:https://stackoverflow.com/questions/24130725/multiple-plots-in-a-for-loop-with-sweave

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