I want to make a single figure in R with two plots in a markdown file with knitr
. Normally, this is easy to do with layout(t(1:2))
or par(mfrow=c(1,2))
. Can I do this with knitr
, or will it always make two separate figures?
Here is a minimum working example which creates a file called ./junk.Rmd
and ./junk.md
in your working directory along with two files ./figure/junkislands1.png
(which only includes the first plot) and ./figure/junkislands2.png
(which includes both plots that I want).
require(knitr)
temp <- "```{r junkislands, fig.width=8, fig.height=5}
layout(t(1:2))
pie(islands)
barplot(islands)
```"
cat(temp, file="junk.Rmd")
knit("junk.Rmd", "junk.md")
The problem isn't so much that it creates two .png files, but rather that the markdown file junk.md
includes both of them.
When I make that markdown into html, it includes both .png files when I only want the one with both figures plotted.
Here is the file junk.md
that is generated from knitr:
```r
par(mfrow = c(1, 2))
pie(islands)
```
![plot of chunk junkislands](figure/junkislands1.png)
```r
barplot(islands)
```
![plot of chunk junkislands](figure/junkislands2.png)
If you are using RStudio, then the “Knit” button (Ctrl+Shift+K) will render the document and display a preview of it.
knitr is an engine for dynamic report generation with R. It is a package in the programming language R that enables integration of R code into LaTeX, LyX, HTML, Markdown, AsciiDoc, and reStructuredText documents. The purpose of knitr is to allow reproducible research in R through the means of literate programming.
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.
Have a look at http://yihui.name/knitr/options and specifically fig.keep
. I think you want fig.keep = 'last'
require(knitr)
temp <- "```{r junkislands, fig.width=8, fig.height=5, fig.keep = 'last'}
layout(t(1:2))
pie(islands)
barplot(islands)
```"
cat(temp, file="junk.Rmd")
knit("junk.Rmd", "junk.md")
gives
```r
layout(t(1:2))
pie(islands)
barplot(islands)
```
![plot of chunk junkislands](figure/junkislands.png)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With