Add contextual (or arbitrary) map insets with ggma

2019-04-15 06:26发布

Good day,

Let's say I use library(ggmap) in R to make this map:

ggmap(get_map(location = c(lon = -81.38630, lat = 19.30340), source = "stamen", maptype = "terrain", zoom = 14))

Which gives:

enter image description here

How do I add a small contextual inset map to this image (probably near the top left?) to show the wider geographical area? In this small inset I'd like for it to have a box that outlines where the bigger map fits in.

Thank you for your help.

1条回答
干净又极端
2楼-- · 2019-04-15 07:03

Here is a possible solution based on the use of grid viewports.

library(ggmap)
library(grid)

map1 <- get_map(location = c(lon = -81.38630, lat = 19.30340), 
        maptype = "terrain", zoom = 14)
map2 <- get_map(location = c(lon = -81.38630, lat = 19.30340), 
        maptype = "terrain", zoom = 12)

p1 <- ggmap(map1)
g1 <- ggplotGrob(p1)
grid.draw(g1)

pushViewport( viewport(x=0.25, y=0.8, w=.3, h=.3) )
xy <- data.frame(x=c(-81.41,-81.41,-81.36,-81.36,-81.41), 
       y=c(19.33,19.28,19.28,19.33,19.33))
p2 <- ggmap(map2) + 
      geom_path(data=xy, aes(x,y), color="red", lwd=1) + 
      theme_void()
g2 <- ggplotGrob(p2)
grid.draw(g2)
grid.rect(gp=gpar(col="white", lwd=5))
popViewport()

enter image description here

查看更多
登录 后发表回答