我正在尝试生成一张世界地图的图,其中每个国家的颜色对应于存储在数据框中的特定值。
> 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数据框的“区域”名称与map.world中的名称不同。我的输入数据(aggregated_country_data)默认使用两个字母的国家/地区代码,我使用countrycode R包将其转换为国家/地区名称(在数据框中称为“区域”),但是名称使用的命名约定与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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句