4

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).

Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
steffi
  • 513
  • 4
  • 15

2 Answers2

11

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.

Ramnath
  • 54,439
  • 16
  • 125
  • 152
  • setting out.width does not automatically put the figures side by side. I am trying to get grid.arrange to run... – steffi Dec 03 '12 at 16:23
  • i ran my code in RStudio and the output does show figures side by side. You might want to tweak the 50% value. Note that if you don't set message = F, then you would need `fig.show = "hold"` to ensure that your figures are printed at the end of the chunk and text does not interfere. – Ramnath Dec 03 '12 at 16:27
  • Works fine, the fig.show = "hold" was the key point. What happens if I would like to do, e.g., 20 plots. I guess I do not get automatically a line break. - So two plots in the first row, two plots in the second row... – steffi Dec 03 '12 at 16:49
  • 1
    I just solved the problem, the issue was to write print(ggplot(data...)). Just ggplot(data) was not enough to print the data.. – steffi Dec 03 '12 at 17:08
  • @steffi if you have 20 plots, you will get "line breaks" automatically if the width is greater than 1/3 but less than 1/2 of the container width. – Yihui Xie Dec 03 '12 at 19:47
5

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.

Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168