R中是否有可加载建筑物轮廓底图的相关工具包?
实现思路
- 依托OpenStreetMap公开矢量建筑数据集,通过
osmdata包拉取目标区域的建筑轮廓矢量数据 - 所有空间数据统一使用WGS84地理坐标系,和你现有的经纬度点位坐标系完全匹配
- ggplot绘图时优先绘制建筑轮廓作为底图,再叠加家庭收入点位图层,保证点位显示在顶层
完整可运行代码
# 首次运行先安装依赖包 # install.packages(c("osmdata", "sf", "ggplot2")) # 加载依赖 library(osmdata) library(sf) library(ggplot2) # 构造测试数据 lat <- c(33.97463, 33.97458, 33.97460, 33.97520, 33.97403, 33.97607) long <- c(-117.9180, -117.9183 , -117.9185, -117.9186 , -117.9184, -117.9184) income <- c(15000, 30000, 50000, 20000, 30000, 100000) data <- as.data.frame(cbind(lat, long, income)) # 生成点位覆盖区域的边界框,扩边0.001避免建筑数据不全 bbox <- c( min(data$long) - 0.001, min(data$lat) - 0.001, max(data$long) + 0.001, max(data$lat) + 0.001 ) # 从OSM查询对应区域的建筑矢量数据 buildings <- opq(bbox = bbox) %>% add_osm_feature(key = "building") %>% osmdata_sf() # 叠加绘图 ggplot() + # 绘制建筑底图:浅灰填充、深灰细边框,可按需调整配色 geom_sf(data = buildings$osm_polygons, fill = "#f5f5f5", color = "#999999", linewidth = 0.2) + # 叠加收入点位 geom_point(data = data, aes(x = long, y = lat, colour = income), size = 2) + scale_color_stepsn(n.breaks = 5, colours = terrain.colors(5)) + # 限定显示范围和点位区域匹配 coord_sf(xlim = c(bbox[1], bbox[3]), ylim = c(bbox[2], bbox[4])) + theme_bw()
调整说明
- 要更贴近谷歌地图的白底建筑风格,可将
geom_sf的fill参数改为"white",color改为"#e5e5e5" - 若查询建筑数据为空,可适当调大bbox的扩边数值(当前为0.001,可改为0.002重试)
内容的提问来源于stack exchange,提问作者KC Ray
相关产品推荐
相关产品推荐

