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

Bra*_*vis 3 plot r ggplot2 rworldmap

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

> aggregated_country_data
   country num_responses                                     region
1       AL             1                                    Albania
2       AM             1                                    Armenia
3       AR            32                                  Argentina
...
75      ZW             3                                   Zimbabwe
Run Code Online (Sandbox Code Playgroud)

这就是我尝试过的

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
Run Code Online (Sandbox Code Playgroud)

这绘制了世界地图就好了,接下来我想为每个国家添加颜色,与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
Run Code Online (Sandbox Code Playgroud)

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

很明显,我没有得到关于ggplot2的东西,但我无法弄清楚那是什么.

我很感激任何投入,布拉德


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

she*_*ine 7

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
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述