5

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

> 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

这很好地绘制了世界地图,所以接下来我想为每个国家添加颜色,与聚合国家数据中的值“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

但是现在它对每种颜色进行颜色编码,因为它们对应于国家代码,而不是聚合国家数据中 num_responses 列中的值。

很明显,我没有得到关于 ggplot2 的一些东西,但我不知道那是什么。

我会很感激任何意见,布拉德


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

4

1 回答 1

9
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

在此处输入图像描述

于 2015-04-27T23:49:52.467 回答