R:创建 png 栅格列表,读入 grid.raster

R: Creating list of png rasters, reading into grid.raster

这个post与一个 I asked a couple days ago, and specifically to this 相关(我从中借用了下面的代码)。我觉得有必要提出一个新问题,因为这是一个新问题。

我正在尝试使用 geom_point 的自定义图像在 ggplot2 中绘制图形,然后将这些图像粘贴到图例中。但是,当我将图像栅格放入列表中,并在 grid.raster 中引用该列表的元素时,它会引发错误。有没有办法将 png 栅格存储在列表中,以便以后可以从 grid.raster 调用它们?这是一个例子...

library(png)
library(ggplot2)
library(grid)

# Get image
img <- readPNG(system.file("img", "Rlogo.png", package="png"))

# Grab online image
url <- "https://www.rstudio.com/wp-content/uploads/2014/06/RStudio-Ball.png"
destfile <- "myfile.png"
r_studio <- download.file(url, destfile, mode="wb")
r_studio <- readPNG("myfile.png")

# Put images in list    
image_list <- list(img, r_studio)

# Plot
p = ggplot(mtcars, aes(mpg, disp, colour = factor(vs))) + 
  geom_point() +
  theme(legend.key.size = unit(1, "cm"))

# Get ggplot grob
gt = ggplotGrob(p)
grid.newpage()
grid.draw(gt)


# Search using regular expressions
Tree = as.character(current.vpTree())
pos = gregexpr("\[key.*?\]", Tree)
match = unlist(regmatches(Tree, pos))

match = gsub("^\[(key.*?)\]$", "\1", match) # remove square brackets
match = match[!grepl("bg", match)]  # removes matches containing bg

# Loop through image list. Change the legend keys to images
for(i in 1:2){
 downViewport(match[i])
 grid.rect(gp=gpar(col = NA, fill = "white"))
 grid.raster(image_list[i], interpolate=FALSE)
 upViewport(0) 
}

当我 运行 最后一个循环时,出现以下错误

Error in UseMethod("as.raster") : 
 no applicable method for 'as.raster' applied to an object of class "list" 

我注意到将图像放入列表会将类型从双精度更改为列表,所以我猜这与它有关。

typeof(img)
[1] "double"
typeof(image_list[1])
[1] "list"

您收到该错误是因为您在执行 image_list[i] 时对 image_list 进行子集化的方式,您需要通过添加一对额外的 [] 来进一步深入,即,image_list[[i]]获取数组(图片)

library(png)
library(ggplot2)
library(grid)

# Get image
img <- readPNG(system.file("img", "Rlogo.png", package="png"))

# Grab online image
url <- "https://www.rstudio.com/wp-content/uploads/2014/06/RStudio-Ball.png"
destfile <- "myfile.png"
r_studio <- download.file(url, destfile, mode="wb")
r_studio <- readPNG("myfile.png")

#Create the object `img`: your example code above does not do this
img <- r_studio

# Put images in list    
image_list <- list(img, r_studio)

# Plot
p = ggplot(mtcars, aes(mpg, disp, colour = factor(vs))) + 
  geom_point() +
  theme(legend.key.size = unit(1, "cm"))

# Get ggplot grob
gt = ggplotGrob(p)
grid.newpage()
grid.draw(gt)

# Search using regular expressions
Tree = as.character(current.vpTree())
pos = gregexpr("\[key.*?\]", Tree)
match = unlist(regmatches(Tree, pos))

match = gsub("^\[(key.*?)\]$", "\1", match) # remove square brackets
match = match[!grepl("bg", match)]  # removes matches containing bg

# Loop through image list. Change the legend keys to images
for(i in 1:2){
 downViewport(match[i])
 grid.rect(gp=gpar(col = NA, fill = "white"))
 grid.raster(image_list[[i]], interpolate=FALSE)
 upViewport(0) 
}