jakzr
jakzr

Reputation: 159

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.

Upvotes: 1

Views: 1851

Answers (2)

baptiste
baptiste

Reputation: 77096

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)

Upvotes: 1

jakzr
jakzr

Reputation: 159

I found out one possible way to do it is to use the function adjustcolor() that takes the parameter of transparency "alpha" And your list of colors and returns a list of transparent colors

Upvotes: 1

Related Questions