How to make graphics with transparent background in R using ggplot2?
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 a transparent background with ggplot2?
To make ggplot transparent background in ggplot2, you can use the plot.background argument in theme function as follows:
library("ggplot2")
d <- rnorm(100)
df <- data.frame(y=d,x=1)
p <- ggplot(df) + stat_boxplot(aes(x = x,y=y))
p <- p + theme(
panel.background = element_rect(fill = "transparent",colour = NA),
panel.grid.minor = element_blank(),
panel.grid.major = element_blank(),
plot.background = element_rect(fill = "transparent",colour = NA)
)
png('tr_tst.png',width=300,height=300,units="px",bg = "transparent")
print(p)
dev.off()
Output: