Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple figures with rhtml and knitr

Tags:

html

r

knitr

I have an Rhtml file from which I source a R file. In this R file I am doing some plots.

p=ggplot(data)
p+geom_line()

Now, I can produce one plot after the other and when doing knit(".Rhtml") then I get on figure after the other.

But I would like to have the figures side by side. (Number of figures varies from report to report).

Is there a way to set an option in the Rhtml file, so that the figures are arranged side by side (e.g. two or three or four columns).

So, actually it would be something like a par(mfrow).

like image 852
steffi Avatar asked Dec 05 '22 13:12

steffi


2 Answers

Use out.width to put figures side by side. Here is a reproducible example

## Figures side by side


```{r out.width = '50%', echo = F, message = F}
require(ggplot2)
p0 = qplot(wt, mpg, data = mtcars)
p1 = p0 + geom_smooth()
p0
p1
```

EDIT. If you want your code to show up, or messages to show up, then just add fig.show = "hold" to your chunk options to ensure that your figures are printed after the rest of the chunk, which will then print them side by side since you set out.width = "50%"

See this news from knitr to note when the change was introduced.

like image 68
Ramnath Avatar answered Dec 18 '22 01:12

Ramnath


Plots can be combined with the gridExtra package. If you have, e.g., three plots (p1, p2, and p3), the command is:

library(gridExtra)
newPlot <- grid.arrange(p1, p2, p3)

Have a look at the gridExtra package for more details.

like image 33
Sven Hohenstein Avatar answered Dec 18 '22 00:12

Sven Hohenstein