如何在ggmap上叠加纽约NTA边界Shapefile?解决相关报错
在ggmap上叠加纽约NTA边界Shapefile的解决方法
问题背景
尝试将纽约曼哈顿的NTA(社区制表区)边界Shapefile叠加到ggmap上,原代码如下:
nta_shp <- st_read('geo_export_de8807a0-e424-4399-95ee-3f8bcc187b7a.shp') nta_shp <- nta_shp[nta_shp$boro_name=="Manhattan",] mh_bb <- getbb("manhattan new york usa") mh_bb[1] <- -74.04 mh_bb[2] <- 40.65 mh_map <- get_map(mh_bb, source="google", zoom=12, scale=2) ggmap(mh_map) + geom_sf(data=nta_shp, aes(geometry=geometry), color="#5e5f61", alpha=.2)
运行后出现报错:
Coordinate system already present. Adding new coordinate system, which will replace the existing one. Error in FUN(X[[i]], ...) : object 'lon' not found
所用nta_shp数据信息:
Simple feature collection with 6 features and 7 fields Geometry type: MULTIPOLYGON Dimension: XY Bounding box: xmin: -74.01638 ymin: 40.71136 xmax: -73.9376 ymax: 40.81809 Geodetic CRS: WGS84(DD) boro_code boro_name county_fip ntacode ntaname shape_area 8 1 Manhattan 061 MN12 Upper West Side 34379942 17 1 Manhattan 061 MN21 Gramercy 7526916 33 1 Manhattan 061 MN32 Yorkville 13648288 37 1 Manhattan 061 MN09 Morningside Heights 20153942 38 1 Manhattan 061 MN11 Central Harlem South 14441228 44 1 Manhattan 061 MN24 SoHo-TriBeCa-Civic Center-Little Italy 25032679 shape_leng geometry 8 29160.21 MULTIPOLYGON (((-73.96003 4... 17 12096.89 MULTIPOLYGON (((-73.98239 4... 33 18190.98 MULTIPOLYGON (((-73.93805 4... 37 20749.50 MULTIPOLYGON (((-73.9521 40... 38 16624.46 MULTIPOLYGON (((-73.94177 4... 44 26855.03 MULTIPOLYGON (((-73.9926 40...
解决方法
报错核心是ggmap()与geom_sf()的兼容性问题,以及坐标系映射冲突。以下是修正后的代码和关键说明:
修正代码
library(ggmap) library(sf) # 读取并筛选曼哈顿NTA数据 nta_shp <- st_read('geo_export_de8807a0-e424-4399-95ee-3f8bcc187b7a.shp') nta_shp <- nta_shp[nta_shp$boro_name=="Manhattan",] # 获取地图边界并调整范围 mh_bb <- getbb("manhattan new york usa") mh_bb[1] <- -74.04 mh_bb[2] <- 40.65 # 获取谷歌地图底图 mh_map <- get_map(mh_bb, source="google", zoom=12, scale=2) # 使用ggmap_sf替代ggmap,配合geom_sf绘制边界 ggmap_sf(mh_map) + geom_sf(data=nta_shp, color="#5e5f61", alpha=.2, inherit.aes = FALSE)
关键要点
- 用
ggmap_sf()替代ggmap():这是ggmap专为sf对象设计的绘图函数,能自动处理坐标系匹配,避免找不到lon的错误。 - 添加
inherit.aes = FALSE:ggmap的默认美学映射与sf不兼容,该参数可阻止继承无效的映射规则,解决冲突。 - 坐标系确认:你的nta_shp已经是WGS84(DD)坐标系(与谷歌地图一致),无需额外转换。若后续遇到坐标系不匹配,可使用
st_transform(nta_shp, 4326)强制转换为WGS84。
内容的提问来源于stack exchange,提问作者atatam_anukah
相关产品推荐
相关产品推荐

