在 knitr 上绘制三分之一的地块

plot one in three plots on knitr

我想运行通过一个脚本做很多剧情,但是只有最后剧情才出来markdown
所以我试图做的是将许多图保存为图列表,但不将它们发布到 markdown。
第二步是浏览列表并绘制三个图中的一个,但由于某种原因我只得到最后一个图。

#+ setup, include=FALSE

library(knitr)
opts_chunk$set(fig.path = 'figure/silk-', fig.width = 10, fig.height = 10)

#' Make a list of plots.
#' 
#/* do not show in Markdown
index = 1
plots<-list()
for (let in letters)
{
 plot(c(index:100))
 assign(let,recordPlot())
 plot.new()
 plots[index]<-(let)
 index=index+1
}
#*/go through list of plots and plot then to markdown file
for (p in seq(from = 1, to = length(plots), by =3))
{

    print(get(plots[[p]]))

} 

您的代码中存在一些来自其他编程语言的错误:

  • 根本不要使用 assign。允许使用assign的人不会使用它。
  • plot.new() 创建一个空白页面。省略
  • 不要使用get。它在 S-Plus 中有它的用处,但现在没有用了。
  • 对于列表,使用 [[,例如plots[[index]]
  • 最重要的是:你想要的是有道理的,但标准图形(例如情节)不适合这个,因为它是在考虑行动而不是任务的情况下构建的。 latticeggplot2 图形都是分配感知的。
  • 在示例中,我使用 lapply 作为标准 R 实践的演示。在这种情况下,for 循环不会变慢,因为绘图会占用大部分时间。
  • 为此最好使用分面或面板,而不是许多单独的图。

`

library(knitr)
library(lattice)
# Make a list of plots.
# do not show in Markdown
plots = lapply(letters[1:3],
    function(letter) {xyplot(rnorm(100)~rnorm(100), main=letter)})

# print can use a list (not useful in this case)    
print(plots)

# go through list of plots and plot then to markdown file
# This only makes sense if you do some paging in between. 
for (p in seq(from = 1, to = length(plots), by =3))
{
  print(plots[[p]])
}