我需要将ggplot2图形从R输出到背景透明的PNG文件.基本R图形一切正常,但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 transparent background with ggplot2?

推荐答案

更新了theme()函数、ggsave()和图例背景代码:

df <- data.frame(y = d, x = 1, group = rep(c("gr1", "gr2"), 50))
p <- ggplot(df) +
  stat_boxplot(aes(x = x, y = y, color = group), 
               fill = "transparent" # for the inside of the boxplot
  ) 

最快的方法是使用rect,因为所有矩形元素都继承自rect:

p <- p +
  theme(
        rect = element_rect(fill = "transparent") # all rectangles
      )
    p

更可控的方法是使用theme个选项:

p <- p +
  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
  )
p

要保存(最后一步很重要):

ggsave(p, filename = "tr_tst2.png",  bg = "transparent")

R相关问答推荐

以R表示的gglikert地块调整总数

R形式的一维数字线/箱形图样式图表

根据列表中项目的名称多次合并数据框和列表

如何根据组大小应用条件过滤?

如何编辑gMarginal背景以匹配绘图背景?

使用整齐的计算(curl -curl )和杂音

在R中使用Scale_y_Break后更改y轴标签

R中的哈密顿滤波

仅在Facet_WRAP()中的相应方面包含geom_abline()

如何在R中平滑地绘制线图(不拟合)?

计算直线上点到参考点的总距离

R -使用矩阵reshape 列表

扩展R中包含列表的数据框

创建列并对大型数据集中的特定条件进行成对比较的更高效程序

我如何使用tidyselect来传递一个符号数组,比如Pivot_Long?

在REST API中使用参数R

从矩阵创建系数图

从字符串01JAN2021创建日期

在具有条件的循环中添加行

GgHighlight找不到它创建的列:`Highlight..1`->;`Highlight.....`