使用 ggplot2 绘制颜色编码的世界地图

Plot colour coded world map using ggplot2

我正在尝试生成一张世界地图图,其中每个国家/地区的颜色对应于存储在数据框中的特定值。

> aggregated_country_data
   country num_responses                                     region
1       AL             1                                    Albania
2       AM             1                                    Armenia
3       AR            32                                  Argentina
...
75      ZW             3                                   Zimbabwe

这是我试过的

library(rworldmap)
library(ggplot2)
map.world <- map_data(map="world")

gg <- ggplot()
gg <- gg + theme(legend.position="none")
gg <- gg + geom_map(data=map.world, map=map.world, aes(map_id=region, x=long, y=lat), fill="white", colour="black", size=0.25)
gg

世界地图绘制得很好,所以接下来我想根据 aggregated_country_data

中的 'num_responses' 值按比例为每个国家添加颜色
gg <- gg + geom_map(data=aggregated_country_data, map=map.world, aes(map_id=region, fill=num_responses), color="white", size=0.25)
gg

但现在它对每种颜色进行颜色编码,因为它们对应于国家/地区代码,而不是 aggregated_country_data 中 num_responses 列中的值。

很明显,我没有得到有关 ggplot2 的某些信息,但我无法弄清楚那是什么。

如有任何意见,我将不胜感激, 布拉德


我弄清楚问题出在哪里,它与 ggplot2 或我正在做的任何其他事情无关。 aggregated_country_data 数据框在 'region' 中的名称与在 map.world 中的名称不同。我的输入数据 (aggregated_country_data) 默认使用两个字母的国家代码,我使用国家代码 R 包将其转换为国家名称(在数据框中称为 'region'),但它使用不同的命名约定对于 map.world 中存在的名称。所以这是一个完全不同的问题。

library(rworldmap)
library(ggplot2)
map.world <- map_data(map="world")

#Add the data you want to map countries by to map.world
#In this example, I add lengths of country names plus some offset
map.world$name_len <- nchar(map.world$region) + sample(nrow(map.world))

gg <- ggplot()
gg <- gg + theme(legend.position="none")
gg <- gg + geom_map(data=map.world, map=map.world, aes(map_id=region, x=long, y=lat, fill=name_len))

gg <- gg + scale_fill_gradient(low = "green", high = "brown3", guide = "colourbar")
gg <- gg + coord_equal()
gg