R:将图表存储到列表中,然后编织knitr文档

时间:2014-11-23 08:27:30

标签: r knitr

我想要一个自定义函数为我生成一些图,然后将它们编织到knitr文档中。

生成图并将它们添加到列表中只会给我一个向量而不是图。

任何线索?

   tesing
   =======================

   ```{r echo=FALSE,results='asis'}
   mytest <- function(myresponse, myterms, mydata) {
     # do clever stuff...
     # then:
     plot1 <- barplot(ppr$pain_protocol1, name=ppr$category,las=2)
     plot2 <- barplot(ppr_pa$extra_pp, name=ppr_pa$adult_anaesthetist,las=2)
     list(plot1 = plot1, plot2 = plot2)
   }

   terms <- c(' age', 'log_age', 'age2', 'inv_age', 'op_time', 'log_op_time',
       'op_time2', 'gender', 'category', 'thimble')
   response <- 'pain_protocol1'
   results <- mytest(response, terms, d4)

   ```

然后这两个都不起作用:

  This is plot 1:

  ```{r echo=FALSE,results='asis'}
  library(ggplot2)
  ggplot_build(results[["plot1"]])
  ```

  This is plot 2:

  ```{r echo=FALSE,results='asis'}
  results[["plot2"]]
  ```

1 个答案:

答案 0 :(得分:3)

R中的默认barplot功能是&#34;基本图形&#34;调用它时绘制的函数。你不能保存这样的情节,并希望通过打印重播它 - 我怀疑你习惯ggplot那样的网格图形。

一个修复可能是使用ggplot图形来完成绘图。你的代码示例不可重现,所以我会在这里停下来,因为我无法准确地告诉你你想要什么。

这是使用recordPlot的基础图形解决方案。您只需在使用块选项创建它们时隐藏图形,否则它们会出现两次。请注意,这是一个可重现的示例 - 将其放在foo.Rmd中,运行knit2html("foo.Rmd"),在浏览器中查看foo.html

tesing
=======================

```{r echo=FALSE,results='asis'}
mytest <- function() {
 set.seed(310366)
  mydata = data.frame(x=runif(10),y1=runif(10),y2=runif(10))
  plot(mydata$x, mydata$y1)
  plot1 = recordPlot()
  plot(mydata$x, mydata$y2)
  plot2 = recordPlot()
  list(plot1 = plot1, plot2 = plot2)
}
```

And now create the plots but don't show...

```{r figures,fig.show="hide"}
plots = mytest()
```

Now show the first

```{r plot1here}
plots[[1]]
```

and then another

```{r plot2here}
plots[[2]]
```
相关问题