Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting map on a plot using ggplot

If I want to plot a map on plot, I do this

library(ggplot2)
library(sf)
library(cowplot)
library(gridExtra)
library(raster)

df <- data.frame(x = 1980:1999, y = sample(1:20, 20, replace = T))
shp.dat <- getData('GADM', country='FRA', level=1)

shp.dat <- shp.dat %>% st_as_sf()

p <- ggplot(df, aes(x = x, y = y)) + geom_line() + ylim(0, 100)
p.shp <- ggplot() +  
        geom_sf(data = shp.dat, fill = ifelse(shp.dat$ID_1 == 1,"red", "grey")) 
inset_map <- ggdraw() + draw_plot(p, 0, 0, 1, 1) + draw_plot(p.shp, 0.5, 0.52, 0.5, 0.4) 
inset_map

enter image description here

Now I have four plots which I have plotted like this

  df <- data.frame(x = 1980:1999, 
                 y1 = sample(1:20, 20, replace = T), 
                 y2 = sample(1:20, 20, replace = T), 
                 y3 = sample(1:20, 20, replace = T), 
                 y4 = sample(1:20, 20, replace = T))


p1 <- ggplot(df, aes(x = x, y = y1)) + geom_line() + ylim(0, 100)
p2 <- ggplot(df, aes(x = x, y = y2)) + geom_line() + ylim(0, 100)
p3 <- ggplot(df, aes(x = x, y = y3)) + geom_line() + ylim(0, 100)
p4 <- ggplot(df, aes(x = x, y = y4)) + geom_line() + ylim(0, 100)

pp <- grid.arrange(p1, p2, p3, p4, ncol = 2)

For each plot, I want to add the map as an inset

inset_map <- ggdraw() + draw_plot(pp, 0, 0, 1, 1) + draw_plot(p.shp, 0.5, 0.52, 0.5, 0.4)

enter image description here

How can I show the map as an inset in each plot separately?

like image 837
89_Simple Avatar asked Apr 27 '26 19:04

89_Simple


1 Answers

You can apply the same code logic you used to generate the single inset_map, before passing the results to grid.arrange():

plot.list <- list(p1, p2, p3, p4)

plot.list %>%

  # add inset map to each plot in the list
  lapply(function(p) ggdraw() + 
           draw_plot(p, 0, 0, 1, 1) + 
           draw_plot(p.shp, 0.5, 0.52, 0.5, 0.4)) %>%

  # convert each plot in the list to grob
  lapply(ggplotGrob) %>%

  # arrange in grid, as before
  grid.arrange(grobs = ., ncol = 2)

plot

like image 150
Z.Lin Avatar answered Apr 30 '26 09:04

Z.Lin