1
votes

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)
```
2

2 Answers

2
votes

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.

1
votes

If you want the plots on separate slides you have to put the plots in separate chunks and slides:

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

# Slide with first Plot
```{r cars, echo = TRUE, eval = TRUE}
plot(mtcars$cyl)
```

# Slide with second Plot
```{r cars2, echo = TRUE, eval = TRUE}
plot(mtcars$hp)
```