0
votes

I have a summary figure that I want to insert at the top of my HTML report generated using knitr/rmarkdown. But the inputs of this figure depend on outputs generated from downstream code chunks and child documents. Is there a way to do this without having to put the summary figure at the end of the document?

I have tried ref.label='last' option in the top level code chunk (with eval=FALSE) to add a duplicate code chunk in the end of the document {r last, eval=TRUE}, but has not worked for me.

Any suggestions?

1

1 Answers

0
votes

You can insert HTML anywhere into your document referencing the figure by the name knitr will use for it.

To figure out the name, temporarily change the YAML header to something like this:

  output: 
    html_document:
      self_contained: FALSE

This won't embed figures in the output, they'll be kept in a separate directory. Open the output in an editor, or view source in a browser, and look for the line that displays the figure. In my test example below, it was being displayed by this code:

<p><img src="Untitled2_files/figure-html/rnormplot-1.png" width="672" /></p>

I copied that line into the document, and removed the self_contained setting, and got this source code:

---
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

This is the figure before it was generated:

<p><img src="Untitled2_files/figure-html/rnormplot-1.png" width="672" /></p>

And here it is being generated:

```{r rnormplot}
x <- rnorm(100)
plot(x)
```

One key is to name the code chunk that generates the plot (mine is named rnormplot) because that helps to make sure the figure name is independent of the rest of the document.