【问题标题】:RMarkdown plot inserted into Word with 101% width and heightRMarkdown 图以 101% 的宽度和高度插入 Word
【发布时间】:2018-06-14 10:54:52
【问题描述】:

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

示例

这个简短的 .Rmd 文件:

---
output:
  word_document

---

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

编织到这个:

然后我右键单击它,选择 Properties 并看到它以原始大小的 101% 插入(下面奇怪的语言是波兰语;))

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

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

我的尝试

(这些都不起作用)

  • 更改绘图大小(fig.widthfig.height 块选项)
  • 将 Word 中的默认单位从 cm 更改为 in
  • 更改用于绘图的设备及其结果(devres 块选项)

【问题讨论】:

  • 我进行了一些测试,发现这是pandoc 问题,而不是rknitr 问题。我在问题中添加了pandoc 标签。
  • 你的pandoc是什么版本?

标签: r ms-word r-markdown knitr pandoc


【解决方案1】:

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

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

链接属性是最近的pandoc 功能,在pandoc 1.16 中引入。 knitr 尚不支持,但根据上述功能要求将很快支持。

只要knitr不支持pandoc链接属性,这里有一个hacky提案来解决这个问题。它使用knitrplot 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 标头中的keep_md 选项检查此中间markdown 文件:

---
output: 
  word_document:
    keep_md: true
---

knitr 的可用版本中,指向图像的链接由knitr 呈现,如下所示:

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

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

建议的knitr plot hook 为链接添加宽度和高度属性。
它返回以下markdown

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

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

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

【讨论】:

  • 几乎完美 ;) 您的代码只允许在 fig.width 和 fig.height 中使用整数。尝试 fig.width=4.5 会导致 spritnf 函数出错。
  • @ŁukaszDeryło 我已将%i 更改为%s。你还好吗?
  • 现在非常完美:D
猜你喜欢
  • 1970-01-01
  • 2017-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多