从URL阅读PNG并将元素添加到拼接图时出现问题

wmvff8tz  于 2023-01-18  发布在  其他
关注(0)|答案(1)|浏览(98)

我尝试将一个来自URL的图像/徽标添加到使用patchwork包创建的绘图的右上角。我尝试按照another post中建议的方法操作,但在使用inset_element()时出现错误(如下所示)。
一旦我运行readPNG()函数,my_image就作为一个大数组包含在我的环境中,我推测这就是问题所在。

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')"

创建于2023年1月18日,使用reprex v2.0.2

ws51t4hk

ws51t4hk1#

解决此问题的一个方法是使用grid::rasterGrob将光栅图像转换为grob。
由于缺少cfbfastR::cfbd_team_info()所需的API密钥,我无法运行代码,让我们首先重现R徽标的问题:

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')"

现在,转换为栅格组将得到所需的结果:

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

相关问题