简体   繁体   中英

Plot zoom with ggmap roadmap and geom_polygon

I want to add county lines to a google roadmap from ggmap . I'm using the county lat/lon data from from ggplot2 . The map is zoomed in to a smaller region than the entire county polygon. Normally, when I am plotting a portion of a polygon, I would generate the whole polygon and then zoom in via coord_map

The problem here is that the google roadmap does not resize.

library(tidyverse)
library(ggmap)

king <- map_data('county') %>% filter(region == 'washington', subregion == 'king')


bbox <- ggmap::make_bbox(lon = king$long, lat = king$lat, f = 0)
county_map <- ggmap::get_map(location = bbox, maptype = "roadmap", source = "google", zoom = calc_zoom(bbox) - 1)
county_map <- ggmap::ggmap(county_map)

c_map <- county_map + geom_polygon(data = king, aes(x = long, y = lat), fill = NA, color = 'blue')


c_map + coord_map(xlim = c(-122.4, -122),ylim = c(47.5, 47.9))

在此处输入图片说明

If I instead get the zoomed in roadmap from the start, I run into the problem of the polygon getting clipped and scrambled.

bbox2 <- ggmap::make_bbox(lon = c(-122.4, -122), lat = c(47.5, 47.9), f = 0)
county_map2 <- ggmap::get_map(location = bbox2, maptype = "roadmap", source = "google", zoom = calc_zoom(bbox2) - 1)
county_map2 <- ggmap::ggmap(county_map2) + coord_map(xlim = c(-122.4, -122),ylim = c(47.5, 47.9))

county_map2 + geom_polygon(data = king, aes(x = long, y = lat), fill = NA, color = 'blue')

在此处输入图片说明

So I'm trying to get the county line from the top plot onto the bottom plot. Thanks!

** Edit: Duplicate of linked post

The post I flagged as a duplicate does seem to answer your question.

ggmap(county_map2, base_layer=ggplot(aes(x=long,y=lat), data=king),
      extent = "normal", maprange=FALSE) +
  geom_polygon(aes(x = long, y = lat),
               data = king, colour = 'blue', fill = NA, alpha = .5) +
  coord_map(projection="mercator", 
            xlim=c(attr(county_map2, "bb")$ll.lon, attr(county_map2, "bb")$ur.lon),
            ylim=c(attr(county_map2, "bb")$ll.lat, attr(county_map2, "bb")$ur.lat)) +
  theme_nothing()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM