Search code examples
htmlrlayoutquarto

Quarto not rendering figures properly inside a conditional statement


I am using quarto to create an html document. I want to have some side-by-side plots.

When I try to render side-by-side plots from inside of a conditional statement, quarto only renders the second plot. Below is a reproducible example.

---
title: "RenderTest"
format: html
---
library(tidyverse)

Straight-up plot - No Conditional

#| layout-ncol: 2
#| out-width: "50%"

ggplot(mtcars, aes(x = mpg, y = wt)) + geom_point()
ggplot(mtcars, aes(x = hp, y = disp)) + geom_point()

Now with conditional:

#| layout-ncol: 2
#| out-width: "50%"

test <- F

if(test){
  ggplot(mtcars, aes(x = mpg, y = wt)) + geom_point()
} else {
  ggplot(mtcars, aes(x = mpg, y = wt)) + geom_point()
  ggplot(mtcars, aes(x = hp, y = disp)) + geom_point()
}

This produces the following output:

enter image description here

You can see that inside the conditional, only the second plot gets displayed. I'm very confused. Is this a bug? Is there something fundamental I don't understand?


Solution

  • You should print the ggplot calls like this:

    ---
    title: "RenderTest"
    format: html
    ---
    
    ```{r}
    library(tidyverse)
    ```
    
    ```{r}
    #| layout-ncol: 2
    #| out-width: "50%"
    
    test <- FALSE
    
    if(test){
      ggplot(mtcars, aes(x = mpg, y = wt)) + geom_point()
    } else {
      print(ggplot(mtcars, aes(x = mpg, y = wt)) + geom_point())
      print(ggplot(mtcars, aes(x = hp, y = disp)) + geom_point())
    }
    ```
    

    Output:

    enter image description here