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

RGraphicsTransparencyGgplot2

R Problem Overview


I need to output ggplot2 graphics from R to PNG files with transparent background. Everything is ok with basic R graphics, but no transparency with ggplot2:

d <- rnorm(100) #generating random data

#this returns transparent png
png('tr_tst1.png',width=300,height=300,units="px",bg = "transparent")
boxplot(d)
dev.off()

df <- data.frame(y=d,x=1)
p <- ggplot(df) + stat_boxplot(aes(x = x,y=y)) 
p <- p + opts(
	panel.background = theme_rect(fill = "transparent",colour = NA), # or theme_blank()
	panel.grid.minor = theme_blank(), 
	panel.grid.major = theme_blank()
)
#returns white background
png('tr_tst2.png',width=300,height=300,units="px",bg = "transparent")
p
dev.off()

Is there any way to get transparent background with ggplot2?

R Solutions


Solution 1 - R

Updated with the theme() function, ggsave() and the code for the legend background:

df <- data.frame(y = d, x = 1, 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
  ) 

Fastest way is using using rect, as all the rectangle elements inherit from rect:

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

More controlled way is to use options of theme:

p <- p +
  theme(
    panel.background = element_rect(fill = "transparent"), # bg of the panel
    plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
    panel.grid.major = element_blank(), # get rid of major grid
    panel.grid.minor = element_blank(), # get rid of minor grid
    legend.background = element_rect(fill = "transparent"), # get rid of legend bg
    legend.box.background = element_rect(fill = "transparent") # get rid of legend panel bg
  )
p

To save (this last step is important):

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

Solution 2 - R

There is also a plot.background option in addition to panel.background:

df <- data.frame(y=d,x=1)
p <- ggplot(df) + stat_boxplot(aes(x = x,y=y)) 
p <- p + opts(
    panel.background = theme_rect(fill = "transparent",colour = NA), # or theme_blank()
    panel.grid.minor = theme_blank(), 
    panel.grid.major = theme_blank(),
    plot.background = theme_rect(fill = "transparent",colour = NA)
)
#returns white background
png('tr_tst2.png',width=300,height=300,units="px",bg = "transparent")
print(p)
dev.off()

For some reason, the uploaded image is displaying differently than on my computer, so I've omitted it. But for me, I get a plot with an entirely gray background except for the box part of the boxplot which is still white. That can be changed using the fill aesthetic in the boxplot geom as well, I believe.

Edit

ggplot2 has since been updated and the opts() function has been deprecated. Currently, you would use theme() instead of opts() and element_rect() instead of theme_rect(), etc.

Solution 3 - R

Just to improve YCR's answer:

  1. I added black lines on x and y axis. Otherwise they are made transparent too.

  2. I added a transparent theme to the legend key. Otherwise, you will get a fill there, which won't be very esthetic.

Finally, note that all those work only with pdf and png formats. jpeg fails to produce transparent graphs.

MyTheme_transparent <- theme(
    panel.background = element_rect(fill = "transparent"), # bg of the panel
    plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
    panel.grid.major = element_blank(), # get rid of major grid
    panel.grid.minor = element_blank(), # get rid of minor grid
    legend.background = element_rect(fill = "transparent"), # get rid of legend bg
    legend.box.background = element_rect(fill = "transparent"), # get rid of legend panel bg
    legend.key = element_rect(fill = "transparent", colour = NA), # get rid of key legend fill, and of the surrounding
    axis.line = element_line(colour = "black") # adding a black line for x and y axis
)

Solution 4 - R

As for someone don't like gray background like academic editor, try this:

p <- p + theme_bw()
p

Solution 5 - R

The Cairo package can be used to save ggplots as images with transparent backgrounds. https://cran.r-project.org/web/packages/Cairo/Cairo.pdf

CaiorPNG(filename = "TEST.png", bg = "transparent")

ggplot(mtcars, aes(wt, mpg))+
   geom_point()+
   theme(panel.background = element_rect(fill = "transparent"),
      plot.background = element_rect(fill = "transparent", colour = NA))

dev.off()

Solution 6 - R

I believe this will work for those who are working within R Markdown and don't want to use ggsave to save a separate file.

You do the following, and just add this chunk option: {r, dev.args = list(bg = 'transparent')}:

ggplot(mtcars, aes(wt, mpg)) +
   geom_point() +
   theme(
     # makes background transparent:
     plot.background = element_rect(fill = "transparent",colour = NA),
     # gets rid of white border around plot: 
     panel.border = element_blank() 
   )

For example, I am using ioslides presentation within R Markdown, though note that I have not tested this outside of this context.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYuriy PetrovskiyView Question on Stackoverflow
Solution 1 - RYCRView Answer on Stackoverflow
Solution 2 - RjoranView Answer on Stackoverflow
Solution 3 - RRtistView Answer on Stackoverflow
Solution 4 - RQinsiView Answer on Stackoverflow
Solution 5 - RSaraView Answer on Stackoverflow
Solution 6 - RmvanamanView Answer on Stackoverflow