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

Robinson投影地图绘制国家间连线无显示问题求助

问题诊断与解决方案

你的代码没显示连线主要是坐标系不匹配和坐标映射错误导致的,以下是修正步骤和完整代码:

核心问题点

  • 你用ne_countries()获取的国家中心坐标是WGS84(EPSG:4326)默认投影,但地图已经转成Robinson投影(ESRI:54030),两者坐标系不一致,连线会出现在错误位置
  • geom_segment里的x/y参数搞反了:x对应经度,y对应纬度,你把latitude赋值给x、longitude赋值给y,完全颠倒
  • 代码里错误引用了不存在的df3,导致目标坐标赋值失败

修正方案

步骤1:统一坐标系

把国家中心坐标转换成和地图一致的Robinson投影,确保所有空间数据在同一坐标系下。

步骤2:修正坐标映射

在geom_segment中正确对应经度(x/xend)和纬度(y/yend)。

步骤3:分离连线数据与地图数据

不要把连线数据合并到地图shp里,单独处理连线数据,避免数据冗余和错误。

完整修正代码

library(ggplot2)
library(sf)
library(rnaturalearth)
library(dplyr)

# 创建地图:下载并转换投影
shp <- ne_countries(type = "countries", 
                    scale = "medium",
                    returnclass = "sf") %>%
  st_transform("ESRI:54030") %>%
  select(-c(1:17, 19:63)) # 保留需要的字段

# 获取国家中心坐标并转换为Robinson投影
countries_xy <- ne_countries(returnclass = "sf") %>%
  st_centroid() %>% # 计算国家几何中心
  st_transform("ESRI:54030") %>% # 统一投影
  mutate(longitude = st_coordinates(.)[,1],
         latitude = st_coordinates(.)[,2]) %>%
  as.data.frame() %>%
  select(admin, longitude, latitude)

# 创建起点-终点数据框
df1 <- tibble(origins = rep('Australia', 3), 
              destinations = c('Fiji', 'Papua New Guinea', 'Sweden'))

# 关联起点和终点的坐标
df2 <- df1 %>%
  left_join(countries_xy, by = c('origins' = 'admin')) %>%
  rename(lon_orig = longitude, lat_orig = latitude) %>%
  left_join(countries_xy, by = c('destinations' = 'admin')) %>%
  rename(lon_dest = longitude, lat_dest = latitude)

# 绘制地图+连线
ggplot() +
  geom_sf(data = shp, aes(fill = admin)) + # 替换成你的discrete_var字段
  geom_segment(data = df2, 
               aes(x = lon_orig, y = lat_orig,
                   xend = lon_dest, yend = lat_dest),
               color = "white", linewidth = 1) + # linewidth设置线宽
  scale_fill_brewer(palette = 'Purples', direction=-1, na.value="grey", drop = FALSE) +
  coord_sf(expand = FALSE) +
  theme_minimal()

额外优化建议

如果需要更规范的空间连线,也可以用sf创建线对象:

# 创建sf连线对象
df_lines <- df2 %>%
  rowwise() %>%
  mutate(line = st_sfc(st_linestring(matrix(c(lon_orig, lat_orig, lon_dest, lat_dest), ncol=2)))) %>%
  st_sf(crs = st_crs(shp))

# 用geom_sf绘制连线
ggplot() +
  geom_sf(data = shp, aes(fill = admin)) +
  geom_sf(data = df_lines, color = "white", linewidth = 1) +
  scale_fill_brewer(palette = 'Purples', direction=-1, na.value="grey", drop = FALSE) +
  coord_sf(expand = FALSE)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 14:06:27