R - 为 ggplot 的 rastergrob 背景添加透明度

R - add transparency to rastergrob background of a ggplot

我想为用作 ggplot 背景的 rastergrob 对象添加透明度。

这是我的代码

library(ggplot2)
library(grid)
library(ggthemes)

reds <- c("brown", "red","orange","green","orange","red","brown","grey")
g <- rasterGrob(reds, width = unit(1, "npc"), height = unit(1,"npc"),interpolate = TRUE)
p <- ggplot(data = economics, aes(x = date, y = unemploy)) +
  annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf)+
  geom_line( alpha=1, color = "white", size = 0.5 ) +
  xlab("Years") + ylab("Unemployed [thousands]") +
  theme_base() + 
  theme(panel.background=element_blank(),
        plot.background=element_blank(),        
        line = element_line(colour="white")) +
  theme()

grid.newpage()

print(p, newpage = FALSE)

我无法在 rastergrob 中添加 alpha,在 annotation_custom 中也是如此。我一直在寻找一段时间。

我发现一种可行的方法是使用带有透明度参数的函数 adjustcolor() "alpha" 以及您的颜色列表和 returns 透明颜色列表

scales::alpha()是一个选项,

grid.newpage()
grid.text("background")

reds <- c("brown", "red","orange","green","orange","red","brown","grey")
grid.raster(scales::alpha(reds, 0.5), width = unit(1, "npc"), height = unit(1,"npc"),interpolate = TRUE)