Home > OS >  Include transparent ggplot in Quarto / Rmarkdown without saving to disk
Include transparent ggplot in Quarto / Rmarkdown without saving to disk

Time:12-17

I can include a ggplot2 figure in a Quarto document with a transparent background if I first use ggplot2::ggsave(bg = "transparent"). How can I do this without having to save the image to disk?

---
title: "test"
theme: darkly
---

```{r, echo = FALSE}
p <- ggplot2::ggplot()  
  ggplot2::geom_tile(data = data.frame(x = 1, y = 1),
                     ggplot2::aes(x = x, y = y))  
      ggplot2::theme_void()  
   ggplot2::theme(
    panel.background = ggplot2::element_rect(fill='transparent'), #transparent panel bg
    plot.background = ggplot2::element_rect(fill='transparent', color=NA), #transparent plot bg
    panel.grid.major = ggplot2::element_blank(), #remove major gridlines
    panel.grid.minor = ggplot2::element_blank(), #remove minor gridlines
    legend.background = ggplot2::element_rect(fill='transparent'), #transparent legend bg
    legend.box.background = ggplot2::element_rect(fill='transparent') #transparent legend panel
  )

```


# Non transparent background
```{r}
p
```

# Transparent background 

```{r}

path <- here::here("test.png")

suppressMessages(
  ggplot2::ggsave(
    plot = p,
    path = dirname(path),
    filename = basename(path),
    bg = "transparent",
    height = 4,
    scale = 2,
    dpi = 300,
    units = "in"
  )
)
  
knitr::include_graphics(path)

```

CodePudding user response:

Using this should work:

```{r, dev = "png", dev.args=list(bg="transparent")}
p
```

See here for a complete set of options for plots in RMarkdown.

  • Related