Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using layout with knitr

Tags:

markdown

r

knitr

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) 
like image 588
user1448319 Avatar asked Jun 26 '12 04:06

user1448319


People also ask

How do you use the knitr in RStudio?

If you are using RStudio, then the “Knit” button (Ctrl+Shift+K) will render the document and display a preview of it.

What is knitr used for?

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.

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.


1 Answers

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) 
like image 167
mnel Avatar answered Nov 15 '22 01:11

mnel