r - Plotting shape files with ggmap: clipping when shape file is larger than ggmap -


i having clipping problems when try combine ggmap shape files. example in kahle , wickham (2013: 158) works fine because raster image ggmap covers entire shape file. below example of happens when try plot shape file u.s. states on ggmap plot covers smaller area. ggmap shows new york city , want overlay borders u.s. states (just example). resulting map doesn't make sense. problem shape file gets clipped , ggplot connects unclipped points. below code. shape file here. showing last plot here.

how can solve problem?

path <- "path shapefile" library("ggmap") library("rgdal")  # shapefile states <- readogr(dsn = path, layer = "states") states_df <- fortify(states) # plot shapefile plot(states, lwd = 0.1) ggplot(states_df, aes(long, lat, group = group)) +     geom_polygon(colour = "black", fill = na, size = 0.1)   # combine ggmap shapefile map <- get_map("new york city", zoom = 10, source = "stamen") ggmap(map, extent = "device")  ggmap(map, extent = "device") +     geom_polygon(aes(long, lat, group=group), data = states_df, colour = "red", fill = na, size = 1) 

kahle, david , hadley wickham. 2013. “ggmap: spatial visualization ggplot2.” r journal 5(1):144–61.

enter image description here

here attempt. use gadm shapefiles, can directly import using raster package. subsetted shape file ny, nj , ct. may not have in end, better reduce amount of data. when drew map, ggplot automatically removed data points stay outside of bbox of ggmap image. therefore, did not have additional work. not sure shapefile used. but, gadm's data seem work ggmap images. hope helps you.

library(raster) library(rgdal) library(rgeos) library(ggplot2)  ### data (shapefile) <- getdata("gadm", country = "us", level = 1)  ### select ny , nj states <- subset(us, name_1 %in% c("new york", "new jersey", "connecticut"))  ### spdf df map <- fortify(states)  ## map mymap <- get_map("new york city", zoom = 10, source = "stamen")   ggmap(mymap) + geom_map(data = map, map = map, aes(x = long, y = lat, map_id = id, group = group)) 

enter image description here

if want lines, following after.

ggmap(mymap) + geom_path(data = map, aes(x = long, y = lat, group = group)) 

enter image description here


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

utf 8 - split utf-8 string into bytes in python -

javascript - Js, document.getElementById("ID").innerHTML, error -