Способ наложения изображения на каждый объект ggplot в списке с помощью grid.raster? - PullRequest
1 голос
/ 26 апреля 2019

У меня есть список объектов 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 ]

3 голосов
/ 26 апреля 2019

Вот возможное решение:

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

0 голосов
/ 26 апреля 2019

Использование этот пост

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)
})
...