【问题标题】:plot one in three plots on knitr在 knitr 上绘制三分之一的地块
【发布时间】:2016-06-14 21:11:33
【问题描述】:

我想运行一个脚本并制作许多情节,但只有在最后情节然后才降价
所以我试图做的是将许多地块保存为地块列表,但不将它们发布到降价。
第二步是通过列表并绘制三分之一的地块,但由于某种原因,我只得到最后一个地块。

#+ 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]]))

} 

【问题讨论】:

    标签: r plot knitr r-markdown


    【解决方案1】:

    作为其他编程语言的遗物,您的代码中有一些错误:

    • 根本不要使用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]])
    }
    

    【讨论】:

    • 谢谢! 1. 我不确定我是否理解您的一些 cmets:“被允许使用 assign 的人不会使用它”(?) 2. 您将循环转为 apply,这是一种很好的做法,但是当我注释掉 apply 函数时并且只使用最后一个 for 循环我仍然只得到记录的最后一个情节
    • 这是我在 2001 年左右在类似工作中使用 assign 时引用的 r-help。请参阅markmail.org/message/w3hwkqs6e57wbuie 和许多其他地方。
    • 当你评论 lapply 函数时,你什么也得不到,或者更好的是你上次运行的遗物。在重新运行之前重新启动 R
    • 我没有将它完全注释掉,我之前和之后的 '/*' 和 '*/' 所以它不会显示在 md 文件中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-08
    相关资源
    最近更新 更多