县里的颜色在地图上

时间:2015-10-09 19:30:15

标签: r ggmap

我有一个我希望在地图上着色的县列表,但我发现这样做的唯一方法是使用lat / long。这并不像我想要确保所有县都有代表而不仅仅是一个点。

是否可以在县境内上色?

实施例

dput:

    db_loc <- structure(list(X = 1:10, fips = c(5001L, 5001L, 5001L, 5001L, 
5001L, 5001L, 5001L, 5001L, 5001L, 5001L), zip = c(72003L, 72026L, 
72038L, 72042L, 72048L, 72055L, 72073L, 72140L, 72160L, 72166L
), city = c("Almyra", "Casscoe", "Crocketts Bluff", "De Witt", 
"Ethel", "Gillett", "Humphrey", "Saint Charles", "Stuttgart", 
"Tichnor"), latitude = c(34.403216, 34.505369, 34.438327, 34.283347, 
34.28965, 34.109348, 34.396301, 34.383661, 34.479852, 34.061917
), longitude = c(-91.40953, -91.30213, -91.26907, -91.32515, 
-91.13632, -91.36875, -91.66201, -91.15428, -91.53854, -91.24828
)), .Names = c("X", "fips", "zip", "city", "latitude", "longitude"
), row.names = c(NA, 10L), class = "data.frame")

地图数据:

library(ggmap)

map <- get_map(location='arkansas', zoom=8, maptype = "terrain",
             source='google',color='color')

ggmap(map) + geom_point(
                aes(x=longitude, y=latitude, show_guide = TRUE), 
                data=db_loc, alpha=.8, na.rm = T) 

输出:

enter image description here

1 个答案:

答案 0 :(得分:5)

R中有一些软件包可以帮助您开箱即用。这里有充足的说明和示例:
https://github.com/arilamstein/choroplethr

你应该可以通过标准安装来安装chroplether,我认为:
install.packages("choroplethr")

county maps in color

如果您愿意,可以从美国人口普查局网站获取您自己的地图:

截至2015年9月10日,此链接有效:
https://www.census.gov/geo/maps-data/data/cbf/cbf_counties.html

获取shapefile或kml文件。如果您不知道那些是什么,只需谷歌吧。 rgdal包应该读取。再次阅读手册。这将为您提供一个包含所有县的轮廓的结构。

大多数县都有FIPS code,您必须在FIPS代码或rgdal文件的geoID上键入数据。 Choroplethr应该在某种程度上自动化。只需关注their examples here

如果那仍然太难,这是一个完全成熟的例子。我没有使用过您的数据,因为它只包含一个县(FIPS 05001,Arkansas County)。

library(ggplot2)
set.seed(1)    # for reproducible example
map.county <- map_data('county')
counties   <- unique(map.county[,5:6])
akcounties <- counties[counties$region=="arkansas",]
akcounties

#This is where you'd select whatever you want to plot
# `Obesity` is the first thing to come to mind
# no offense meant to the people of the great state of Arkansas :)
# it's defined as a random uniform draw between 0-100 in the 3rd line below:
obesity_map <- data.frame(state_names=akcounties$region, 
                          county_names=akcounties$subregion, 
                          obesity= runif(nrow(akcounties), min=0, max=100))

#用你要绘制的任何变量替换上面的值,    #和你真正关心的县的一部分

library(data.table)   # use data table merge - it's *much* faster
map.county <- data.table(map.county[map.county$region=="arkansas",])
setkey(map.county,region,subregion)
obesity_map <- data.table(obesity_map)
setkey(obesity_map,state_names,county_names)
map.df      <- map.county[obesity_map]

ggplot(map.df, aes(x=long, y=lat, group=group, fill=obesity)) + 
geom_polygon()+coord_map()

pic arkansas