Reputation: 311
I have a list of ggplot objects that I want to place a logo onto in the same relative position without having to specify new x,y coordinates for when the axes are different.
The application of grid::grid.raster()
is exactly how I want it to perform, but I can't sort out how to apply it to objects in my list and not my open graphics device.
annotate_custom()
& annotate_raster()
(as far as I can tell) will require me to set positioning according to the data for each plot which is not ideal.
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?
Ideally each plot would now have that image overlaid on it. But, currently what is happening is the image is overlaid on the open plot and no list is returned.
I think I need to isolate the graphics device for each one, but I'm not sure, and may not.
Upvotes: 3
Views: 925
Reputation: 2698
Utilizing 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)
})
Upvotes: 0
Reputation: 24262
Here is a possibile solution:
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)
Upvotes: 3