3
votes

[Related to Control alignment of two side-by-side plots in knitr ]

I cannot figure out how to arrange two side-by-side plots as explained in the knitr graphics manual page 2 (http://yihui.name/knitr/demo/graphics/). I use the following MWE and the output is below. I would like to be able to control the distance between the plots - the two plots are now too close to each other. The pdf is generated in RStudio (Knit to PDF).

I have tried to tamper with for instance par(mar = c(rep(5,4))), but without luck.

---
title: "Untitled"
output: pdf_document
---

## R Markdown

```{r,echo=FALSE,out.width='.49\\linewidth', fig.width=3, fig.height=3, fig.show='hold',fig.align='center'}

barplot(1:4)
barplot(4:7)

```

enter image description here

1

1 Answers

2
votes

You can use layout to add an adjustable space between the two plots. Create a three-plot layout and make the middle plot blank. Adjust the widths argument to apportion the relative amount of space among the three plots.

In the example below, I also had to adjust the plot margin settings (par(mar=c(4,2,3,0))) to avoid a "figure margins too large" error and I changed fig.width to 4 to get a better aspect ratio for the plots. You may need to play with the figure margins and the figure parameters in the chunk to get the plot dimensions you want.

```{r,echo=FALSE,out.width='.49\\linewidth', fig.width=4, fig.height=3, fig.align='center'}

par(mar=c(4,2,3,0))
layout(matrix(c(1,2,3),nrow=1), widths=c(0.45,0.1,0.45))
barplot(1:4)
plot.new()
barplot(4:7)

```

enter image description here

If you happen to want to use grid graphics, you can use an analogous approach:

```{r,echo=FALSE,out.width='.49\\linewidth', fig.width=3, fig.height=3, fig.align='center'}

library(ggplot2)
library(gridExtra)
library(grid)

p1=ggplot(mtcars, aes(wt, mpg)) + geom_point()

grid.arrange(p1, nullGrob(), p1, widths=c(0.45,0.1,0.45))

```