Search code examples
rggplot2ggplotlyreveal.jsquarto

R-stack layout graphs in Quarto


I would like to use the r-stack layout class in a Quarto presentation with ggplot and ggplotly output. For images we could use the following code like shown in the link above:

---
title: "r-stack with graphs in Quarto"
format: revealjs
---

## Example slide

::: {.r-stack}
![](image1.png){.fragment width="450" height="300"}

![](image2.png){.fragment width="300" height="450"}

![](image3.png){.fragment width="400" height="400"}
:::

Using the following code with r-stack class doesn't work:

---
title: "r-stack with graphs in Quarto"
format: revealjs
---

## Example slide

::: {.r-stack}

```{r}
library(ggplot2)
library(plotly)
p1 <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point()
ggplotly(p1)
```

```{r}
library(ggplot2)
library(plotly)
p2 <- ggplot(iris, aes(x = Petal.Length, y = Petal.Width)) +
  geom_point()
ggplotly(p2)
```

:::

Output:

enter image description here

Nothing happens. So I was wondering if anyone knows how to use the r-stack class with ggplotly graphs like it is possible with the images?


Solution

  • According to the docs .r-stack

    is intended to be used together with fragments to incrementally reveal elements.

    Hence, to make .r-stack work you have wrap your plots in fragements.

    Note: I used different widths and heights to make the stacking of the plots visible.

    ---
    title: "r-stack with graphs in Quarto"
    format: revealjs
    ---
    
    ## Example slide
    
    ```{r}
    library(ggplot2)
    library(plotly)
    ```
    
    ::: {.r-stack}
    
    ::: {.fragment}
    ```{r fig.width=4, fig.height=5}
    p1 <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
      geom_point()
    ggplotly(p1)
    ```
    :::
    
    ::: {.fragment}
    ```{r fig.width=5, fig.height=4}
    p2 <- ggplot(iris, aes(x = Petal.Length, y = Petal.Width)) +
      geom_point()
    ggplotly(p2)
    ```
    :::
    
    :::
    

    enter image description here