Home > OS >  R/ggplot2: Add png with transparency info
R/ggplot2: Add png with transparency info

Time:10-27

I want to stack PNG images on a ggplot2 plot. One of the pngs has alpha/transparency info, but it gets ignored.

How can I add the second image (image1.png) on top of bg.png, so that transparency gets preserved and only the black text is visible on the yellow background?

Example

library(ggplot2)
library(png)
library(patchwork)

img1 <- readPNG("bg.png", native = TRUE)
img2 <- readPNG("image1.png", native = TRUE)

ggp <- ggplot(data.frame())  
  geom_point()   
  theme_nothing()  
  inset_element(p = img1,
                left = 0,
                bottom = 0,
                right = 1,
                top = 1,
                align_to = "full")  
  inset_element(p = img2,
                left = 0,
                bottom = 0,
                right = 0.5,
                top = 0.5,
                align_to = "full")

ggp

Example files:

  • bg.png: enter image description here

  • Related