如何使用grid.raster在列表中的每个ggplot对象上覆盖图像?

时间:2019-04-26 19:51:35

标签: r ggplot2 raster purrr

我有一个ggplot对象列表,我希望将徽标放置在相同的相对位置上,而不必为轴不同时指定新的x,y坐标。

grid::grid.raster()的应用正是我希望它执行的方式,但是我无法弄清楚如何将其应用到列表中的对象而不是我的开放式图形设备。

annotate_custom()annotate_raster()(据我所知)将要求我根据每个图的数据设置定位,这并不理想。

library(magick)
library(ggplot2)
library(grid)
library(purrr)

stock_image <- image_read_svg('http://jeroen.github.io/images/tiger.svg', width = 400)
print(stock_image)

#make a ggplot object for example
any_ggplot <- qplot(mtcars$hp, mtcars$mpg)

#make a list of them
plot_list <- rep(list(any_ggplot), 4)

#the goal is to put that image on all of them, and save the new plots in a list.

# I can do it once with grid.raster,
# And this is the preferred method because the scaling and position is consistent 
# even if the axes change
grid::grid.raster(stock_image, x = 0.5, y = 0.5, just = c('left', 'bottom'), width = unit(1.5, 'inches'))


# But I can't do it to the list
new_plot_list <- purrr::map(plot_list, function(x) {

  x
  grid::grid.raster(stock_image, x = 0.5, y = 0.5, just = c('left', 'bottom'), width = unit(1.5, 'inches'))


})

#Help?

理想情况下,现在每个情节都将图像覆盖在上面。但是,当前正在发生的情况是图像被覆盖在开放图上,并且没有返回列表。

我认为我需要为每个图形设备隔离一个图形设备,但是我不确定,也许不是。

2 个答案:

答案 0 :(得分:3)

这是一个可能的解决方案:

library(ggplot2)
library(purrr)
library(cowplot)
library(gridExtra)
library(magick)

stock_image <- image_read_svg('http://jeroen.github.io/images/tiger.svg', width = 400)

# Make 4 ggplot objects for example
any_ggplot1 <- qplot(mtcars$hp, mtcars$mpg)
any_ggplot2 <- qplot(mtcars$drat, mtcars$mpg)
any_ggplot3 <- qplot(mtcars$wt, mtcars$cyl)
any_ggplot4 <- qplot(mtcars$disp, mtcars$cyl)

# Make a list of them
plot_list <- list(any_ggplot1, any_ggplot2, any_ggplot3, any_ggplot4)

new_plot_list <- purrr::map(plot_list, function(x) {
    ggdraw() +
      draw_image(stock_image, x = 0.25, y = 0.25, scale=0.25) +
      draw_plot(x)
})

grid.arrange(grobs=new_plot_list)

enter image description here

答案 1 :(得分:0)

使用this post

img <- rasterGrob(stock_image, interpolate=TRUE, x = .5, y = .5, just = c('left', 'bottom'), width = unit(1.5, 'inches'))

any_ggplot +
  annotation_custom(img, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf)


new_plot_list <- purrr::map(plot_list, function(x) {
  x +
    annotation_custom(img, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf)
})