在夸托/ Rmarkdown中包括透明ggplot,无需保存到磁盘

moiiocjp  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(125)

如果我第一次使用ggplot2::ggsave(bg = "transparent"),我可以在一个带有透明背景的夸托文档中包含一个ggplot2图形。如何在不将图像保存到磁盘的情况下完成此操作?

---
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

p

Transparent background


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

2ul0zpep1#

使用此方法应该可以:

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

查看此处了解RMarkdown中绘图的完整选项集。

相关问题