Table of Contents
To use a transparent background in ggplot2, you can add the argument alpha = 0 to your plot’s geom_ functions. This will allow the background of the plot to be transparent, allowing the underlying data to be seen. You can also use the theme_bw() function to switch to a white background with a transparent grid. This will make the plot easier to read while still allowing the data to be seen.
You can use the following syntax to create a transparent background in a plot in ggplot2:
p + theme( panel.background = element_rect(fill='transparent'), #transparent panel bg plot.background = element_rect(fill='transparent', color=NA), #transparent plot bg panel.grid.major = element_blank(), #remove major gridlines panel.grid.minor = element_blank(), #remove minor gridlines legend.background = element_rect(fill='transparent'), #transparent legend bg legend.box.background = element_rect(fill='transparent') #transparent legend panel )
If you decide to export the plot using ggsave(), be sure to specify that the background should be transparent:
ggsave('myplot.png', p, bg='transparent')
The following example shows how to use this syntax in practice.
Example: Use a Transparent Background in ggplot2
The following code shows how to create a simple grouped boxplot in ggplot2:
library(ggplot2) #make this example reproducible set.seed(1) #create dataset data <- data.frame(team=rep(c('A', 'B', 'C'), each=50), program=rep(c('low', 'high'), each=25), values=seq(1:150)+sample(1:100, 150, replace=TRUE)) #create boxplot ggplot(data, aes(x=team, y=values, fill=program)) + geom_boxplot()
We can use the following code to create a transparent background for the plot:
library(ggplot2) #make this example reproducible set.seed(1) #create dataset data <- data.frame(team=rep(c('A', 'B', 'C'), each=50), program=rep(c('low', 'high'), each=25), values=seq(1:150)+sample(1:100, 150, replace=TRUE)) #create boxplot p <- ggplot(data, aes(x=team, y=values, fill=program)) + geom_boxplot() + theme( panel.background = element_rect(fill='transparent'), plot.background = element_rect(fill='transparent', color=NA), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), legend.background = element_rect(fill='transparent'), legend.box.background = element_rect(fill='transparent') ) #display boxplot p
We can then export this plot to a PNG file, specifying that the background should be transparent in the exported image:
ggsave('grouped_boxplot.png', p, bg='transparent')
If I open this exported file on my computer, I can see that the background is indeed transparent: