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

前端 未结 3 869
耶瑟儿~
耶瑟儿~ 2020-11-28 18:17

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:

         


        
3条回答
  •  渐次进展
    2020-11-28 18:59

    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.

提交回复
热议问题