Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

caption in the html output of knitr

When knitting the following Rmd file

```{r, fig.cap="mycaption"}
plot(0,0,axes=FALSE,xlab=NA,ylab=NA)

```

with the "Knit HTML" button of RStudio then the caption does not appear in the html output file. Indeed the html source code corresponding to the figure is:

<p><img src="data:image/png;base64,..." alt="mycaption"/></p> 

To see the caption it should be for instance:

<p><img src="data:image/png;base64,..." alt="mycaption"/><p class="caption">mycaption</p></p> 

How to easily get an html output with visible captions ?

like image 564
Stéphane Laurent Avatar asked Feb 21 '13 19:02

Stéphane Laurent


People also ask

What does knitr :: Opts_chunk set echo true mean?

The first code chunk: ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` is used to specify any global settings to be applied to the R Markdown script. The example sets all code chunks as “echo=TRUE”, meaning they will be included in the final rendered version.

How do I write HTML in R Markdown?

To transform your markdown file into an HTML, PDF, or Word document, click the “Knit” icon that appears above your file in the scripts editor. A drop down menu will let you select the type of output that you want. When you click the button, rmarkdown will duplicate your text in the new file format.

How do I caption an image in R Markdown?

Figure captions are turned off by default in R Markdown, and you have to turn them on ( fig_caption: true ). You can also find this setting from the gear button on the toolbar of RStudio IDE. Thanks very much!

How do I display code output in R Markdown?

There are two ways to render an R Markdown document into its final output format. If you are using RStudio, then the “Knit” button (Ctrl+Shift+K) will render the document and display a preview of it. Note that both methods use the same mechanism; RStudio's “Knit” button calls rmarkdown::render() under the hood.


1 Answers

I usually just use results='asis' in the chunk options and include raw html in the chunk, wrapping it in cat() but as Yihui mentioned you can create your own hook:

```{r}
knit_hooks$set(htmlcap = function(before, options, envir) {
  if(!before) {
    paste('<p class="caption">',options$htmlcap,"</p>",sep="")
    }
    })
```

```{r, htmlcap="Hello Dolly"}
library(ggplot2)
ggplot(diamonds,aes(price,carat)) + geom_point()
```
like image 72
Brandon Bertelsen Avatar answered Oct 15 '22 03:10

Brandon Bertelsen