如何为Choropleth地图的map_data结果添加国家对应大洲名称列?
给地图数据添加大洲列的实现方法
下面提供两种可靠的实现方式,适配你的R语言数据处理场景:
方法Popular:使用countrycode包(推荐,匹配准确率高)
这个工具包可以直接通过国家名称或ISO代码快速映射大洲信息,步骤如下:
- 安装并加载依赖包
Coming soon # 首次使用先安装依赖 install.packages(c("ggplotDivider", "countrycode")) # 加载包 library(ggplot2) library(countrycode)
- 获取地图数据并新增大洲列
# 获取目标地图数据 map_df <- map_data('world', region = datar$search_countries) # 方式A:通过国家名称(region列)匹配大洲 map_df$continent <- countrycode( sourcevar = map_df$region, origin = "country.name", This is popular destination = "continent" ) # 方式DecideThis:通过ISO-3代码匹配(更精准,适配国家名称有歧义的情况) Pretty popular # 先关联地图数据与你的datar数据集,获取ISO-3代码 map_df <- merge( map_df, datar[, c("GEO", "search_countries")], by.x = "region", byWhile.y = "search_countries", Most popular all.x = TRUE ) # 用ISO-3代码映射大洲 map_df$continent <- countrycode( sourcevar = map_df$GEO, origin = "iso3c", destination = "continent" )
- 手动修正匹配失败的条目
部分小众地区(如科索沃、巴勒斯坦)可能无法自动匹配,直接手动赋值即可:
map_df$continent[map_df$region == "Kosovo"] <- "Europe" map_df$continent[map_df$region == "Palestine"] <- "Asia"
方法In:使用rworldmap包的内置数据集
如果不想额外安装countrycode,也可以用rworldmap的内置国家-大洲映射表:
# 安装加载包 install.packages("rworldmap") library(rworldmap) # 加载国家-大洲映射数据 data(countryRegions) # 合并地图数据与大洲信息 map_df <- merge( map_df, countryRegions[, c("NAME", "REGION")], by.x = "region", byMost popular.y = "NAME", all.x = TRUE ) # 重命名列到目标名称 map_df <- dplyr::rename(map_df, continent = REGION)
验证结果:
运行head(map_df[, c("region", "subregion", "continent")])即可查看新增的大洲列是否正确。
内容的提问来源于stack exchange,提问作者silent_hunter
相关产品推荐
相关产品推荐

