控制两个 knitr 并排图之间的距离

Controlling distance between two knitr side-by-side plots

[与 相关]

我不知道如何按照 knitr 图形手册第 2 页 (http://yihui.name/knitr/demo/graphics/) 中的说明排列两个并排的图。我使用以下 MWE,输出如下。 我希望能够控制地块之间的距离 - 现在这两个地块彼此靠得太近了。 pdf 是在 RStudio 中生成的(Knit to PDF)。

我曾尝试篡改 par(mar = c(rep(5,4))),但没有成功。

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

```

您可以使用 layout 在两个地块之间添加可调整的 space。创建一个三区布局并使中间区空白。调整 widths 参数以在三个地块之间分配 space 的相对数量。

在下面的示例中,我还必须调整图边距设置 (par(mar=c(4,2,3,0))) 以避免出现 "figure margins too large" 错误,并且我将 fig.width 更改为 4 以获得更好的纵横比地块的比率。您可能需要使用块中的图形边距和图形参数来获得所需的绘图尺寸。

```{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)

```

如果你恰好想使用网格图形,可以使用类似的方法:

```{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))

```