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

前端 未结 3 866
耶瑟儿~
耶瑟儿~ 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:57

    Just to improve YCR's answer:

    1) I added black lines on x and y axis. Otherwise they are made transparent too.

    2) I added a transparent theme to the legend key. Otherwise, you will get a fill there, which won't be very esthetic.

    Finally, note that all those work only with pdf and png formats. jpeg fails to produce transparent graphs.

    MyTheme_transparent <- theme(
        panel.background = element_rect(fill = "transparent"), # bg of the panel
        plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
        panel.grid.major = element_blank(), # get rid of major grid
        panel.grid.minor = element_blank(), # get rid of minor grid
        legend.background = element_rect(fill = "transparent"), # get rid of legend bg
        legend.box.background = element_rect(fill = "transparent"), # get rid of legend panel bg
        legend.key = element_rect(fill = "transparent", colour = NA), # get rid of key legend fill, and of the surrounding
        axis.line = element_line(colour = "black") # adding a black line for x and y axis
    )
    

提交回复
热议问题