[英]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包轉換為國家名稱(在數據框中稱為“區域”),但它使用的名稱的命名約定與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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.