如何创建一个 Rmd 模板,允许 DOCX 和 HTML 进行吸引人的绘图输出?

问题描述 投票:0回答:2

运行下面的 Rmd 将返回漂亮的 HTML 输出。然而,在渲染 DOCX 时,绘图的分辨率并不吸引人。增加 dpi(例如增加到 600)会使 DOCX 中的字体尺寸太小,并使 HTML 变大。 HTML 可以通过调整

fig.width
fig.height
来修复,但 DOCX 中的字体大小问题仍然存在。我已经玩了一段时间了,正在努力寻找适用于两种输出的通用解决方案。

我希望能够让这两项工作“开箱即用”。我能做什么?

---
output:
  officedown::rdocx_document:
    base_format: "rmarkdown::word_document"
  bookdown::html_document2:
    toc: false
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, fig.topcaption = FALSE, warning = FALSE, message = FALSE, dpi = 100)

library(officedown) # 0.3.0
library(magrittr) # 2.0.3
library(ggplot2) # 3.4.2
library(plotly) # 4.10.4
```

```{r myplot}
ggp <- iris %>%
    ggplot(aes(x = Sepal.Length)) +
    geom_histogram(binwidth = 4, fill = "forestgreen", color = "white", alpha = 0.5) +
    theme_classic()

ggplotly(ggp)
```
r plotly r-markdown ggplotly officedown
2个回答
0
投票

我想我会添加一个条件语句,仅在输出为 html 时运行 ggplotly。

尝试将其添加到最后一个块中:

library(knitr)
    if(is_html_output()){
    plotly(ggp)
    }else{
    ggp
    }

0
投票

看来解决方案需要定制。与

ggplot2::theme()
一起创建可回收的
theme()
至少可以提供一些可扩展性。

---
output:
  officedown::rdocx_document:
    base_format: "rmarkdown::word_document"
  bookdown::html_document2:
    toc: false
---

```{r setup, include=FALSE}
is_html <- knitr::is_html_output()
knitr::opts_chunk$set(echo = FALSE, fig.topcaption = FALSE, warning = FALSE,
                      message = FALSE, dpi = 600)

if (is_html) {
  knitr::opts_chunk$set(fig.width = 1.3, fig.height = 1.0)
} else {
  knitr::opts_chunk$set(fig.width = 6.0, fig.height = 4.0)
}

library(officedown) # 0.3.0
library(magrittr) # 2.0.3
library(ggplot2) # 3.4.2
library(plotly) # 4.10.4

my_theme <- function() {
  theme(
    text = element_text(size = 60),
    axis.ticks.length = unit(0.6, "cm"),
    axis.line = element_line(size = 2),
    axis.ticks = element_line(size = 2)
  )
}

```

```{r myplot}
ggp <- iris %>%
  ggplot(aes(x = Sepal.Length)) +
  geom_histogram(binwidth = 4, fill = "forestgreen", color = "white", alpha = 0.5) +
  theme_classic()

if(is_html) {
  ggplotly(ggp)
} else {
  ggp <- ggp +
    my_theme()
  ggplotly(ggp) %>%
    config(displayModeBar = FALSE) # displayModeBar is superfluous in docx
}
```
© www.soinside.com 2019 - 2024. All rights reserved.