我正在尝试创建美国县的分区地图,其中两个数据集通过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/)可能是有用的 –