Issue with reading a PNG from URL and adding element to patchwork plot

I’m trying to add an image/logo from a URL to the top corner of my plot which is created with the patchwork package. I’ve tried following the method suggested in another post, but I’m getting an error (displayed below) when using inset_element().

my_image is contained as a large array in my environment once I run the readPNG() function, and I’m presuming this is where the issues lies. Some assistance will be greatly appreciated. Thanks.

library(tidyverse)
#> Warning: package 'tibble' was built under R version 4.0.5
#> Warning: package 'tidyr' was built under R version 4.0.5
#> Warning: package 'readr' was built under R version 4.0.5
#> Warning: package 'dplyr' was built under R version 4.0.5
library(patchwork)
library(RCurl)
#> Warning: package 'RCurl' was built under R version 4.0.5
#> 
#> Attaching package: 'RCurl'
#> The following object is masked from 'package:tidyr':
#> 
#>     complete

dat <- data.frame(
  x = 1:10,
  y = 1:10
)

list_of_url_logos <- cfbfastR::cfbd_team_info() %>%
  select(school, logo)

my_url <- head(list_of_url_logos$logo, 1)

my_image <-  png::readPNG(getURLContent(my_url))


p1 <- ggplot(dat, aes(x = x, y = y)) +
  geom_point()

p2 <- ggplot(dat, aes(x = x, y = y)) +
  geom_line()

p1 / p2 +
  inset_element(my_image, left = 0.6, bottom = 0.6, right = 1, top = 1, align_to = "full")
#> Error in UseMethod("as_patch"): no applicable method for 'as_patch' applied to an object of class "c('array', 'double', 'numeric')"

Created on 2023-01-18 with reprex v2.0.2

>Solution :

One option to fix your issue would be to convert your raster image to a grob using grid::rasterGrob.

As I wasn’t able to run code as I lack the necessary API key for cfbfastR::cfbd_team_info() let’s first reproduce your issue with the R logo:

library(tidyverse)
library(patchwork)
library(RCurl)

dat <- data.frame(
  x = 1:10,
  y = 1:10
)

myurl <- "https://www.r-project.org/logo/Rlogo.png"
my_image <-  png::readPNG(getURLContent(myurl))

p1 <- ggplot(dat, aes(x = x, y = y)) +
  geom_point()

p2 <- ggplot(dat, aes(x = x, y = y)) +
  geom_line()

p1 / p2 +
  inset_element(my_image, left = 0.6, bottom = 0.6, right = 1, top = 1, align_to = "full")
#> Error in UseMethod("as_patch"): no applicable method for 'as_patch' applied to an object of class "c('array', 'double', 'numeric')"

Now, converting to a raster grob gives the desired result:

p1 / p2 +
  inset_element(grid::rasterGrob(my_image), left = 0.6, bottom = 0.6, right = 1, top = 1, align_to = "full")

enter image description here

Leave a Reply