如何在R语言中在Shapefile图层上绘制坐标点?
解决ggplot添加陨石坐标点到世界地图的错误问题
错误原因
- 你将经纬度字段
lat和long转换为了factor(分类变量),而空间坐标需要是数值型,这导致coord_sf无法识别并计算坐标范围,触发报错。 - 绘图时
geom_point的aes里把x、y轴对应关系写反了:应该是x = long(经度),y = lat(纬度)。
解决方案
方案1:修正数据类型后用geom_point绘图
先把经纬度转回数值型,过滤无效的NA坐标,再正确映射坐标:
# 读取陨石数据,不要将lat/long转为factor;如果已经转了,执行下面两行转回数值型 MeteoriteData <- read.csv("C:/Users/ChaseDickson_/Desktop/College/AERO 689/Semester Project/Meteorite Landings.csv") MeteoriteData$lat <- as.numeric(as.character(MeteoriteData$lat)) MeteoriteData$long <- as.numeric(as.character(MeteoriteData$long)) # 过滤掉缺失坐标的行,避免绘图报错 MeteoriteData <- MeteoriteData[!is.na(MeteoriteData$lat) & !is.na(MeteoriteData$long), ] # 加载并转换世界地图坐标系 world <- st_read("C:/Users/ChaseDickson_/Desktop/College/AERO 689/Semester Project/TM_WORLD_BORDERS_SIMPL-0.3/TM_WORLD_BORDERS_SIMPL-0.3.shp") world <- st_transform(world, crs = 4326) # 正确绘图:x对应经度long,y对应纬度lat ggplot() + geom_sf(data = world) + geom_point(data = MeteoriteData, aes(x = long, y = lat), size = 1, color = "red") + theme_bw()
方案2:将陨石数据转为sf对象,用geom_sf绘图
这种方式更符合空间数据的处理逻辑,避免坐标映射错误:
# 读取并清理陨石数据 MeteoriteData <- read.csv("C:/Users/ChaseDickson_/Desktop/College/AERO 689/Semester Project/Meteorite Landings.csv") MeteoriteData$lat <- as.numeric(as.character(MeteoriteData$lat)) MeteoriteData$long <- as.numeric(as.character(MeteoriteData$long)) MeteoriteData <- MeteoriteData[!is.na(MeteoriteData$lat) & !is.na(MeteoriteData$long), ] # 将普通数据框转为sf空间对象,指定坐标系为4326(和世界地图一致) Meteorite_sf <- st_as_sf(MeteoriteData, coords = c("long", "lat"), crs = 4326) # 加载并转换世界地图 world <- st_read("C:/Users/ChaseDickson_/Desktop/College/AERO 689/Semester Project/TM_WORLD_BORDERS_SIMPL-0.3/TM_WORLD_BORDERS_SIMPL-0.3.shp") world <- st_transform(world, crs = 4326) # 绘图,直接用geom_sf加载空间点 ggplot() + geom_sf(data = world) + geom_sf(data = Meteorite_sf, size = 1, color = "red") + theme_bw()
内容的提问来源于stack exchange,提问作者Chase Dickson
相关产品推荐
相关产品推荐

