Search code examples
rr-markdownknitrbeamer

How to create two plots from one chunk of code in a beamer presentation with RMarkdown?


I would like to create several plots from one chunk of R code in an RMarkdown document. The output format is beamer-presentation, I am knitting the document by hitting the knit buttom in RStudio. Here is a minimal example, where only one slide with one plot is created and the second plot is omitted. I would like to see two slides with one plot each.

---
title: "2 Plots"
output: beamer_presentation
---

# Slide with Plot
```{r cars, echo = TRUE, eval = TRUE}
plot(cars$speed)
plot(cars$dist)
```

Solution

  • You just need to output the code to start a new slide between the code for the plots. For example,

    ---
    title: "2 Plots"
    output: beamer_presentation
    ---
    
    # Slide with Plot
    ```{r cars, echo = -2, eval = TRUE}
    plot(cars$speed)
    knitr::asis_output("\n\n# slide 2\n")
    plot(cars$dist)
    ```
    

    Note that echo = -2 says not to echo the 2nd statement, which is the one that writes out the second slide title.

    I'd recommend writing a little function to wrap up the asis_output line so it's easier to type. For example,

    # Slide 3
    ```{r eval = TRUE, echo = c(-1,-3)}
    slide <- function(title)
      knitr::asis_output(paste("\n\n#", title, "\n"))
    plot(cars$speed)
    slide("Slide 4")
    plot(cars$dist)
    ```
    

    You may find that the asis_output doesn't work properly if it's in the middle of a for loop; see its help page for details.