How to make graphics with transparent background in R using ggplot2?

Create the initial plot:

library(ggplot2)
d <- rnorm(100)
df <- data.frame(
  x = 1,
  y = d,
  group = rep(c("gr1", "gr2"), 50)
)
p <- ggplot(df) + stat_boxplot(
  aes(
    x = x,
    y = y,
    color = group
  ), 
  fill = "transparent" # for the inside of the boxplot
)

The fastest way to modify the plot above to have a completely transparent background is to set theme()‘s rect argument, as all the rectangle elements inherit from rect:

p <- p + theme(rect = element_rect(fill = "transparent"))
          
p

A more controlled way is to set theme()‘s more specific arguments individually:

p <- p + theme(
  panel.background = element_rect(fill = "transparent",
                                  colour = NA_character_), # necessary to avoid drawing panel outline
  panel.grid.major = element_blank(), # get rid of major grid
  panel.grid.minor = element_blank(), # get rid of minor grid
  plot.background = element_rect(fill = "transparent",
                                 colour = NA_character_), # necessary to avoid drawing plot outline
  legend.background = element_rect(fill = "transparent"),
  legend.box.background = element_rect(fill = "transparent"),
  legend.key = element_rect(fill = "transparent")
)

p

ggsave() offers a dedicated argument bg to set the

Background colour. If NULL, uses the plot.background fill value from the plot theme.

To write a ggplot object p to filename on disk using a transparent background:

ggsave(
  plot = p,
  filename = "tr_tst2.png",
  bg = "transparent"
)

Leave a Comment