Question

Can I force a ggplot to an A4 word page without changing fig.height, fig.width and dpi parameters?

Given the same ggplot with two different fig.height/fig.width chunk header configurations one can see that the outputs look different. The points in Plot 2 are more conjested and the fonts are bigger. For Plot 1 the opposite is the case.

I'm looking for a programmatic solution to produce Plot 1 and keep it in the given A4 boundaries (theoretically I can manually reduce the size when the word doc is open). I'm showing Plot 2 to clarify that adjusting fig.height/fig.width will not produce the desired output. Also dpi must be 600.

---
output:
  officedown::rdocx_document:
    base_format: "rmarkdown::word_document"
---

# Plot 1

```{r, fig.height = 10, fig.width = 10, echo = FALSE, message = FALSE, dpi = 600}
library(officedown) # 0.3.0
library(ggplot2) # 3.4.2

df <- data.frame(A = sample(1000), B = sample(1000), size = sample(1000))

ggp <- ggplot(data = df, aes(x = A, y = B, size = size)) +
  geom_point()

ggp
```

# Plot 2

```{r, fig.height = 7, fig.width = 7, echo = FALSE, message = FALSE, dpi = 600}
ggp
```
 3  56  3
1 Jan 1970

Solution

 1

Not as clean as it could be but its possible to save the desired ggplot with ggsave() where height and width can be set in ggsave() as required. This static image can then be included via knitr::include_graphics() and sized to A4 dimensions using the chunk options fig.height/fig.width.

---
output:
  officedown::rdocx_document:
    base_format: "rmarkdown::word_document"
---

# Plot

```{r, fig.height = 7, fig.width = 7, echo = FALSE, message = FALSE, dpi = 600}
library(officedown) # 0.3.0
library(ggplot2) # 3.4.2

df <- data.frame(A = sample(1000), B = sample(1000), size = sample(1000))

ggp <- ggplot(data = df, aes(x = A, y = B, size = size)) +
  geom_point()

ggsave("my_ggplot.png", plot = ggp, dpi = 600, height = 10, width = 10)
knitr::include_graphics("my_ggplot.png")
```

Note that non-square images also need to set an appropriate fig.asp (e.g. height/width = 0.6) to prevent unwanted distortion. For the above example it would thus also be possible to only set fig.width = 7 and fig.asp = 1.

---
output:
  officedown::rdocx_document:
    base_format: "rmarkdown::word_document"
---

# Plot

```{r, fig.width = 7, fig.asp = 0.6, echo = FALSE, message = FALSE, dpi = 600}
library(officedown) # 0.3.0
library(ggplot2) # 3.4.2

df <- data.frame(A = sample(1000), B = sample(1000), size = sample(1000))

ggp <- ggplot(data = df, aes(x = A, y = B, size = size)) +
  geom_point()

ggsave("my_ggplot.png", plot = ggp, dpi = 600, height = 6, width = 10)
knitr::include_graphics("my_ggplot.png")
```
2024-07-23
Patrick