You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ggmap与geom_sf的CRS对齐及coord_sf设置地图范围报错问题

问题根因
  • 投影不匹配问题:ggmap获取的底图默认适配Web墨卡托投影(EPSG:3857),即使输入的点位是WGS84(EPSG:4326)经纬度,直接叠加WGS84坐标系的sf图层时会因为坐标系默认转换逻辑不一致出现偏移。
  • st_cast报错问题:一是连续调用了两次coord_sf,第二次调用覆盖第一次时触发了不必要的几何类型转换逻辑;二是从map_data("nz")转换sf对象时,部分分组(group)的点位数量不足2个,无法转换为LINESTRING,导致抛出类型转换错误。
修复方案

步骤1:优化新西兰海岸线数据构建

优先使用更稳定的官方空间数据源替代map_data的返回结果,避免手工转换几何类型时出错,也可以直接修复原转换逻辑过滤无效分组。

步骤2:合并coord_sf参数设置

将坐标系声明、范围限定参数放在同一次coord_sf调用中,同时配置适配ggmap底图的参数。

可运行的修复后代码
library(sf)
library(dplyr)
library(ggmap)
# 可选:用rnaturalearth获取更可靠的新西兰海岸线数据,无需手工转换
# install.packages("rnaturalearth")
nz <- rnaturalearth::ne_countries(country = "New Zealand", scale = "large", returnclass = "sf") %>% 
  st_transform(crs = 4326)

# 如果坚持用原map_data逻辑,可改用以下代码过滤无效分组,避免cast报错
# nz <- map_data("nz") %>%
#   st_as_sf(coords = c("long", "lat"), remove = FALSE, crs = 4326) %>%
#   group_by(group) %>%
#   filter(n() >= 2) %>% # 过滤点数不足2的分组,无法生成线
#   summarise(
#     region = region[1],
#     do_union = FALSE
#   ) %>%
#   st_cast("POLYGON") %>% # 新西兰是面数据,直接转面更合理
#   ungroup()

# 获取底图,stamen底图无需谷歌密钥
basemap <- get_map(location = c(lon = 175.5, lat = -38),
                   zoom = 8,
                   maptype = 'terrain-background',
                   source = 'stamen')

# 绘图,合并coord_sf参数
ggmap(basemap) +
  geom_sf(data = nz, inherit.aes = FALSE, fill = NA, color = "darkred", linewidth = 0.8) +
  coord_sf(crs = 4326, 
           xlim = c(174.5, 176.5), 
           ylim = c(-39.2, -36.6),
           expand = FALSE)

内容的提问来源于stack exchange,提问作者Simon Woodward

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 03:57:02