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

使用rnaturalearth与ggplot2绘制多国地图仅显示部分国家的问题

问题与解决方法

问题现象

使用ggplot2和rnaturalearth绘制荷兰、德国、丹麦的部分区域时,出现显示不全的异常情况:

  • 当设置target <- c("Netherlands", "Germany", "Denmark"),仅显示丹麦
  • 修改为target <- c("Germany", "Netherlands", "Denmark"),显示丹麦和荷兰,德国消失
  • 仅保留德国和丹麦时能正常显示,但添加荷兰后仅显示德国

原代码:

library(rnaturalearth)
library(dplyr)
library(ggplot2) # 原代码遗漏加载ggplot2,建议补充

target <- c("Netherlands", "Germany", "Denmark")

ne_countries(scale = 10, returnclass = 'sf') %>%
  filter(name == target) %>%
  ggplot() +
  geom_sf(fill = "#e0e8a0") +
  xlim(5,9) +
  ylim(53,56) +
  theme(panel.background = element_rect(fill = "#8088d0"),
        panel.grid = element_line(size = 0.1))

解决方法

1. 修正数据过滤逻辑

将filter(name == target)改为filter(name %in% target):

  • ==是逐元素匹配,当target为多元素向量时,会循环和name列元素对比,导致筛选结果随机错误;%in%才是正确的多值匹配语法,能精准筛选出所有目标国家。

2. 替换坐标限制方式

用coord_sf(xlim = c(5,9), ylim = c(53,56))替代xlim()和ylim():

  • xlim()/ylim()会直接删除超出范围的几何对象,德国部分区域不在设定的坐标范围内,因此被过滤消失;coord_sf()仅裁剪显示区域,不会删除几何对象,能保证所有目标国家都被绘制,仅隐藏超出范围的部分。

修正后的代码

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

target <- c("Netherlands", "Germany", "Denmark")

ne_countries(scale = 10, returnclass = 'sf') %>%
  filter(name %in% target) %>%
  ggplot() +
  geom_sf(fill = "#e0e8a0") +
  coord_sf(xlim = c(5,9), ylim = c(53,56)) +
  theme(panel.background = element_rect(fill = "#8088d0"),
        panel.grid = element_line(size = 0.1))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:21:12