Search code examples
rggplot2pngggpubr

change transparency of background image in ggplot


I have added a background image and how can I set alpha of background image to 0.5?

library(tidyverse)
library(png)
library(ggpubr)

tbl = tibble(x = runif(25),
          y = runif(25))

# read any image from computer for background
im = readPNG("temp.png")

ggplot(data = tbl, 
       aes(x = x, 
           y = y)) + 
  background_image(im) + 
  geom_point(color = "red",
             size = 5)


Solution

  • You will need to set the alpha before you make the plot

    Before:

    before

    im <- readPNG("example.image.png")
    im2 <- matrix(rgb(im[,,1],im[,,2],im[,,3], im[,,4] * 0.5), nrow=dim(im)[1]) ## you can change 0.5 to change the alpa
    

    You can then apply this:

    library(png)
    library(grid)
    library(tibble)
    
    ggplot(data = tbl, 
           aes(x = x, 
               y = y)) + 
      annotation_custom(rasterGrob(im2, 
                                   width = unit(1,"npc"), 
                                   height = unit(1,"npc")), 
                        -Inf, Inf, -Inf, Inf) +
      geom_point(color = "red",
                 size = 5)
    

    After: after