如何为zip_choropleth生成的地图添加邮政编码标签或参考地图
解决zip_choropleth的两个问题:添加邮编标签+修复参考地图
1. 添加邮政编码标签
zip_choropleth本质是ggplot2对象,直接叠加文本图层就能加标签,核心是拿到每个邮编区域的中心坐标,你可以用choroplethr内置的zip.regions数据集(自带每个邮编的经纬度中心),合并到你的数据后用geom_text/geom_label实现:
library(choroplethr) library(ggplot2) # 提取内置邮编区域的中心坐标 zip_centers <- zip.regions %>% select(region, longitude, latitude) %>% rename(zip = region) # 和你的数据框合并,匹配邮编 df_with_centers <- merge(df, zip_centers, by.x = "regions", by.y = "zip") # 生成地图并添加标签 zip_choropleth(df, county_zoom = X, title = "Title", legend = "legend", num_colors = 1) + coord_map() + geom_text(data = df_with_centers, aes(x = longitude, y = latitude, label = regions), size = 3, color = "black") # 可按需调整大小、颜色
如果内置数据里找不到你的邮编,也可以用sf包自己计算多边形中心:
library(sf) # 获取目标区域的邮编空间多边形 zip_sf <- get_zip_map(county_zoom = X) %>% st_as_sf() # 计算每个多边形的中心坐标 zip_sf$center <- st_centroid(zip_sf$geometry) zip_sf$longitude <- st_coordinates(zip_sf$center)[,1] zip_sf$latitude <- st_coordinates(zip_sf$center)[,2] # 合并到你的数据框 df_with_centers <- merge(df, zip_sf[,c("region", "longitude", "latitude")], by.x = "regions", by.y = "region")
2. 修复失效的reference_map参数
旧版本的reference_map = TRUE大概率因为依赖的地图服务(比如ggmap)停止维护失效了,现在可以用ggspatial包添加底图,示例代码如下:
library(ggspatial) # 生成基础填充地图 base_map <- zip_choropleth(df, county_zoom = X, title = "Title", legend = "legend", num_colors = 1) + coord_map() # 添加OpenStreetMap底图,把填充层放在上面 base_map + annotation_map_tile( type = "osm", # 可选"cartolight"等其他底图类型 cachedir = system.file("rosm.cache", package = "ggspatial") ) + geom_sf(data = get_zip_map(county_zoom = X) %>% st_as_sf(), aes(fill = value), inherit.aes = FALSE) + scale_fill_gradient(low = "white", high = "red") # 按需调整配色
注意coord_map()默认用WGS84坐标系,和annotation_map_tile兼容,不需要额外转换。
内容的提问来源于stack exchange,提问作者Namuel_S
相关产品推荐
相关产品推荐

