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

前端 未结 2 1169
长发绾君心
长发绾君心 2021-02-09 10:00

I am having clipping problems when I try to combine ggmap with shape files. The example in Kahle and Wickham (2013: 158) works fine because the raster image from ggmap covers th

2条回答
  •  情话喂你
    2021-02-09 10:27

    I would check out this answer, it seems that ggmap as you expected doesn't handle polygon's in an ideal way when you zoom in, namely items not on the plot get truncated causing 'interesting' results with respect to the shape files.

    Polygons nicely cropping ggplot2/ggmap at different zoom levels

    # transform for good measure
    states <- spTransform(states,CRS("+datum=WGS84 +proj=longlat") )
    
    # combine ggmap with shapefile
    states_df <- fortify(states)
    
    # get your map
    map <-get_map("new york city", zoom = 10, source = "stamen")
    
    a <- ggmap(map, # this is where we get our raster
           base_layer=ggplot(aes(x=long, y=lat), data=states_df), # this defines the region where things are plotted
           extent = "normal",  # this won't work with device, you need normal (see examples in ggmap documentation)
           maprange=FALSE
           ) +
    coord_map( # use map's bounding box to setup the 'viewport' we want to see
      projection="mercator",
      xlim= c(attr(map, "bb")$ll.lon, attr(map, "bb")$ur.lon),
      ylim=c(attr(map, "bb")$ll.lat, attr(map, "bb")$ur.lat)
    ) +
    geom_polygon( # plot the polygon
      aes(x=long, y=lat,group=group), data =states_df, color = "red", fill=NA, size = 1)
    
    print(a)
    

    With output: enter image description here

    As a side note you might want to check out using the U.S. Census data for state maps, they seem to be of higher quality than the ESRI data set.

    ftp://ftp2.census.gov/geo/pvs/tiger2010st/tl_2010_us_state10.zip

    As a final note, there are issues with ggmap near the poles so I would also subset your data by the states you are interested in.

提交回复
热议问题