3

I'm trying to create a jpeg of a plot with a transparent background. I want to use the jpeg in powerpoint. I cannot get the transparency to work. When I insert the jpeg into a ppt, it still has a white background. Are there options I am missing?

library(tidyverse)
library(dplyr)
library(gridExtra)
df<-data.frame(x=1:5)
df$y<-df$x**2

pl<-ggplot(df,aes(x=x,y=x)) +
     geom_point()
pl
pl_for_jpeg<-pl+
   theme(axis.text.x = element_blank(),
        axis.text.y = element_blank(),
        axis.ticks = element_blank(),
        plot.margin = unit(c(0,0,0,0),'mm'),
        panel.background = element_rect(fill = "transparent", color=NA),
        panel.grid.major = element_blank(),
        plot.background =  element_rect(fill = "transparent", color=NA),
        
   )

pl_for_jpeg

ggsave("pl.jpeg",pl_for_jpeg,width=10, height = 7.5, units = "in",bg = "transparent")
Rich
  • 31
  • 1
  • 3
    Hello Rich, welcome to StackOverflow. As far as I know, `jpg` can't contain transparency. [link] https://www.quora.com/Can-a-JPEG-image-have-a-transparent-background?share=1 – Alexis Jul 17 '20 at 15:51
  • 1
    Alexis-thanks, that explains it. A png format will do the trick for me. – Rich Jul 17 '20 at 16:30

2 Answers2

2

This should be the answer:

ggsave("pl.png",pl_for_jpeg,width=10, height = 7.5, units = "in",bg = "transparent")

Just have to change the extension to png for example and voila! You'll se your graphic with a transparent background on a ppt.

enter image description here

Alexis
  • 2,104
  • 2
  • 19
  • 40
2

You aren't missing anything, the problem is with jpeg files: the format is made for photography, hence the files are usually square without backgroung transparency. Changing to another raster file format (like .png) or to a vector file (like .svg) should solve the problem.

In ggsave(), you just need to change the file extension. Alternatively, in base R, you can use the png(), tiff(), or bmp() functions.

Giulio Centorame
  • 678
  • 4
  • 19