解决ggplot2中添加经magick旋转的透明PNG的显示异常问题
问题:patchwork插入透明PNG失效及旋转PNG显示异常
使用ggplot2::annotation_custom()可以正常为ggplot图形添加带透明背景的PNG图片,但patchwork::inset_element()无法保留图片的透明效果;同时,经magick::image_rotate()旋转后的PNG图片在添加时会出现显示异常。
注:本问题并非以下内容的重复,异常问题由图片旋转操作导致:
- R/ggplot2: 添加带透明信息的PNG
- 使用ggplot2生成高分辨率透明背景图
可复现代码如下:
library(magick) library(patchwork) library(tidyverse) url <- "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d0/RStudio_logo_flat.svg/2560px-RStudio_logo_flat.svg.png" img <- magick::image_read(url) %>% grid::rasterGrob() img_rot <- magick::image_read(url) %>% magick::image_rotate(30) %>% grid::rasterGrob() ggplot(tibble(x = 1:3)) + aes(x = x, y = x) + geom_point() + coord_fixed() + ggplot2::annotation_custom(img, 1, 2, 2, 3) + ggplot2::annotation_custom(img_rot, 2, 3, 2, 3) + patchwork::inset_element(img, 0, 0, 0.5, 0.5) + patchwork::inset_element(img_rot, 0.5, 0, 1, 0.5)
显示效果:
解决方案
1. 修复patchwork::inset_element()的透明背景问题
使用grid::rasterGrob()时需显式指定interpolate = TRUE,确保图片的alpha透明通道被正确识别:
img <- magick::image_read(url) %>% grid::rasterGrob(interpolate = TRUE)
2. 修复旋转后图片的显示异常问题
图片旋转后会自动生成白色填充背景,需通过image_transparent()移除该背景,同时保留透明通道:
img_rot <- magick::image_read(url) %>% magick::image_rotate(30) %>% magick::image_transparent("white") %>% # 移除旋转产生的白色背景 grid::rasterGrob(interpolate = TRUE)
完整修正代码
library(magick) library(patchwork) library(tidyverse) url <- "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d0/RStudio_logo_flat.svg/2560px-RStudio_logo_flat.svg.png" # 修正普通图片的rasterGrob参数 img <- magick::image_read(url) %>% grid::rasterGrob(interpolate = TRUE) # 修正旋转图片:移除白色背景+指定interpolate img_rot <- magick::image_read(url) %>% magick::image_rotate(30) %>% magick::image_transparent("white") %>% grid::rasterGrob(interpolate = TRUE) ggplot(tibble(x = 1:3)) + aes(x = x, y = x) + geom_point() + coord_fixed() + ggplot2::annotation_custom(img, 1, 2, 2, 3) + ggplot2::annotation_custom(img_rot, 2, 3, 2, 3) + patchwork::inset_element(img, 0, 0, 0.5, 0.5) + patchwork::inset_element(img_rot, 0.5, 0, 1, 0.5)
修改后,inset_element()可正常显示透明背景,旋转后的图片也不会出现白色背景遮挡问题。
内容的提问来源于stack exchange,提问作者Paul Schmidt
相关产品推荐
相关产品推荐

