ggplot 中的面板透明度

Panel transparency in ggplot

我希望我的输出 ggplot2 图形具有透明边框(面板)但白色(不透明)绘图背景。

我试过这两个选项

d <- rnorm(100)
df <- data.frame(y = d, x = 1)
p <- ggplot(df) + stat_boxplot(aes(x = x, y = y)) 
# first option
p <- p + theme(
  panel.background = element_rect(fill = "transparent", colour = NA), 
  panel.grid.minor = element_blank(), 
  panel.grid.major = element_blank()
)
# second option
# 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('plot.png', width = 300, height = 300, units = "px", bg = "transparent")
print(p)
dev.off()

但我得到的结果并不令人满意

好吧,诀窍很明显。我误解了面板和情节背景是什么。所以这个应该有效:

# third option
 p <- p + theme(
   panel.grid.minor = element_blank(), 
   panel.grid.major = element_blank(),
   plot.background = element_rect(fill = "transparent", colour = NA)
 )