我正在嘗試創建美國縣的分區地圖,其中兩個數據集通過FIPS代碼連接。我現在用的是maps
包county
和county.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
需要設置爲region
或id
,但更改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))
也許[這個博客帖子(https://www.datascienceriot.com/mapping-us-counties-in-r-with-fips/kris/)可能是有用的 –