在knitr上绘制三个地块中的一个

时间:2016-03-02 06:31:35

标签: r plot knitr r-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]]))

} 

1 个答案:

答案 0 :(得分:2)

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

  • 根本不使用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]])
}
相关问题