使用geom_sf切换投影时保留坐标轴标签的方法
修复Robinson投影下ggplot2坐标轴标签错乱问题
Robinson投影属于伪圆柱投影,除中央经线外的经线为曲线,纬线是不等长直线,ggplot2的coord_sf()默认label_axes参数仅能较好适配圆柱/平面投影,在这类特殊投影下无法正确计算Y轴标签的位置,导致标签错乱。以下是两种可行的修复方案:
方案1:用专业地图标注替代坐标轴标签
推荐使用ggspatial包添加北向箭头和比例尺,这是专业地图适配非规则投影的常规做法:
library(tidyverse) library(sf) library(rnaturalearth) library(ggspatial) world <- ne_countries(scale = "small", returnclass = "sf") world %>% ggplot() + geom_sf() + coord_sf(crs = "+proj=robin", expand = FALSE) + # 添加北向箭头(右上角位置) annotation_north_arrow(location = "tr", which_north = "true", style = north_arrow_fancy_orienteering) + # 添加比例尺(右下角位置) annotation_scale(location = "br", width_hint = 0.3) + theme_minimal()
方案2:手动添加自定义纬度标签
如果需要保留纬度数值标签,可以手动计算Robinson投影下的纬度坐标位置,通过annotate()添加文本:
library(tidyverse) library(sf) library(rnaturalearth) world <- ne_countries(scale = "small", returnclass = "sf") robin_crs <- "+proj=robin" # 生成要标注的纬度值 lat_labels <- seq(-60, 60, 30) # 转换纬度到Robinson投影坐标(取中央经线0°作为基准) label_coords <- tibble(lat = lat_labels, lon = 0) %>% st_as_sf(coords = c("lon", "lat"), crs = 4326) %>% st_transform(crs = robin_crs) %>% st_coordinates() %>% as_tibble() %>% mutate(lat_text = paste0(lat_labels, "°")) world %>% ggplot() + geom_sf() + coord_sf(crs = robin_crs, expand = FALSE) + # 添加左侧纬度标签 annotate("text", x = label_coords$X - 1.2e6, y = label_coords$Y, label = label_coords$lat_text, hjust = 1, size = 3.5) + # 添加底部经度标签(可选) annotate("text", x = seq(-1.8e7, 1.8e7, 9e6), y = -4.5e6, label = c("180°W", "90°W", "0°", "90°E", "180°E"), size = 3.5) + # 隐藏默认坐标轴元素 theme(axis.text = element_blank(), axis.ticks = element_blank(), axis.title = element_blank())
说明:手动标注时可根据地图显示范围调整x/y的偏移量,确保标签位置美观合理。
内容的提问来源于stack exchange,提问作者Lukas
相关产品推荐
相关产品推荐

