以 101% 的宽度和高度插入到 Word 中的 RMarkdown 图

RMarkdown plot inserted into Word with 101% width and height

就像在标题中一样:无论我从 RMarkdown 插入到 Word 中的图表多么花哨或简单,我都会得到一张高度和宽度为 101% 的图像。这很烦人,因为这会使情节看起来模糊。

例子

这个简短的 .Rmd 文件:

---
output:
  word_document

---

```{r, echo=F}
plot(1:100)
```

编织到这个:

然后我right-click在上面,selectProperties,看到它被插入了原始大小的101%(下面奇怪的语言是波兰语;) )

当我将它重置为 100% 时,它看起来好多了:

问题 如何强制 RMarkdown 插入宽度和高度为 100% 的绘图?

我试过的

(none 个作品)

首先请注意,当this knitr feature request实施时,您必须停止使用以下答案。

这个问题可以使用 pandoc link attributes 来解决。正如 pandoc 文档中所解释的,没有 link 属性“ 后备是查看图像文件中嵌入的图像分辨率和 dpi 元数据 ”(我认为麻烦来自于这种回退方法)。

Link 属性是最近的 pandoc 特性,在 pandoc 1.16 中引入。 knitr 尚不支持,但根据 above-mentioned 功能要求,很快就会支持。

只要knitr不支持pandoclink属性,这里有一个解决这个问题的hacky提议。它使用 knitr plot hook.

---
output: word_document
---

```{r setup, echo=FALSE}
default_plot_hook <- knitr::knit_hooks$get('plot')

knitr::knit_hooks$set(plot = function(x, options) {
  default_md <- default_plot_hook(x, options)
  link_attr <- sprintf("{width=%sin height=%sin}", options$fig.width, options$fig.height)
  sub("(!\[.*]\(.*\))", paste0("\1", link_attr), default_md)
})
```

```{r, echo=F}
plot(1:100)
```

说明
RMarkdown 文件 (.Rmd) 渲染过程的第一步是生成普通 markdown 文件 (.md)。 这是 knitr 的工作。

该过程的第二步是从这个 markdown 文件生成 word 文件 (.docx)。 这是pandoc的工作。

请注意,您可以使用 YAML header:

中的 keep_md 选项检查此中间 markdown 文件
---
output: 
  word_document:
    keep_md: true
---

使用 knitr 的可用版本,link 图像由 knitr 渲染,如下所示:

![](myreport_files/figure-docx/unnamed-chunk-1-1.png)<!-- -->

没有 link 属性,因此 pandoc 使用其后备方法确定图像的尺寸。

提议的 knitr plot hook 添加宽度和高度属性到 link。
它returns以下markdown

![](myreport_files/figure-docx/unnamed-chunk-1-1.png){width=5in height=4in}<!-- -->

因此,pandoc 根据这些属性而非后备方法确定图像的尺寸。

显然,要使用此提案,您的 pandoc 版本必须 >= 1.16。