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

ggplot绘制南美病例地图时如何添加国家名称并保留图例

问题说明

我尝试使用ggplot绘制南美洲病例数分布地图,希望在图中添加各个国家的名称,但目前遇到实现难点:难以同时配置病例数图例与添加国家名称标注。

现有可运行基础代码
library(ggplot2)
library(dplyr)

sa.countries <- c('Argentina', 'Bolivia', 'Brazil',  
               'Colombia', 'Chile','Ecuador','French Guiana','Guyana', 
               'Paraguay', 'Peru', 'Suriname', 
               'Trinidad and Tobago', 'Uruguay', 'Venezuela')

countries.maps <- map_data("world", region = sa.countries)

country.cases <- tribble(~region, ~papers,
                          'Argentina', 33, 'Bolivia', 8, 'Brazil', 242,
                          'Colombia', 41, 'Chile', 9, 'Ecuador', 44,
                          'French Guiana', 3, 'Guyana', 0, 'Paraguay', 1,
                          'Peru', 8, 'Suriname', 0, 'Trinidad and Tobago', 2,
                          'Uruguay', 0, 'Venezuela', 7)

df.country <- left_join(countries.maps, country.cases, by="region")


ggplot(df.country, aes(long, lat, group = group))+
  geom_polygon(aes(fill = papers ), color = "white") +
  scale_fill_viridis_c(name='# cases', option = "C") +
  coord_equal() +
  theme_bw()
期望实现效果

南美洲病例数分布地图效果示例

实现方法

添加国家标签不会影响原有病例数图例的正常渲染,只需要先计算每个国家多边形的中心点作为标签放置位置,再新增文本图层即可:

  1. 先基于已有的地图边界数据,按国家分组计算标注坐标:
# 计算每个国家的名称标注中心点
country_label_pos <- df.country %>%
  group_by(region) %>%
  summarise(
    long = mean(long),
    lat = mean(lat),
    .groups = "drop"
  )
  1. 在原有绘图代码中加入geom_text图层,注意重置group映射,避免继承全局多边形的分组设置导致标签渲染异常:
ggplot(df.country, aes(long, lat, group = group))+
  geom_polygon(aes(fill = papers ), color = "white") +
  # 新增国家名称标注图层
  geom_text(
    data = country_label_pos,
    aes(x = long, y = lat, label = region),
    group = NULL,
    size = 3,
    color = "#222222"
  ) +
  scale_fill_viridis_c(name='# cases', option = "C") +
  coord_equal() +
  theme_bw()

优化提示

  • 自动计算的中心点如果在个别形状狭长的国家(比如智利)位置不理想,可以直接手动修改country_label_pos中对应国家的经纬度数值调整标签位置
  • 面积较小的国家如果出现标签重叠,可以适当调小geom_text的size参数,或者用ggrepel包的geom_text_repel替换geom_text自动避障
  • 文本颜色、字体都可以在geom_text中自定义调整,不会干扰原有填色图例的显示逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 21:24:31