[英]R: store plots to a list then weave in knitr document
我想要一个自定义函数为我生成一些图,然后将它们输出并编织到编织文档中。
生成图并将它们添加到列表中只会给我一个向量,而不是图。
有什么线索吗?
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"]]
```
R中的默认barplot
函数是“基本图形”函数,在您调用它时会进行绘制。 您无法保存那样的图并希望通过打印来重播它-我怀疑您已经习惯了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]]
```
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.