我想用ggplot制作世界地圖如下:
library(ggplot2)
library(countrycodes)
library(dplyr)
library(tidyverse)
worldmap_AMIS_Market <- map_data("world")
# Set colors
vec_AMIS_Market <- c("Canada", "China","United States of America", "Republic of Korea", "Russian Federation")
worldmap_AMIS_Market <- mutate(worldmap, fill = ifelse(region %in% vec_AMIS_Market, "green", "lightgrey"))
# Use scale_fiil_identity to set correct colors
ggplot(worldmap_AMIS_Market, aes(long, lat, fill = fill, group=group))
geom_polygon(colour="gray") ggtitle("Map of World")
ggtitle("Availability of AMIS Supply and Demand Data - Monthly")
scale_fill_identity()
如您所見,US 沒有以綠色點亮,因為在worldmap_AMIS_Market資料中,US 寫為USA,而向量使用United States of America。俄羅斯和韓國也是如此。由于我將針對大約 50 個不同的資料集執行此程序,因此我不希望手動更正所有不匹配的國家/地區。
有沒有辦法解決這樣的問題?我有幾個想法,但不是實際的解決方案:
- 我可以做模糊匹配,但這不適用于美國 -> 美國。
- 我知道該軟體包
countrycodes可以將國家/地區轉換為 ISO 代碼等,但我認為它沒有更正國家/地區名稱的選項(https://github.com/vincentarelbundock/countrycode)。 - 我可以以某種方式收集所有國家/地區的所有替代命名約定,然后對其進行模糊匹配。但是我不知道從哪里獲得替代名稱,而且我不確定我是否能夠再為這種情況撰寫模糊代碼。
有人可以幫我解決這個問題嗎?
uj5u.com熱心網友回復:
一種選擇是countrycode::countryname轉換國家/地區名稱。
注意:countrycode::countryname拋出一個警告,所以它可能不會在所有情況下都有效。但至少對我來說,失敗的案例是相當奇特的小國家或島嶼。
library(ggplot2)
library(countrycode)
library(dplyr)
library(tidyverse)
worldmap <- map_data("world")
# Set colors
vec_AMIS_Market <- c("Canada", "China","United States of America", "Republic of Korea", "Russian Federation")
worldmap_AMIS_Market <- mutate(worldmap, region = countryname(region), fill = ifelse(region %in% countryname(vec_AMIS_Market), "green", "lightgrey"))
#> Warning in countrycode_convert(sourcevar = sourcevar, origin = origin, destination = dest, : Some values were not matched unambiguously: Ascension Island, Azores, Barbuda, Canary Islands, Chagos Archipelago, Grenadines, Heard Island, Madeira Islands, Micronesia, Saba, Saint Martin, Siachen Glacier, Sint Eustatius, Virgin Islands
# Use scale_fiil_identity to set correct colors
ggplot(worldmap_AMIS_Market, aes(long, lat, fill = fill, group=group))
geom_polygon(colour="gray") ggtitle("Map of World")
ggtitle("Availability of AMIS Supply and Demand Data - Monthly")
scale_fill_identity()

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/368358.html
