Reputation: 5415
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:
Upvotes: 1
Views: 752
Reputation: 173813
I think that the alpha channel is being respected here. It's just that inset_element
draws a white canvas element first. What you are trying to do arguably isn't an inset, more of an annotation.
I think using annotation_custom
from ggplot2
is more appropriate here (and means one less package to load).
library(ggplot2)
library(png)
img1 <- grid::rasterGrob(readPNG("bg.png"))
img2 <- grid::rasterGrob(readPNG("image1.png"))
ggp <- ggplot(data.frame()) +
geom_point() +
theme_void() +
annotation_custom(img1) +
annotation_custom(img2, xmax = 0.5, ymax = 0.5)
ggp
Upvotes: 1