johnnyg
johnnyg

Reputation: 129

Overlay geom_sf onto ggplot

I have a list of ggplots of simple ggplot line graphs based on a location. I created a list of ggplot maps to identify each of my locations and would like to overlay maps within the plot in the corner. Here is a simple example:

library(ggplot2)
library(rnaturalearth)
library(rnaturalearthdata)
library(dplyr)
library(ggthemes)

#create line plot
x <- c(1:10)
y <- c(10:19)
df <- data.frame(x=x,y=y)
p <- ggplot(data=df,aes(x=x,y=y))+geom_line()+ylim(0,20)+theme_bw()

#create map
world <- ne_countries(scale = "medium", returnclass = "sf")
India <- world%>%filter(admin=='India')

map <- ggplot()+
  geom_sf(data=India)+
  theme_map()

p
map

Example Plot Example Map

And here is what I would like to get: Goal figure

How would I do this within R and using my two lists of ggplots?

Upvotes: 0

Views: 440

Answers (1)

stefan
stefan

Reputation: 123783

One approach to achieve this using ggplot2 would be via annotation_custom. To this end you have to convert your map ggplot to a grob using ggplotGrob. To position the map you have to set the coordinates as absolute values using data coordinates:

library(ggplot2)
library(rnaturalearth)
library(rnaturalearthdata)
library(dplyr)
library(ggthemes)

p +
  annotation_custom(grob = ggplotGrob(map), xmin = 7.5, xmax = 10, ymax = 10)

A second approach would be to make use of patchwork::inset_element which allows to position the map via relative coordinates:

library(patchwork)

p +
  inset_element(map,
    left = unit(.75, "npc"), top = unit(.5, "npc"),
    bottom = unit(0, "npc") + unit(2, "mm"), right = unit(1, "npc") - unit(2, "mm")
  )

Finally, both approaches could be combined with e.g. purrr::map2 to loop over your lists of plots and corresponding maps like so:

plist <- list(p, p)
maplist <- list(map, map)

pmaplist <- purrr::map2(plist, maplist, ~ .x + inset_element(.y,
  left = unit(.75, "npc"), top = unit(.5, "npc"),
  bottom = unit(0, "npc") + unit(2, "mm"), right = unit(1, "npc") - unit(2, "mm")
))

Upvotes: 2

Related Questions