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

时间:2016-05-09 13:02:39

标签: r layout plot knitr r-markdown

[与Control alignment of two side-by-side plots in knitr相关]

我无法弄清楚如何在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)

```

enter image description here

1 个答案:

答案 0 :(得分:2)

您可以使用layout在两个图之间添加可调节空间。创建三图布局并将中间图设为空白。调整widths参数以分配三个图中的相对空间量。

在下面的示例中,我还必须调整绘图边距设置(par(mar=c(4,2,3,0)))以避免“数字边距太大”错误,并将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)

```

enter image description here

如果您碰巧想要使用网格图形,可以使用类似的方法:

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

```