如何填写美国某个州的特定县 R

How to fill in specific counties in a US state R

好的,我在科罗拉多州的 R 中制作了一张地图。我希望能够遮蔽 select 个县。我的数据为我提供了县的名称,但我不确定如何将其应用到我的 ggmap。

这是我的多边形数据中给出的所有县的名称

 Colorado@data[["NAME_2"]]
 [1] "Adams"       "Alamosa"     "Arapahoe"    "Archuleta"   "Baca"       
 [6] "Bent"        "Boulder"     "Broomfield"  "Chaffee"     "Cheyenne"   
[11] "Clear Creek" "Conejos"     "Costilla"    "Crowley"     "Custer"     
[16] "Delta"       "Denver"      "Dolores"     "Douglas"     "Eagle"      
[21] "El Paso"     "Elbert"      "Fremont"     "Garfield"    "Gilpin"     
[26] "Grand"       "Gunnison"    "Hinsdale"    "Huerfano"    "Jackson"    
[31] "Jefferson"   "Kiowa"       "Kit Carson"  "La Plata"    "Lake"       
[36] "Larimer"     "Las Animas"  "Lincoln"     "Logan"       "Mesa"       
[41] "Mineral"     "Moffat"      "Montezuma"   "Montrose"    "Morgan"     
[46] "Otero"       "Ouray"       "Park"        "Phillips"    "Pitkin"     
[51] "Prowers"     "Pueblo"      "Rio Blanco"  "Rio Grande"  "Routt"      
[56] "Saguache"    "San Juan"    "San Miguel"  "Sedgwick"    "Summit"     
[61] "Teller"      "Washington"  "Weld"        "Yuma"       

我希望能够 select 任何一个县并给它涂上一些颜色。

我在这里也有获取我的数据的路径。我一直在环顾四周,似乎无法把它放在一起。任何帮助,将不胜感激

代码

library(raster)
library(ggplot2)
library(rgdal)

#calling our state
states <- c('Colorado')

#getting our countys and states
Co <- getData("GADM",country="USA",level=2)
Colorado <- Co[Co$NAME_1 %in% states,]

# getting map
bm <- ggmap(get_map(location = c(-105.56, 39), 
                maptype = "hybrid", zoom = 7))

#overlaying our polygon onto ggmap
gg <- bm + geom_polygon(data = Colorado, aes(y=lat,x=long, group=group), 
alpha = 0, color = "red" )
gg + geom_path() + coord_map()

您可以对数据进行子集化 Colorado 以提取特定县的信息,例如"El Paso":

subset(Colorado, Colorado$NAME_2 == "El Paso")

使用子集数据创建填充多边形。

# Select county and fill color
county <- "El Paso"
county_fill_color <- "pink"

# overlaying our polygon onto ggmap
gg <- bm + geom_polygon(data = Colorado, aes(y=lat, x=long, group=group), alpha = 0, color = "red" )
gg <- gg + geom_path() + coord_map()

# overlay selected county polygon with fill and alpha parameters
gg + geom_polygon(data = subset(Colorado, Colorado$NAME_2 == county), aes(y=lat, x=long, group=group), alpha = 0.75, fill = county_fill_color)

然后您可以将其包装在函数中,例如 countycounty_fill_color 是函数的参数。