Home > Enterprise >  Add png to {ggplot2} that has transparent background and was rotated via {magick}
Add png to {ggplot2} that has transparent background and was rotated via {magick}

Time:08-30

While adding a transparent png to a ggplot works fine via ggplot2::annotation_custom() (but not via patchwork::inset_element), there seem to be problems when rotating the image via magick::image_rotate().

Find the reprex below. Does anyone have a solution for this?

NOTE: While there is some overlap, I do not consider this question to be a duplicate of R/ggplot2: Add png with transparency info or Transparent background graph with ggplot2 in high resolution, R, since the problem here seems to specifically arise due to the image rotation.

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)

Created on 2022-08-26 with reprex v2.0.2

CodePudding user response:

This doesn't really have anything to do with ggplot specifically. The rotate changes the size of the image but does not set the background transparent. The image will always have a rectangular shape. You need to set the background so magick knows what to fill in the newly created space with

img_rot <- magick::image_read(url) %>%
  magick::image_background("none") %>% 
  magick::image_rotate(30) %>% 
  grid::rasterGrob()
  • Related