在 RMarkdown/knitr 中绘制边距

Plot margins in RMarkdown/knitr

在 RStudio 中,我的绘图看起来很完美,但是当我通过 "knit HTML" 按钮生成 HTML 时,我的边距被切断了。

我正在使用基本图形包创建一个简单的条形图。

我有一个较大的下边距以容纳横跨 x-axis 的垂直标签,还有一个较宽的左边距以将 y-axis 标题保留在一些大数字的左侧,例如:

```{r set-graph-options}
par(mar = c(12, 6, 4, 2) + 0.1, mgp = c(4, 1, 0), las = 2)
```

x-axis和y-axislabels/titles都受到影响;使用默认的 mgp 设置,我的 ylab 设置看起来很好,但是如果值更大,它似乎会被推离 "canvas"(或 R 中的任何术语)。

我还注意到 knitr/rmarkdown 无法识别全局设置的 par() 选项。比如上面设置后,barplot(injury_top12, ylab = "Injuries")会识别marmgplas选项中的none,但是如果我把选项复制到barplot()调用自己,las = 2&mgp = c(4, 1, 0)开始工作,但mar仍然无法识别

我尝试使用命令 R -e "rmarkdown::render('Readme.Rmd')" 从命令行生成 HTML,但出现了同样的问题。

我使用的是 R Studio 0.98.1103,knitr 是 1.11,rmarkdown 是 0.8,OS 是 ubuntu linux.

Example.Rmd:

```{r echo = F, example-set-par}
library(knitr)
opts_knit$set(cache = FALSE, verbose = TRUE, global.par = TRUE)
par(mar = c(12, 6, 4, 2) + 0.1, mgp = c(4, 1, 0), las = 2)
d <- c("This is a longer than usual label" = 355,
       "Another quite long label" = 144,
       "A third longish label for a barplot" = 222)
```

Plot one depends on values set by `par()`:

```{r echo = F, example-plot-using-par}
barplot(d, ylab = "Arbitrary numbers")
```

Plot two explicitly sets options:

```{r echo = F, example-plot-with-explicit-options}
barplot(d, ylab = "Arbitrary numbers", mar = c(12, 6, 4, 2) + 0.1, mgp = c(4, 1, 0), las = 2)
```

当我编织这个 Rmd 文档时,第一个情节没有使用 par() 中设置的 lasmgp 选项。第二个情节确实如此,但 x-axis 标签被切断,y-axis 标题几乎完全被推出框架(y 的尾部略微可见)。

对于想要直接在评论和推文中隐藏答案的人,您的 .Rmd 文件应如下所示:

---
title: exemple
header of your Rmd
---

```{r}
library(knitr)
opts_knit$set(global.par = TRUE)
```
The important think in the previous chunk is  to put global.par=TRUE 

Plot one depends on values set by `par()`:

```{r}
par(mar=c(5,5,0,0)) #it's important to have that in a separate chunk
``` 
Now we just plot a point with the good margin set by the global `par()`

```{r}
plot(1,1,main="a plot with the margin as set globally")
```

如果您不想在输出中包含用于设置全局边距的代码,只需添加:

```{r,include=FALSE}
par(mar=c(5,5,0,0))
``` 

在您不想包含的块中。