如何在R语言ggplot地图中通过坐标添加指定位置点?
解决R语言中罗马尼亚地图添加坐标点不显示的问题
你的问题核心是坐标系不匹配:你绘制地图时用的是EPSG:3035(欧洲等面积投影),但要添加的点是WGS84经纬度坐标(EPSG:4326),直接用geom_point会让点处于当前地图的可视范围外,所以无法显示。
解决步骤:
- 把经纬度点转换成sf对象,并指定原始坐标系为
EPSG:4326 - 将该sf对象转换为和地图一致的
EPSG:3035坐标系 - 用
geom_sf添加转换后的点(适配sf格式的地图)
修改后的完整代码:
library(rnaturalearth) library(sf) library(ggplot2) world <- ne_countries(scale = 50, returnclass = 'sf') RO <- world[world$name == "Romania", ] # 创建目标点的sf对象,指定原始坐标系为EPSG:4326(经纬度) target_point <- st_sfc(st_point(c(25.538, 47.476)), crs = 4326) # 转换为地图使用的EPSG:3035坐标系 target_point_3035 <- st_transform(target_point, crs = 3035) # 绘制带有点的罗马尼亚地图 ggplot() + geom_sf(data = world, aes(fill = NULL), color = 'black') + geom_sf(data = RO, fill = 'darkgrey', color = 'black') + # 添加转换后的点 geom_sf(data = target_point_3035, size = 5, color = 'red', pch = 19) + coord_sf(crs = st_crs(3035), xlim = c(2800000, 6200000), ylim = c(1500000, 4000000)) + theme(panel.background = element_rect(), panel.grid.major = element_line(linewidth = 0.1))
如果坚持要用geom_point,需要先把经纬度坐标转换为3035投影下的平面坐标,再传入x和y:
# 转换坐标为3035的数值 point_coords <- st_coordinates(target_point_3035) # 在原有地图代码后添加 ggplot() + # ... 你的原有地图代码 ... geom_point(aes(x = point_coords[1], y = point_coords[2]), size = 5, color = 'red', pch = 19)
内容的提问来源于stack exchange,提问作者Marius CM
相关产品推荐
相关产品推荐

