一个块中的knitr图,标签和标题 - .Rmd文件

时间:2014-12-12 11:46:57

标签: r knitr

Jallen制作了一个解决方案,用于在一个块内生成knitr图,标签和标题 - 用于Rnw文件。

knitr plots, labels, and captions within one chunk

这很适合.Rnw,但是我不能让它适用于.Rmd,不知道出了什么问题...

---
output:
  pdf_document:
    fig_caption: yes
    fig_crop: no
---

```{r startup,echo=FALSE,results='hide',message=FALSE,tidy=FALSE,warning=FALSE,fig.keep='all',comment=NA}
require(knitr)
require(ggplot2)
opts_knit$set(progress = F, verbose = F)
opts_chunk$set(comment=NA,
           tidy=FALSE,
           warning=FALSE, 
           message=FALSE, 
           echo=FALSE, 
           dpi=600,
           fig.width=6.75, fig.height=4, # Default figure widths
           dev=c("pdf",'tiff'),
           dev.args=list(pdf=list(NULL),tiff=list(compression='lzw')),
           error=FALSE)

```


```{r plotloop,results='asis'}
for(x in seq(1,20)){
  x1<-data.frame(x=seq(1,10),y=seq(1,10))
  plt<-ggplot(data=x1,aes(x,y))+geom_point()
  figLabel=paste('Figure',x,sep='')
  capt<-paste('Caption for fig.',x)
  cat(knit(text=(paste("```{r ",figLabel,",fig.pos='h',fig.cap='",capt,"'}\nplt\n```",sep=''))))
cat('\\newpage')

1 个答案:

答案 0 :(得分:2)

可以修改knitr plots, labels, and captions within one chunk中的plot.knit函数以考虑markdown的语法而不是latex。 plot.knit.md变为

plot.knit.md<-function(chunkLabel,#text for chunk label which is also used for figure file name
                    capt,#text for caption
                    plt,
                    ...)
  {
  cat(knit(text=knit_expand(text="```{r, {{chunkLabel}},eval=TRUE,fig.cap='{{capt}}',echo=FALSE}\nplt\n```"),
       quiet=TRUE))
  }

这适用于以下降价文档。

---
title: "plot.knit.md demo"
author: "Joel Allen"
date: "04/23/2015"
output:
  html_document: default
  pdf_document:
    fig_caption: yes
---

This is an R Markdown document to demonstrate the generation of self-contained code chunks in a markdown file.  It is particularly useful for situations where multiple plots are generated in a single code chunk allowing for dynamic label and caption support.

This example draws on 

http://stackoverflow.com/questions/21685885/knitr-plots-labels-and-captions-within-one-chunk

in response to 

https://stackoverflow.com/questions/27443019/knitr-plots-labels-and-captions-within-one-chunk-rmd-files

Items to note:

#. output pdf_document fig_caption option must be set to yes

#. plot.knit has been modified to plot.knit.md to account for the different syntax needed.

```{r, echo=FALSE,results='asis'}
plot.knit.md<-function(chunkLabel,#text for chunk label which is also used for figure file name
                    capt,#text for caption
                    plt,
                    ...)
  {
  cat(knit(text=knit_expand(text="```{r, {{chunkLabel}},eval=TRUE,fig.cap='{{capt}}',echo=FALSE}\nplt\n```"),
       quiet=TRUE))
  }
require(ggplot2)
cars.p<-ggplot(cars,aes(x=speed,y=dist))+
  geom_point()
plot.knit.md(chunkLabel="carsPlot",capt="this is a caption for the cars plot",plt=cars.p)
```

要弄清楚的一件事是标签的附件......