Search code examples
rggplot2backgroundtransparency

R - add transparency to rastergrob background of a ggplot


I'd like to add transparency to a rastergrob object used as a ggplot background.

Here is my code

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)

I could not add an alpha in the rastergrob , neither in annotation_custom. I've been searching for a while.


Solution

  • scales::alpha() is one option,

    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)