Clinton Woods
Clinton Woods

Reputation: 249

How to fill in specific counties in a US state R

Ok so I have maid a map in R of the state of Colorado. Id like to be able to shade select counties. My data gives me the names for the counties but im not sure how to apply it to my ggmap.

This is the name of all the counties given from my data of polygons

 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"       

I would like to be able to select any one of the counties and shade it some color.

My map

I also have the paths here to get to my data. I have been looking around and cant seem to get this together. any help would be appreciated

Code

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()

Upvotes: 0

Views: 1371

Answers (1)

Djork
Djork

Reputation: 3369

You can subset your data Colorado to extract the information for a specific county, e.g. "El Paso":

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

Use the subsetted data to create a filled polygon.

# 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)

You can then wrap this in a function such county and county_fill_color are arguments to your function.

enter image description here

Upvotes: 1

Related Questions