本文介绍了如何使用ggplot2在R中使用透明背景制作图形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我需要将R的ggplot2图形输出为具有透明背景的PNG文件。 d #this返回透明png png('tr_tst1.png',width = 300,height = 300,units =px,bg =transparent) boxplot (d) dev.off() df p p panel.background = theme_rect(fill =transparent,color = NA),#或theme_blank() panel.grid.minor = theme_blank(), panel.grid.major = theme_blank()) #returns白色背景 png('tr_tst2.png', width = 300,height = 300,units =px,bg =transparent)p dev.off() 有没有办法通过ggplot2获取透明背景? 除了 panel.background :以外,还有一个 plot.background 选项。 df p p panel.background = theme_rect(fill =transparent,color = NA),#or theme_blank() panel.grid.minor = theme_blank(), panel.grid.major = theme_blank(), plot.background = theme_rect(fill =transparent,color = NA))#返回白色背景 png('tr_tst2.png',width = 300,height = 300,units =px,bg =transparent) print(p) dev.off() 由于某些原因,上传的图像与我的电脑显示的不一样,所以我省略了它。但是对我来说,除了箱子里仍然是白色的箱子外,我会得到一个完全灰色的背景。我相信这可以通过boxplot geom中的填充美学来改变。 编辑 ggplot2 已被更新,并且 opts()函数已被弃用。目前,您可以使用 theme()来代替 opts()和 element_rect()而不是 theme_rect()等。 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 pngpng('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 backgroundpng('tr_tst2.png',width=300,height=300,units="px",bg = "transparent")pdev.off()Is there any way to get transparent background with ggplot2? 解决方案 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 backgroundpng('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.Editggplot2 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. 这篇关于如何使用ggplot2在R中使用透明背景制作图形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-29 04:27