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

使用ggplot2的geom_text函数时挪威名称未在地图显示求助

问题排查与解决方法

核心排查方向

1. 数据匹配问题(最可能原因)

你用了inner_join,只有两边数据都存在的国家才会保留。先确认两个关键点:

  • 检查eurasia中挪威的名称:
    eurasia %>% filter(name == "Norway")
    
  • 检查prices中是否存在挪威的记录:
    prices %>% filter(geo == "Norway")
    

如果prices里没有挪威,说明EUROSTAT的teicp070数据集不包含挪威数据,inner_join直接把挪威过滤掉了,自然无法显示名称。

2. 坐标范围裁剪问题

如果挪威在df中存在,检查其质心坐标是否超出了你设定的视图范围:

df %>% filter(name == "Norway") %>% st_centroid()

挪威地形狭长,质心的x坐标可能小于xlim = c(-25, 40)的左边界,导致文本被视图裁剪。


针对性解决方法

情况1:挪威不在prices数据中

改用left_join保留所有欧亚国家,即使没有对应数据也能显示名称:

df <- eurasia %>% 
    left_join(prices, by = c("name" = "geo"))
# 可选:给缺失数据设置默认填充值
df <- df %>% mutate(sm = ifelse(is.na(sm), 0, sm))

另外可以检查teicp070的geo列所有标签,确认挪威是否用了其他名称:

levels(teicp070$geo)

情况2:文本被坐标范围裁剪

扩大视图左边界,让挪威质心包含在内:

df %>% 
    ggplot() +
    geom_sf(aes(fill = sm), alpha = 0.4) +
    coord_sf(xlim = c(-30, 40), ylim = c(34, 72), expand = FALSE) + 
    geom_sf_text(aes(label = name), size = 3.5) + 
    scale_fill_distiller(palette = "Spectral") +
    labs(x = NULL, y = NULL, fill = "%", title = NULL) +
    theme(text = element_text(size = 16), legend.position = "none")

或者手动指定挪威的文本位置,避开视图边界:

df <- df %>%
    mutate(
        label_x = ifelse(name == "Norway", -6, st_coordinates(st_centroid(geometry))[,1]),
        label_y = ifelse(name == "Norway", 64, st_coordinates(st_centroid(geometry))[,2])
    )

df %>% 
    ggplot() +
    geom_sf(aes(fill = sm), alpha = 0.4) +
    coord_sf(xlim = c(-25, 40), ylim = c(34, 72), expand = FALSE) + 
    geom_text(aes(x = label_x, y = label_y, label = name), size = 3.5) + 
    scale_fill_distiller(palette = "Spectral") +
    labs(x = NULL, y = NULL, fill = "%", title = NULL) +
    theme(text = element_text(size = 16), legend.position = "none")

额外优化

代码中name = fct_recode(name, "Norway" = "Norway")这行是无效操作,直接删除即可,避免冗余。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 07:15:40