2017-04-11 147 views
0

我想为用作ggplot背景的rastergrob对象添加透明度。R - 为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添加α,无论是在annotation_custom。我一直在寻找一段时间。

+0

您是否尝试过使用数值?例如。而不是“红色”使用“#F5262688” – G5W

+0

好吧,我发现了函数“调整颜色”,可以转换我的载体的所有颜色透明等值。谢谢 ! – jakzr

+0

也许你可以发布自己的问题的答案,以便人们知道它已被回答。 – G5W

回答

0

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) 
0

我发现了一个可能的方式做到这一点是使用函数adjustcolor(),它的透明度“阿尔法”和你的颜色列表中的参数和返回的透明色