Search code examples
rggplot2r-markdownpurrr

r - export plots in list to ppt in separate slides without including the index


I have prepared an .rmd file that contains the code below, and i'm trying to produce a .ppt using an .rmd in which I will have multiple slides based on the length of the list I have, that contains plots inside.

I have tried most of the solutions in related issues but none was able to solve my problem. I tried walk , for loops, using the invisible function, but none does the expected.

---
title: "test1"
output: powerpoint_presentation
date: "2023-04-12"
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(purrr)
library(ggplot2)
library(dplyr)

dt <- iris %>%
  group_by(Species) %>%
  tidyr::nest() %>%
  mutate(plots = pmap(list(data, Species, Species),
                      ~ ..1 %>% ggplot() + geom_point(aes(Sepal.Width, Sepal.Length)) + ggtitle(paste0(..2, "-", ..3))
                      )
         )
```

## Slide with R Output

```{r echo = FALSE}
walk(dt$plots, print)
```

```{r echo = FALSE, results = 'asis'}
walk(dt$plots, print)
```

```{r echo = FALSE, results = 'asis'}
print(dt$plots)
```

The last 3 chunks produce the desired format (image with no text), but they return only the first plot in a single slide.

The following chunk produces all 3 slides but with the index text visible on the slide (the idea is to make the graph full size on the slide without the text)

```{r echo = FALSE}
invisible( print(dt$plots))
```

Solution

  • One option would be to create a new slide when looping over your plots using cat and setting the chunk option results='asis'. Also note the the need to add two line breaks via \n\n:

    ---
    title: "test1"
    output: 
      powerpoint_presentation:
        keep_md: true
    date: "2023-04-12"
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = FALSE)
    library(purrr)
    library(ggplot2)
    library(dplyr)
    
    dt <- iris %>%
      group_by(Species) %>%
      tidyr::nest() %>%
      mutate(plots = pmap(list(data, Species, Species),
                          ~ ..1 %>% ggplot() + geom_point(aes(Sepal.Width, Sepal.Length)) + ggtitle(paste0(..2, "-", ..3))
                          )
             )
    ```
    
    ```{r echo = FALSE, results='asis'}
    iwalk(dt$plots, function(x, y) {
      cat("## Slide with R output\n\n")
      cat("Plot ", y, "\n\n")
      print(x)
      cat("\n\n")
    })
    ```
    

    enter image description here

    EDIT If you only want a slide with the chart but no text or title then you could do:

    Note: You could also set the fig.width in the chunk option to change the size of the plot, e.g. use fig.width=9 to set the width to 9 inches (which from my inspection is the width of the placeholder where the chart is placed).

    ```{r echo = FALSE, results='asis'}
    iwalk(dt$plots, function(x, y) {
      cat("---\n\n")
      print(x)
      cat("\n\n")
    })
    ```