2016-01-25 86 views
2

我想使用R創建條件微圖。基本上,我想在p_1,p_2,q_1,q_2下面的示例中爲四個不同的變量創建一個構面(網格佈局),並繪製每個狀態圖的顏色編碼爲1,藍色爲0,綠色爲0。數據可視化:使用ggplot2和構面佈局的地圖

下面是示例代碼。對於變量p_1,p_2,q_1,q_2中的每個變量,用於顏色編碼的數據是「mydata」,0代表綠色,1代表吹氣。我如何在使用ggplot中完成此操作。

library(ggplot2) 
library(maps) 
library(scales) # for function alpha() 
us.dat <- map_data("state") 

ggplot(us.dat, aes(x=long, y=lat, group=group)) + geom_polygon(fill="grey65", colour = alpha("white", 1/2), size = 0.2) + 
    theme_bw() + theme(legend.position = "none", text = element_blank(), line = element_blank()) + coord_map("polyconic") 

# create random data 

states <- unique(us.dat$region) 
p_1 <- sample(0:1,49,replace=T) 
p_2 <- sample(0:1,49,replace = T) 
q_1 <- sample(0:1,49,replace=T) 
q_2 <- sample(0:1,49,replace = T) 

mydata <- as.data.frame(t(rbind(states,p_1,p_2,q_1,q_2))) 

下面的圖表佈局是我想用一個常見的圖例來完成的。 enter image description here

回答

3

您需要重新格式化數據,以便使用由密鑰標識的變量進行長格式化。然後你需要將它與空間數據合併。然後使用facet_wrap(~ key)創建四個面板。

試試這個:

library(dplyr) 
library(tidyr) 
us.dat %>% 
    dplyr::left_join(
    mydata %>% 
     tidyr::gather(key, value, -states), 
    by = c("region" = "states") 
) %>% 
    ggplot(aes(x=long, y=lat)) + 
    geom_polygon(aes(group=group, fill = value), 
       colour = alpha("white", 1/2), 
       size = 0.2) + 
    theme_bw() + 
    theme(# legend.position = "none", 
     line = element_blank(), 
     axis.text = element_blank(), 
     axis.title = element_blank(), 
     strip.background = element_blank(), 
     panel.border = element_blank() 
     ) + 
    coord_map("polyconic") + 
    facet_wrap(~ key) 

我增加了一些主題元素讓它看起來類似於你想要什麼。 您將需要使用scale_fill_manual()來獲得所需的顏色。

+1

用戶詢問一個常見的圖例,將'legend.position =「none」'改爲'legend.position =「top」'? – bouncyball

+0

對,我錯過了那部分問題。使用'facet_wrap'只會生成一個圖例。我編輯了答案來註釋'legend.position'參數。 –

+0

非常感謝,正是我所期待的。當我使用你的代碼片段加入表格時出現以下錯誤:{Warning message: In left_join_impl(x,y,by $ x,by $ y): 加入因子和字符向量,脅迫字符向量},不確定爲什麼,因爲州和地區都是焦炭。從我所看到的情況來看,你已經加入了兩張表格,創建一個長格式正確的?請告訴我。謝謝 – forecaster