解决sf对象与自定义geom_point坐标格式不匹配致点不显示问题
解决sf地图上自定义点不显示的问题
1. 获取sf对象的坐标系
要查看sf对象的坐标参考系(CRS),直接调用st_crs()函数即可:
st_crs(nc)
运行后会输出类似EPSG: 4269的结果,这就是nc图层使用的坐标系(北美基准面1983的经纬度坐标系)。
2. 转换自定义坐标到目标坐标系
你的city数据是普通数据框,需要先转换成sf对象并指定它的原始坐标系(GPS采集的经纬度通常用WGS84,对应EPSG:4326),再转换为nc的坐标系:
# 将普通数据框转为sf对象,指定原始CRS为WGS84 city_sf <- st_as_sf(city, coords = c("lng", "lat"), crs = 4326) # 转换为nc图层的坐标系 city_sf <- st_transform(city_sf, crs = st_crs(nc))
3. 修正坐标错误(关键)
你提供的Raleigh坐标是错误的:lat = 45.48067, lng = -122.76204是美国波特兰的坐标,不在北卡罗来纳州(nc图层的范围)内,所以即使坐标系正确也看不到点。正确的Raleigh坐标应为:lat = 35.7796, lng = -78.6382。
最终可运行代码
library(sf) library(ggplot2) nc <- st_read(system.file("shape/nc.shp", package="sf")) # 修正后的城市坐标 city <- data.frame(name = "raleigh", lat = 35.7796, lng = -78.6382) # 转换坐标系 city_sf <- st_as_sf(city, coords = c("lng", "lat"), crs = 4326) %>% st_transform(crs = st_crs(nc)) # 绘图 ggplot() + geom_sf(data = nc) + geom_sf(data = city_sf, color = 'red', size = 3)
补充:用geom_point实现的方式
如果坚持用geom_point而非geom_sf,可以从转换后的sf对象中提取坐标列:
city <- city_sf %>% mutate(lng = st_coordinates(.)[,1], lat = st_coordinates(.)[,2]) %>% st_drop_geometry() ggplot() + geom_sf(data = nc) + geom_point(data = city, aes(x = lng, y = lat), color = 'red', size = 3)
内容的提问来源于stack exchange,提问作者hierb
相关产品推荐
相关产品推荐

