如何在ggplot2地图中绘制SpatialLines类河流线要素并解决报错问题
解决方案
报错核心原因
ggplot2的绘图图层默认不支持直接传入sp体系的S4空间对象(SpatialLines/SpatialPolygons等),需要先转换为可识别的结构化数据框,或使用适配空间对象的专用绘图接口。
方案1:基于现有sp代码修改
无需额外转换为SpatialLinesDataFrame,使用broom包的tidy()函数即可直接将Spatial*对象转换为ggplot2可用的数据框:
- 安装并加载broom包
install.packages("broom") library(broom) library(ggplot2)
- 转换空间对象为tidy数据框
# 转换县界对象 counties_tidy <- tidy(counties) # 转换裁切后的河流SpatialLines对象 rivers_tidy <- tidy(rivers)
- 修改绘图代码,注意固定颜色不要放在
aes()映射内:
ggplot() + geom_path(data = counties_tidy, aes(x = long, y = lat, group = group), col = 'darkgreen') + geom_path(data = rivers_tidy, aes(x = long, y = lat, group = group), col = 'blue') + coord_equal() # 保证地理坐标比例正确
方案2:推荐使用sf包实现(R空间生态主流方案)
老旧的sp/rgdal/rgeos体系已经停止维护,现在推荐使用更简洁的sf包处理空间数据,天然适配ggplot2:
- 替换原有数据读取与处理逻辑
library(sf) library(ggplot2) library(dplyr) # 读取并处理县界数据 counties <- st_read('D:\\Shapefiles\\Counties\\tl_2020_us_county.shp') %>% filter(STATEFP == '46') %>% st_transform(3395) # 读取、处理并裁切河流数据 rivers <- st_read('D:\\Shapefiles\\Main_Rivers\\rs16my07.shp') %>% st_set_crs(4326) %>% # 原始数据为WGS84经纬度投影,对应EPSG:4326 st_transform(3395) %>% st_intersection(counties) # 直接完成范围内裁切
- 直接使用ggplot2的
geom_sf()图层绘图,无需手动转换坐标或设置group:
ggplot() + geom_sf(data = counties, fill = NA, color = "darkgreen") + geom_sf(data = rivers, color = "blue")
内容的提问来源于stack exchange,提问作者user8229029
相关产品推荐
相关产品推荐

