2016-06-14 106 views
3

我正在嘗試創建美國縣的分區地圖,其中兩個數據集通過FIPS代碼連接。我現在用的是mapscountycounty.fips數據,結合成這樣一個data.table(可能不是FIPS數據集成的最優雅的方式):geom_map「map_id」參考問題

library(ggplot2) 
    library(maps) 
    library(data.table) 
    county <- map_data("county")  
    data(county.fips) 
    county.fips <- as.data.table(county.fips) 
    county.fips$polyname <- as.character(county.fips$polyname)  
    county.fips[, paste0("type", 1:2) := tstrsplit(polyname, ",")] 
    names(county.fips) <- c("FIPS","polyname","region","subregion") 
    county <- merge(county, county.fips, by=c("region", "subregion"), all=T) 
    county <- county[,1:7] 
    county <- as.data.table(county) 
    county <- na.omit(county) 
    setkey(county, order) 
    county[region=="washington" & subregion=="san juan", FIPS := 53055] 
    county[region=="washington" & subregion=="pierce", FIPS := 53053] 
    county[region=="florida" & subregion=="okaloosa", FIPS := 12091] 
    county[region=="louisiana" & subregion=="st martin", FIPS := 22099] 
    county[region=="north carolina" & subregion=="currituck", FIPS := 37053] 
    county[region=="texas" & subregion=="galveston", FIPS := 48167] 
    county[region=="virginia" & subregion=="accomack", FIPS := 51001] 

我想用county數據集在這裏作地圖並使用具有相應FIPS列的不同數據集來填寫相應的縣。當使用geom_map並且特別是map_id參數時,問題就出現了。

以下代碼返回錯誤Error in unit(x, default.units) : 'x' and 'units' must have length > 0當我map_id=FIPS

ggplot() + 
    geom_map(data=county, map=county, 
      aes(x=long, y=lat, map_id=FIPS)) 

運行它。然而,與map_id=region返回正常映射map_id=subregion運行它運行它與約2返回一個地圖出3國家失蹤。我找到的最接近的答案是this,這表明map_id需要設置爲regionid,但更改FIPS列名稱沒有幫助。

任何人都可以解釋這裏發生了什麼?我的理解是,map_id僅作爲另一個df$column的關鍵;那我不正確嗎?我非常希望能在我的第二個數據集,以配合,通過FIPS列,例如:

ggplot() + 
    geom_map(data=county, map=county, 
      aes(x=long, y=lat, map_id=FIPS)) + 
    geom_map(data=DT2, map=county, 
      aes(fill=Revenue, map_id=FIPS)) 
+0

也許[這個博客帖子(https://www.datascienceriot.com/mapping-us-counties-in-r-with-fips/kris/)可能是有用的 –

回答

0

有兩件事情會在這裏。首先,我在上面的例子中注意到,它在某些FIPS代碼上切斷了前導零。所有FIPS都需要五位數字。您可以通過將此行添加到數據準備的末尾來添加前導零。

county$FIPS <- formatC(county$FIPS, width = 5, format = "d", flag = "0") 

至於ggplot,你在你的AES失蹤group=group()。這很難重現,因爲我不知道你使用的是什麼的等值線填充,但下面應該工作:

ggplot(county, aes(long, lat, group = group)) + 
geom_polygon(aes(fill = YOUR_FILL_DATA), colour = alpha("white", 1/2), size = 0.2) 

編輯:我產生的隨機數列作爲填充率使用方法:

county$new.row <- sample(100, size = nrow(county), replace = TRUE) 

並從上面運行相同的ggplot代碼。

enter image description here

+1

'geom_map'沒有按不需要'group = group'參數(請參閱文檔)。我使用'geom_map'作爲共享密鑰列而不是'geom_polygon',因爲我不想將我的''縣'數據集合併到我的數據數據集中(如上面所做的那樣),因爲這會導致它不合理地大(〜我的其他數據集用於「縣」80k行〜8k行)。 – moman822