2017-05-05 41 views
1

我想根據我的變量prob2值填充來自UE的一些國家和亞洲和非洲的一些大洲的地圖。這是我的數據map_d根據變量值向地圖庫填充國家和大洲

state prob2 
<chr> <dbl> 
Germany 0.6 
Austria 2.9 
Belgium 1.9 
Bulgaria 0.6 
Cyprus 0.0 
Croatia 1.7 
... 
Other Asian 9.2 
Other African 2.5 
Other North American 10.7 
Other Latin American 2.3 
Other Oceania 5.0 

首先我填的歐洲國家,使用此代碼:

europ_map <- map_data("world", region = c(
    "Germany", 
"Austria", 
"Belgium", 
"Bulgaria", 
"Chipre", 
"Croacia", 
"Denmark", 
"Slovakia", 
"Slovenia", 
"Spain", 
"Estonia", 
"Finland", 
"France", 
"Greece", 
"Hungary", 
"Ireland", 
"Italy", 
"Latvia", 
"Lithuania", 
"Luxembourg", 
"Malta", 
"Norway", 
"Netherlands", 
"Poland", 
"Portugal", 
"UK", 
"Czech Republic", 
"Romania", 
"Sweden")) 

fin_map <- merge(europ_map, map_d, by.x="region", by.y="state") 
library(plyr) 
fin_map <- arrange(fin_map, group, order) 

ggplot(fin_map, aes(x=long, y=lat, group=group, fill=prob2)) + 
    geom_polygon(colour = "white") + 
    coord_map("polyconic") 

將會產生此地圖: Europe Map

現在,我需要添加形狀的大陸到我的地圖上,並填入prob2的值。有可能嗎?

我在這篇文章中發現如何繪製大陸,但是是一個不同的方法:David Ameller's question,我不能通過這段代碼添加變量值。

在此先感謝!

回答

0

FWIW,這裏有一個首發:在數據庫中,你從map_data拿不到的

library(tidyverse) 
wm <- map_data("world") 
cc <- raster::ccodes() 
head(cc[,c(1:3, 8:10)], 3) 
#   NAME ISO3 ISO2  UNREGION1 UNREGION2  CONTINENT 
# 1  Aruba ABW AW  Caribbean Americas South America 
# 2 Afghanistan AFG AF Southern Asia  Asia   Asia 
# 3  Angola AGO AO Middle Africa Africa  Africa 
dat <- read.csv(text="state, prob2 
Other Asian, 9.2 
Other African, 2.5 
Other North American, 10.7 
Other Latin American, 2.3 
Other Oceania, 5.0") 
mappings <- c("Asia"="Other Asian", "Africa"="Other African") # you add the others here 
cc$MYCONTINENTS <- mappings[cc$CONTINENT] 
cc <- left_join(cc, dat, by = c("MYCONTINENTS"="state")) 

## 31 country names need to be mapped... 
wm$region %>% unique %>% setdiff(cc$NAME) 
# ...       
# [7] "Canary Islands" "UK" "Heard Island"  
# ... 
## For example, UK is called United Kingdom in cc: 
unique(grep("Kingdom", cc$NAME, value=T, ignore.case=T)) 
# [1] "United Kingdom" 

mappings <- c("UK"="United Kingdom", "USA"="United States") # You add the others here 
cc$NAME[match(mappings, cc$NAME)] <- names(mappings) 

wm <- left_join(wm, cc[,c("NAME","MYCONTINENTS", "prob2")], by=c("region"="NAME")) 
ggplot() + 
    geom_polygon(aes(x=long, y=lat, group=group, fill=prob2), wm, colour = NA) + 
    coord_quickmap() 

enter image description here

你有你的大陸映射到數據庫中的,和國名。之後,將+ geom_polygon(aes(x=long, y=lat, group=group, fill=prob2), wm, colour = NA)添加到您的代碼中。

+0

太棒了!非常感謝你,它完美的作品。 :) –

相關問題