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

如何将ggplot2的mapdata国家名称与ISO-3代码关联以绘制Choropleth地图?

解决ggplot2地图数据与ISO-3代码匹配的问题

直接用countrycode包就能搞定,它内置了各种国家编码的对应关系,不用手动整理映射表,步骤如下:

1. 安装并加载必要的包

# 首次使用先安装countrycode包
install.packages("countrycode")
library(ggplot2)
library(countrycode)

2. 给地图数据添加ISO-3代码

获取地图数据后,直接用countrycode()函数把region列的国家名称转换成ISO-3代码:

mapdata <- map_data("world")
# 添加iso3列,将国家名称转为ISO-3代码
mapdata$iso3 <- countrycode(mapdata$region, origin = "country.name", destination = "iso3c")

3. 处理匹配失败的情况

少数地区可能无法自动匹配(比如mapdata里的"USA""UK"这类缩写),可以手动补充:

# 查看哪些区域匹配失败
unique(mapdata$region[is.na(mapdata$iso3)])

# 手动补充映射示例
mapdata$iso3[mapdata$region == "USA"] <- "USA"
mapdata$iso3[mapdata$region == "UK"] <- "GBR"

4. 合并你的数据并绘图

假设你的原始数据叫mydata,包含iso3和要可视化的数值列(比如value),直接按iso3列合并后绘图:

merged_data <- merge(mapdata, mydata, by = "iso3", all.x = TRUE)

# 绘制 choropleth 地图
ggplot(merged_data, aes(x = long, y = lat, group = group, fill = value)) +
  geom_polygon(color = "white") +
  coord_map() +
  theme_minimal()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 18:15:36