简体   繁体   English

R/ggplot2:添加带有透明度信息的 png

[英]R/ggplot2: Add png with transparency info

I want to stack PNG images on a ggplot2 plot.我想在 ggplot2 绘图上堆叠 PNG 图像。 One of the pngs has alpha/transparency info, but it gets ignored.其中一个 png 具有 alpha/透明度信息,但它被忽略了。

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?如何在 bg.png 顶部添加第二个图像 (image1.png),以便保留透明度并且在黄色背景上仅显示黑色文本?

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:示例文件:

I think that the alpha channel is being respected here.我认为,alpha通道正在这里推崇。 It's just that inset_element draws a white canvas element first.只是inset_element绘制了一个白色的 canvas 元素。 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).我认为在这里使用ggplot2 annotation_custom更合适(意味着少加载一个包)。

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM