Search code examples
rggplot2r-markdown

Faceting Charts in Word


I typically use R to create graphs with ggplot2, and they look fantastic when exported to PDF documents. However, I encounter an issue when trying to incorporate these graphs into Word documents. Specifically, I usually want to include up to four charts on one Word page, each taking up half of the page, as shown in the example below. enter image description here

When I export the charts as pictures and import them into Word, readability becomes a problem. For instance, the charts are not easily readable, especially on the titles of the axes themselves due to the reduced quality in Word,etc.

To address this problem, I now export charts directly from R to Word using the script provided below with Rmarkdown.

---
title: "Test graphs"
output: word_document
---

```{r setup, include=FALSE,echo=FALSE}
knitr::opts_chunk$set(echo = TRUE,
                      dpi = 900)

library(ggplot2)
set.seed(1234)

wdata = data.frame(
  sex = factor(rep(c("F", "M"), each=200)),
  weight = c(rnorm(200, 55), rnorm(200, 58)))

a <- ggplot(wdata, aes(x = weight))


```

```{r,echo=FALSE}


a + geom_bar(stat = "bin",
              color= "black", fill="red")
```

So now I want to reproduce four charts with this code as shown in the example below. The charts need to take up half of the page, with high quality.

Can anybody help me solve this problem?


Solution

  • With the chunk options: figh.height & fig.width we can define the size of the figures (in inches as unit). See knitr chunk options for more info.

    ---
    title: "Test graphs"
    output: word_document
    ---
    
    ```{r setup, include = FALSE, echo = FALSE}
    knitr::opts_chunk$set(echo = TRUE, 
                          dpi = 900)
    
    library(ggplot2)
    set.seed(1234)
    
    wdata = data.frame(
      sex = factor(rep(c("F", "M"), each = 200)),
      weight = c(rnorm(200, 55), rnorm(200, 58)))
    
    a <- ggplot(wdata, aes(x = weight))
    ```
    
    ```{r, fig.width = 3, fig.height = 2, message = FALSE, echo = FALSE}
    a + geom_bar(stat = "bin", color = "black", fill = "red")
    a + geom_bar(stat = "bin", color = "black", fill = "red")
    a + geom_bar(stat = "bin", color = "black", fill = "red")
    a + geom_bar(stat = "bin", color = "black", fill = "red")
    ```
    

    Does this help?