+r +ggplot +jpeg +backgroud +transparent

Viewed 444

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")
2 Answers

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

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.

Related