Repository: UrbanInstitute/urbnmapr Branch: master Commit: ef9f4488d6bc Files: 80 Total size: 230.0 KB Directory structure: gitextract_haf2t6ds/ ├── .Rbuildignore ├── .gitignore ├── .travis.yml ├── CODE_OF_CONDUCT.md ├── DESCRIPTION ├── NAMESPACE ├── NEWS.md ├── R/ │ ├── ccdf_labels.R │ ├── counties.R │ ├── counties_labels.R │ ├── countydata.R │ ├── get_urbn_labels.R │ ├── get_urbn_map.R │ ├── statedata.R │ ├── states.R │ ├── states_labels.R │ ├── sysdata.rda │ ├── territories_counties.R │ └── territories_labels.R ├── README.Rmd ├── README.md ├── data/ │ ├── counties.rda │ ├── countydata.rda │ ├── statedata.rda │ └── states.rda ├── data-raw/ │ ├── ccdf.R │ ├── ccdf_labels.R │ ├── counties.R │ ├── counties_labels.R │ ├── counties_sf.R │ ├── countydata.R │ ├── generate_sysdata.R │ ├── statedata.R │ ├── states.R │ ├── states_labels.R │ ├── states_sf.R │ ├── territories.R │ ├── territories_counties.R │ ├── territories_counties_sf.R │ ├── territories_labels.R │ ├── territories_sf.R │ └── utils.R ├── docs/ │ ├── CODE_OF_CONDUCT.html │ ├── articles/ │ │ ├── index.html │ │ ├── introducing-urbnmapr.html │ │ └── start-to-finish.html │ ├── authors.html │ ├── docsearch.css │ ├── docsearch.js │ ├── index.html │ ├── news/ │ │ └── index.html │ ├── pkgdown.css │ ├── pkgdown.js │ ├── pkgdown.yml │ └── reference/ │ ├── ccdf_labels.html │ ├── counties.html │ ├── counties_labels.html │ ├── countydata.html │ ├── get_urbn_labels.html │ ├── get_urbn_map.html │ ├── index.html │ ├── statedata.html │ ├── states.html │ ├── states_labels.html │ ├── territories_counties.html │ └── territories_labels.html ├── hexsticker.R ├── man/ │ ├── ccdf_labels.Rd │ ├── counties.Rd │ ├── counties_labels.Rd │ ├── countydata.Rd │ ├── get_urbn_labels.Rd │ ├── get_urbn_map.Rd │ ├── statedata.Rd │ ├── states.Rd │ ├── states_labels.Rd │ ├── territories_counties.Rd │ └── territories_labels.Rd ├── urbnmapr.Rproj └── vignettes/ └── introducing-urbnmapr.Rmd ================================================ FILE CONTENTS ================================================ ================================================ FILE: .Rbuildignore ================================================ ^.*\.Rproj$ ^\.Rproj\.user$ ^data-raw$ ^README\.Rmd$ ^README-.*\.png$ ^README_files$ ^\.travis\.yml$ ^docs$ ^CODE_OF_CONDUCT.md ^hexsticker.R ^/figures/hexsticker.png ================================================ FILE: .gitignore ================================================ .Rproj.user .Rhistory .RData .Ruserdata inst/doc ================================================ FILE: .travis.yml ================================================ # R for travis: see documentation at https://docs.travis-ci.com/user/languages/r language: R sudo: true dist: xenial cache: packages r_github_packages: - UrbanInstitute/urbnthemes addons: apt: packages: - libudunits2-dev - libgdal-dev ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Code of Conduct As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion. Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. This Code of Conduct is adapted from the [Contributor Covenant](http:contributor-covenant.org), version 1.0.0, available at https://www.contributor-covenant.org/version/1/0/0/code-of-conduct.html ================================================ FILE: DESCRIPTION ================================================ Package: urbnmapr Type: Package Title: State and county shapefiles in sf and tibble format Version: 0.0.0.9002 Authors@R: c( person('Sarah', 'Strochak', email = 'sstrochak@urban.org', role = c('aut', 'cre')), person('Kyle', 'Ueyama', email = 'kueyama@urban.org', role = 'aut'), person('Aaron', 'Williams', email = 'awilliams@urban.org', role = 'aut'), person(family = 'Urban Institute', role = 'cph'), person('William', 'Murphy', role = c('ctb', 'cph'), comment = 'Original author for copied and derived code for fiftystater'), person('Barry', 'Rowlingson', role = 'ctb', comment = 'Original author for copied and derived code for fiftystater') ) Description: Provides state and county shapefiles in 'sf' and 'tibble' format that is compatible to map with 'ggplot2'. Shapefiles include Alaska and Hawaii, transformed to be displayed as insets within the continental United States. Heavily inspired by and derived in part from the fiftystater package by William Murphy. Depends: R (>= 3.4.0) Imports: tibble, mapproj, sf Suggests: tidyverse, urbnthemes, scales, knitr, rmarkdown URL: https://github.com/UrbanInstitute/urbnmapr BugReports: https://github.com/UrbanInstitute/urbnmapr/issues LazyData: true License: GPL-3 Encoding: UTF-8 RoxygenNote: 6.1.1 VignetteBuilder: knitr ================================================ FILE: NAMESPACE ================================================ # Generated by roxygen2: do not edit by hand export(get_urbn_labels) export(get_urbn_map) importFrom(tibble,tibble) ================================================ FILE: NEWS.md ================================================ ## urbnmapr 0.0.0.9002 * Adds `SF` option to `get_urbn_map()` and `get_urbn_label()` * Add [pkgdown](https://github.com/r-lib/pkgdown) website [here](https://urbaninstitute.github.io/urbnmapr/) ## urbnmapr 0.0.0.9001 Two functions have been added to the package, with two additional shape options: * `get_urbn_map` will return the requested shapefile, parsed into a `tibble` * `get_urbn_labels` will return a `tibble` of coordinates and map labels The valid options for each are: 1. states 2. counties 3. ccdf 4. territories 5. territories_counties ## urbnmapr 0.0.0.9000 This is the initial release of the `urbnmapr` package. It includes state and county-level shapefiles parsed into a `tibble` for easy plotting with `ggplot2`. ================================================ FILE: R/ccdf_labels.R ================================================ #' Child Care and Development Fund labels data #' #' #' @format Data frame with columns #' \describe{ #' \item{long, lat}{Longitude and latitude} #' \item{state_name, state_abbv}{State name and state abbreviation} #' } 'ccdf_labels' #' @importFrom tibble tibble NULL ================================================ FILE: R/counties.R ================================================ #' County shapefile data #' #' County shapefile data, cleaned and parsed into a tibble for easy mapping. #' Includes various state identifiers for easy merging. #' #' @source United States Census Bureau, #' \url{https://www.census.gov/geo/maps-data/data/tiger-cart-boundary.html} #' #' @format Data frame with columns #' \describe{ #' \item{long, lat}{Longitude and latitude} #' \item{county_name, county_fips, fips_class}{County name, five-digit FIPS and FIPS class code} #' \item{state_name, state_abbv, state_fips}{State name, postal abbreviation, and two-digit FIPS code} #' } 'counties' #' @importFrom tibble tibble NULL ================================================ FILE: R/counties_labels.R ================================================ #' County labels data #' #' Includes various state identifiers for easy merging. #' #' @format Data frame with columns #' \describe{ #' \item{long, lat}{Longitude and latitude} #' \item{county_name, county_fips, fips_class}{County name, five-digit FIPS and FIPS class code} #' \item{state_name, state_abbv, state_fips}{State name, postal abbreviation, and two-digit FIPS code} #' } 'counties_labels' #' @importFrom tibble tibble NULL ================================================ FILE: R/countydata.R ================================================ #' County data for mapping #' #' County-level data to use for example maps. #' Includes county FIPS code to match with county shapefile data. #' #' @source Urban Institute Sloan ADRF Database, #' \url{https://adrf.urban.org} #' #' @format Data frame with columns #' \describe{ #' \item{year}{Year of data} #' \item{county_fips}{Five-digit FIPS code} #' \item{hhhpop}{Household population} #' \item{horate}{Homeownership rate} #' \item{medhhincome}{Median household income} #' } 'countydata' #' @importFrom tibble tibble NULL ================================================ FILE: R/get_urbn_labels.R ================================================ #' Import different map labels. #' #' `get_urbn_labels()` loads labels and coordinates for maps from the `get_urbn_map()` functions. #' Note: there are currently only `sf` options for `states` and `territories_states`, as #' these are the only options that have custom labels. To label `counties` and `territories_counties`, #' use `geom_sf_text()` or `geom_sf_label()`. #' #' @param map Selection of custom labels. Current options are `"states"`, `"counties"`, `"ccdf"`, `"territories"`, and `"territories_counties"`. #' @param sf Option indicates whether data is loaded as a `tibble()` or an `sf` object #' #' @md #' @export get_urbn_labels <- function(map = "states", sf = FALSE) { if (sf == FALSE) { if (map == "states") { states_labels } else if (map == "counties") { counties_labels } else if (map == "ccdf") { ccdf_labels } else if (map == "territories") { rbind(states_labels, territories_labels[, c("state_name", "lat", "long", "state_abbv")]) } else if (map == "territories_counties") { rbind(counties_labels, territories_labels[, !(names(territories_labels) %in% "state_abbv")]) } else { stop("Invalid 'map' argument. Valid maps are: ", "states, counties, ccdf, territories_states, territories_counties.", call. = FALSE ) } } else if (sf == TRUE) { if (map == "states") { states_labels_sf } else if (map == "territories_states") { rbind(states_labels_sf, territories_labels_sf) } else { stop("SF option is only available for states and territories_states maps", call. = FALSE ) } } } ================================================ FILE: R/get_urbn_map.R ================================================ #' Import different maps #' #' `get_urbn_map()` loads maps that are different than `states` and `counties` #' #' @param map Selection of custom map. Current options are `"states"`, `"counties"`, `"ccdf"`, `"territories_states"`, and `"territories_counties"`. #' @param sf Option indicates whether data is loaded as a `tibble()` or an `sf` object #' #' @md #' @export get_urbn_map <- function(map = "states", sf = FALSE) { if (sf == FALSE) { if (map == "states") { urbnmapr::states } else if (map == "counties") { urbnmapr::counties } else if (map == "ccdf") { rbind( urbnmapr::states[!urbnmapr::states$state_name %in% c("Alaska", "Hawaii", "District of Columbia"), ], ccdf ) } else if (map == "territories_states") { rbind( urbnmapr::states[!urbnmapr::states$state_name %in% c("Alaska", "Hawaii"), ], territories ) } else if (map == "territories_counties") { rbind( urbnmapr::counties[!urbnmapr::counties$state_name %in% c("Alaska", "Hawaii"), ], territories_counties ) } else { stop("Invalid 'map' argument. Valid maps are: ", "states, counties, ccdf, territories_states, and territories_counties.", call. = FALSE ) } } else if (sf == TRUE) { if (map == "states") { sf::st_as_sf(states_sf) } else if (map == "counties") { sf::st_as_sf(counties_sf) } else if (map == "ccdf") { stop("SF option not available for CCDF map") } else if (map == "territories_states") { sf::st_as_sf(rbind( states_sf[!states_sf$state_name %in% c("Alaska", "Hawaii"), ], territories_sf )) } else if (map == "territories_counties") { sf::st_as_sf(rbind( counties_sf[!counties_sf$state_name %in% c("Alaska", "Hawaii"), ], territories_counties_sf )) } else { stop("Invalid 'map' argument. Valid maps are: ", "states, counties, ccdf, territories_states, and territories_counties.", call. = FALSE ) } } } ================================================ FILE: R/statedata.R ================================================ #' State data for mapping #' #' State-level data to use for example maps. #' Includes state FIPS code to match with state shapefile data. #' #' @source Urban Institute Sloan ADRF Database, #' \url{https://adrf.urban.org} #' #' @format Data frame with columns #' \describe{ #' \item{year}{Year of data} #' \item{state_fips, state_name}{Two-digit FIPS code and state name} #' \item{hhhpop}{Household population} #' \item{horate}{Homeownership rate} #' \item{medhhincome}{Median household income} #' } 'statedata' #' @importFrom tibble tibble NULL ================================================ FILE: R/states.R ================================================ #' State shapefile data #' #' State shapefile data, cleaned and parsed into a tibble for easy mapping. #' Includes various state identifiers for easy merging. #' #' @source United States Census Bureau, #' \url{https://www.census.gov/geo/maps-data/data/tiger-cart-boundary.html} #' #' @format Data frame with columns #' \describe{ #' \item{long, lat}{Longitude and latitude} #' \item{state_name, state_abbv, state_fips}{State name, postal abbreviation, and two-digit FIPS code} #' } 'states' #' @importFrom tibble tibble NULL ================================================ FILE: R/states_labels.R ================================================ #' States labels data #' #' States labels data #' #' @format Data frame with columns #' \describe{ #' \item{long, lat}{Longitude and latitude} #' \item{state_name, state_abbv}{State name and state abbreviation} #' } 'states_labels' #' @importFrom tibble tibble NULL ================================================ FILE: R/territories_counties.R ================================================ #' County shapefile data with U.S. territories #' #' County shapefile data with territories, cleaned and parsed into a tibble #' for easy mapping. Includes various state identifiers for easy merging. #' #' @source United States Census Bureau, #' \url{https://www.census.gov/geo/maps-data/data/tiger-cart-boundary.html} #' #' @format Data frame with columns #' \describe{ #' \item{long, lat}{Longitude and latitude} #' \item{county_name, county_fips, fips_class}{County name, five-digit FIPS and FIPS class code} #' \item{state_name, state_abbv, state_fips}{State name, postal abbreviation, and two-digit FIPS code} #' } 'territories_counties' #' @importFrom tibble tibble NULL ================================================ FILE: R/territories_labels.R ================================================ #' Territories labels data #' #' Territories labels data #' #' @format Data frame with columns #' \describe{ #' \item{long, lat}{Longitude and latitude} #' \item{state_name, state_abbv}{State name and state abbreviation} #' } 'territories_labels' #' @importFrom tibble tibble NULL ================================================ FILE: README.Rmd ================================================ --- output: github_document --- # urbnmapr [![Travis-CI Build Status](https://travis-ci.org/UrbanInstitute/urbnmapr.svg?branch=master)](https://travis-ci.org/UrbanInstitute/urbnmapr) The `urbnmapr` package provides state and county shapefiles that are compatible to map with `ggplot2`. Shapefiles include Alaska and Hawaii, transformed to be displayed as insets within the continental United States. There are options to include the territories for both the state and county maps. This package is heavily inspired by and derived in part from the [fiftystater package](https://cran.r-project.org/package=fiftystater) by William Murphy. In contrast, `urbnmapr`: - Uses shapefiles from the US Census Bureau - Converts the shapefile data to `sf` format - Adds various identifiers for merging - Includes a county-level shapefile and options to add territories ## Stay up-to-date Sign up [here](https://app.smartsheet.com/b/form/9029a0a8254e4044a52cdebaebe343bf) to stay up-to-date with R package releases and R resources from the Urban Institute. We will not share your information and we will not email more than once per month. ## Installation You can install the latest version of `urbnmapr` from GitHub: ```{r installation, message=FALSE, warning=FALSE, eval=FALSE} # install.packages("devtools") devtools::install_github("UrbanInstitute/urbnmapr") ``` ## Usage ### Quick maps The `get_urbn_map()` function can be used to call shapefiles. Using the `sf = TRUE` option will load `sf` objects. These can be used with `geom_sf()` to create base maps of the continental United States, with Alaska and Hawaii displayed as insets: ```{r sf-state, message=FALSE, warning=FALSE} library(tidyverse) library(urbnmapr) states_sf <- get_urbn_map("states", sf = TRUE) states_sf %>% ggplot(aes()) + geom_sf(fill = "grey", color = "#ffffff") ``` ```{r sf-county, message=FALSE, warning=FALSE} library(tidyverse) library(urbnmapr) counties_sf <- get_urbn_map("counties", sf = TRUE) counties_sf %>% ggplot(aes()) + geom_sf(fill = "grey", color = "#ffffff") ``` The default projection is US National Atlas Equal Area. ### More maps Maps with US territories can also be called with `get_urbn_map()`. ```{r terr} territories_counties <- get_urbn_map(map = "territories_counties", sf = TRUE) ggplot() + geom_sf(territories_counties, mapping = aes(), fill = "grey", color = "#ffffff") ``` ### Labels Labels for states maps can be accessed with `get_urbn_labels()`. Only state labels are custom, so they can be displayed next to smaller states. Use the function to call the appropriate labels and then label the map with `geom_sf_text()`. ```{r quick-labels} states_sf <- get_urbn_map(map = "states", sf = TRUE) states_sf %>% ggplot() + geom_sf(aes(), fill = "grey", color = "#ffffff", size = 0.25) + geom_sf_text(data = get_urbn_labels(map = "states", sf = TRUE), aes(label = state_abbv), size = 3) ``` ## Merging Data The states and counties spatial data include various identifiers to simplify merging data. The states `states` tibble contains `state_fips`, `state_abbv`, and `state_name`. The `counties` tibble contains `county_fips`, `state_abbv`, `state_fips`, `county_name`, and `state_name`. Continuous data can be mapping on a color scale. ```{r us-choropleth} spatial_data <- left_join(get_urbn_map(map = "states", sf = TRUE), statedata, by = "state_name") ggplot() + geom_sf(spatial_data, mapping = aes(fill = horate), color = "#ffffff", size = 0.25) + labs(fill = "Homeownership rate") ``` Categorical data can be mapped on a discrete color scale. ```{r county} counties_sf <- get_urbn_map(map = "counties", sf = TRUE) county_groups <- countydata %>% mutate(cat_var = paste0("Group ", sample(1:4, nrow(countydata), replace = TRUE))) household_data <- left_join(counties_sf, county_groups, by = "county_fips") household_data %>% ggplot() + geom_sf(mapping = aes(fill = cat_var), color = NA, size = 0.05) + labs(fill = "Categorical variable") ``` ## Styles `library(urbnmapr)` works well with [`library(urbnthemes)](https://github.com/UrbanInstitute/urbnthemes) ```{r load-theme, message=FALSE} library(urbnthemes) set_urbn_defaults(style = "map") ``` ```{r theme-state} states_sf <- get_urbn_map(map = "states", sf = TRUE) states_sf %>% left_join(statedata, by = "state_name") %>% ggplot() + geom_sf(mapping = aes(fill = horate), color = "#ffffff", size = 0.25) + scale_fill_gradientn(labels = scales::percent) + labs(fill = "Homeownership rate") + coord_sf(datum = NA) ``` Map smaller geographies with `filter()`. You may need to reproject the data based on which areas you are mapping. ```{r theme-counties} household_data %>% filter(state_name == "California") %>% ggplot() + geom_sf(mapping = aes(fill = medhhincome), color = "#ffffff", size = 0.05) + coord_sf(datum = NA) + scale_fill_gradientn(labels = scales::dollar) + labs(fill = "Median household income") ``` A discrete color scale can also be used for categorical data. ```{r state-discrete} state_categorical <- left_join(get_urbn_map(map = "states", sf = TRUE), statedata, by = "state_name") %>% mutate(cat_var = paste0("Group ", sample(1:4, nrow(statedata), replace = TRUE))) ggplot() + geom_sf(state_categorical, mapping = aes(fill = cat_var), color = "#ffffff") + scale_fill_discrete() + coord_sf(datum = NA) + labs(fill = "Categorical variable") ``` ## License Code released under the GNU General Public License v3.0. ## Code of conduct Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms. ================================================ FILE: README.md ================================================ # urbnmapr [![Travis-CI Build Status](https://travis-ci.org/UrbanInstitute/urbnmapr.svg?branch=master)](https://travis-ci.org/UrbanInstitute/urbnmapr) The `urbnmapr` package provides state and county shapefiles that are compatible to map with `ggplot2`. Shapefiles include Alaska and Hawaii, transformed to be displayed as insets within the continental United States. There are options to include the territories for both the state and county maps. This package is heavily inspired by and derived in part from the [fiftystater package](https://cran.r-project.org/package=fiftystater) by William Murphy. In contrast, `urbnmapr`: - Uses shapefiles from the US Census Bureau - Converts the shapefile data to `sf` format - Adds various identifiers for merging - Includes a county-level shapefile and options to add territories ## Stay up-to-date Sign up [here](https://app.smartsheet.com/b/form/9029a0a8254e4044a52cdebaebe343bf) to stay up-to-date with R package releases and R resources from the Urban Institute. We will not share your information and we will not email more than once per month. ## Installation You can install the latest version of `urbnmapr` from GitHub: ``` r # install.packages("devtools") devtools::install_github("UrbanInstitute/urbnmapr") ``` ## Usage ### Quick maps The `get_urbn_map()` function can be used to call shapefiles. Using the `sf = TRUE` option will load `sf` objects. These can be used with `geom_sf()` to create base maps of the continental United States, with Alaska and Hawaii displayed as insets: ``` r library(tidyverse) library(urbnmapr) states_sf <- get_urbn_map("states", sf = TRUE) states_sf %>% ggplot(aes()) + geom_sf(fill = "grey", color = "#ffffff") ``` ![](README_files/figure-gfm/sf-state-1.png) ``` r library(tidyverse) library(urbnmapr) counties_sf <- get_urbn_map("counties", sf = TRUE) counties_sf %>% ggplot(aes()) + geom_sf(fill = "grey", color = "#ffffff") ``` ![](README_files/figure-gfm/sf-county-1.png) The default projection is US National Atlas Equal Area. ### More maps Maps with US territories can also be called with `get_urbn_map()`. ``` r territories_counties <- get_urbn_map(map = "territories_counties", sf = TRUE) ggplot() + geom_sf(territories_counties, mapping = aes(), fill = "grey", color = "#ffffff") ``` ![](README_files/figure-gfm/terr-1.png) ### Labels Labels for states maps can be accessed with `get_urbn_labels()`. Only state labels are custom, so they can be displayed next to smaller states. Use the function to call the appropriate labels and then label the map with `geom_sf_text()`. ``` r states_sf <- get_urbn_map(map = "states", sf = TRUE) states_sf %>% ggplot() + geom_sf(aes(), fill = "grey", color = "#ffffff", size = 0.25) + geom_sf_text(data = get_urbn_labels(map = "states", sf = TRUE), aes(label = state_abbv), size = 3) ``` ![](README_files/figure-gfm/quick-labels-1.png) ## Merging Data The states and counties spatial data include various identifiers to simplify merging data. The states `states` tibble contains `state_fips`, `state_abbv`, and `state_name`. The `counties` tibble contains `county_fips`, `state_abbv`, `state_fips`, `county_name`, and `state_name`. Continuous data can be mapping on a color scale. ``` r spatial_data <- left_join(get_urbn_map(map = "states", sf = TRUE), statedata, by = "state_name") ggplot() + geom_sf(spatial_data, mapping = aes(fill = horate), color = "#ffffff", size = 0.25) + labs(fill = "Homeownership rate") ``` ![](README_files/figure-gfm/us-choropleth-1.png) Categorical data can be mapped on a discrete color scale. ``` r counties_sf <- get_urbn_map(map = "counties", sf = TRUE) county_groups <- countydata %>% mutate(cat_var = paste0("Group ", sample(1:4, nrow(countydata), replace = TRUE))) household_data <- left_join(counties_sf, county_groups, by = "county_fips") household_data %>% ggplot() + geom_sf(mapping = aes(fill = cat_var), color = NA, size = 0.05) + labs(fill = "Categorical variable") ``` ![](README_files/figure-gfm/county-1.png) ## Styles `library(urbnmapr)` works well with [\`library(urbnthemes)](https://github.com/UrbanInstitute/urbnthemes) ``` r library(urbnthemes) set_urbn_defaults(style = "map") ``` ## Warning: New theme missing the following elements: axis.ticks.length.x, ## axis.ticks.length.x.top, axis.ticks.length.x.bottom, axis.ticks.length.y, ## axis.ticks.length.y.left, axis.ticks.length.y.right ``` r states_sf <- get_urbn_map(map = "states", sf = TRUE) states_sf %>% left_join(statedata, by = "state_name") %>% ggplot() + geom_sf(mapping = aes(fill = horate), color = "#ffffff", size = 0.25) + scale_fill_gradientn(labels = scales::percent) + labs(fill = "Homeownership rate") + coord_sf(datum = NA) ``` ![](README_files/figure-gfm/theme-state-1.png) Map smaller geographies with `filter()`. You may need to reproject the data based on which areas you are mapping. ``` r household_data %>% filter(state_name == "California") %>% ggplot() + geom_sf(mapping = aes(fill = medhhincome), color = "#ffffff", size = 0.05) + coord_sf(datum = NA) + scale_fill_gradientn(labels = scales::dollar) + labs(fill = "Median household income") ``` ![](README_files/figure-gfm/theme-counties-1.png) A discrete color scale can also be used for categorical data. ``` r state_categorical <- left_join(get_urbn_map(map = "states", sf = TRUE), statedata, by = "state_name") %>% mutate(cat_var = paste0("Group ", sample(1:4, nrow(statedata), replace = TRUE))) ggplot() + geom_sf(state_categorical, mapping = aes(fill = cat_var), color = "#ffffff") + scale_fill_discrete() + coord_sf(datum = NA) + labs(fill = "Categorical variable") ``` ![](README_files/figure-gfm/state-discrete-1.png) ## License Code released under the GNU General Public License v3.0. ## Code of conduct Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms. ================================================ FILE: data-raw/ccdf.R ================================================ # American Samoa needs multiple transformations. The transformation are simpler # with the county data. get American Samoa, tidy, add fips data, and remove # county data american_samoa <- get_ccdf_shapefile(2016, "county", "5m") %>% filter(state_name == "American Samoa") # get state shapefile, tidy, add fips data ccdf <- get_ccdf_shapefile(2016, "state", "5m") %>% filter(state_fips %in% c("02", "11", "15", "52", "66", "69", "72", "78")) %>% mutate(group = as.character(group), piece = as.character(piece)) ccdf <- bind_rows(ccdf, american_samoa) ================================================ FILE: data-raw/ccdf_labels.R ================================================ # labels for ccdf map # to be called only by generate_sysdata.R for internal package use ccdf_labels <- readr::read_csv( "state_name, lat, long, state_abbv Alabama, 32.7794, -86.8287, AL Alaska, 45.5, -133, AK American Samoa, 31.2, -127, AS Arizona, 34.2744, -111.6602, AZ Arkansas, 34.8938, -92.4426, AR California, 37.1841, -119.4696, CA Colorado, 38.9972, -105.5478, CO Connecticut, 41, -71.5, CT Delaware, 39, -73.6, DE District of Columbia, 36.7, -73.2, DC Florida, 28.6305, -81.6, FL Georgia, 32.6415, -83.4426, GA Guam, 36.6, -129, GU Hawaii, 35, -125.5, HI Idaho, 44.3509, -115, ID Illinois, 40.0417, -89.1965, IL Indiana, 39.8942, -86.2816, IN Iowa, 42.0751, -93.4960, IA Kansas, 38.4937, -98.3804, KS Kentucky, 37.5347, -85.3021, KY Louisiana, 31.5, -92.7, LA Maine, 45.3695, -69.2428, ME Mariana Islands, 35, -133, MP Maryland, 38, -74, MD Massachusetts, 42.2596, -69, MA Michigan, 43, -84.5, MI Minnesota, 46.2807, -94.3053, MN Mississippi, 32.7364, -89.6678, MS Missouri, 38.3566, -92.4580, MO Montana, 47.0527, -109.6333, MT Nebraska, 41.5378, -99.7951, NE Nevada, 39.3289, -116.6312, NV New Hampshire, 45.8, -71.7, NH New Jersey, 40.1907, -73, NJ New Mexico, 34.4071, -106.1126, NM New York, 42.9538, -75, NY North Carolina, 35.5557, -79.3877, NC North Dakota, 47.4501, -100.4659, ND Ohio, 40.2862, -82.7937, OH Oklahoma, 35.5889, -97.4943, OK Oregon, 43.9336, -120.5583, OR Pennsylvania, 40.8781, -77.7996, PA Puerto Rico, 31, -74.5, PR Rhode Island, 41, -69.8, RI South Carolina, 33.9169, -80.8964, SC South Dakota, 44.4443, -100.2263, SD Tennessee, 35.8580, -86.3505, TN Texas, 31.4757, -99.3312, TX Utah, 39.3055, -111.6703, UT Vermont, 45.5, -74, VT Virgin Islands, 27.3, -75.5, VI Virginia, 37.6, -78.3, VA Washington, 47.3826, -120, WA West Virginia, 38.6409, -80.6227, WV Wisconsin, 44.6243, -89.9941, WI Wyoming, 42.9957, -107.5512, WY") ================================================ FILE: data-raw/counties.R ================================================ # load utility functions source('data-raw/utils.R') # get state shapefile, tidy, add fips data counties <- get_shapefile(2016, 'county', '5m') %>% tidy(region = "GEOID") %>% rename(county_fips = id) %>% as_tibble() %>% left_join(get_county_fips(), by = "county_fips") %>% filter(!state_fips %in% c("60", "66", "69", "72", "78")) # compress and save save(counties, file = 'data/counties.rda', compress = 'bzip2') ================================================ FILE: data-raw/counties_labels.R ================================================ # generate counties labels # to be called only by generate_sysdata.R for internal package use library(dplyr) counties_labels <- urbnmapr::counties %>% group_by(county_name, state_name, county_fips, state_fips, fips_class) %>% summarize(lat = mean(lat), long = mean(long)) %>% ungroup() ================================================ FILE: data-raw/counties_sf.R ================================================ # get county shapefile, convert to SF, add fips data, filter out territories counties_sf <- get_shapefile(2016, 'county', '5m') %>% sf::st_as_sf() %>% # set prejection to US National Atlas Equal Area sf::st_transform(crs = 2163) %>% mutate(county_fips = paste0(STATEFP, COUNTYFP)) %>% select(county_fips) %>% left_join(get_county_fips(), by = "county_fips") %>% filter(!state_fips %in% c("60", "66", "69", "72", "78")) ================================================ FILE: data-raw/countydata.R ================================================ library(tidyverse) # read county level household variables from Sloan database temp <- tempfile(fileext = '.zip') download.file('https://s3.amazonaws.com/ui-spark-social-science-public/sloan-hfpc-data/county_household_csv.zip', temp) temp_dir <- tempdir() unzip(temp, exdir = temp_dir, junkpaths = TRUE) countydata <- read_csv(paste(temp_dir, 'county_household.csv', sep='/'), guess_max = 40000) countydata <- countydata %>% # recode county changes - see https://www.census.gov/geo/reference/county-changes.html # Shannon County, SD changed name to Oglala Lakota County effective May 1, 2015 mutate(county = if_else(county == '46113', '46102', county)) %>% # Wade Hampton Census Area, AK changed name and code to Kusilvak Census Area effective July 1, 2015 mutate(county = if_else(county == '02270', '02158', county)) %>% filter(YEAR == 2015) %>% mutate(hhpop = OWNERSHP_1 + OWNERSHP_2, horate = OWNERSHP_1 / hhpop) %>% select(year = YEAR, county_fips = county, hhpop, horate, medhhincome = HHINCOME_P50) save(countydata, file = 'data/countydata.rda', compress = 'bzip2') ================================================ FILE: data-raw/generate_sysdata.R ================================================ # source & save various data creation files for internal sysdata.rda source('data-raw/utils.R') source('data-raw/states_labels.R') source('data-raw/counties_labels.R') source('data-raw/ccdf_labels.R') source('data-raw/territories_labels.R') source('data-raw/territories_counties.R') source('data-raw/territories.R') source('data-raw/ccdf.R') # sf data source('data-raw/counties_sf.R') source('data-raw/territories_counties_sf.R') source('data-raw/states_sf.R') source('data-raw/territories_sf.R') save(states_labels, states_labels_sf, counties_labels, ccdf_labels, territories_labels, territories_labels_sf, territories_counties, territories, ccdf, counties_sf, territories_counties_sf, states_sf, territories_sf, file = 'R/sysdata.rda', compress = 'bzip2') ================================================ FILE: data-raw/statedata.R ================================================ library(tidyverse) # read county level household variables from Sloan database temp <- tempfile(fileext = '.zip') download.file('https://s3.amazonaws.com/ui-spark-social-science-public/sloan-hfpc-data/state_household_csv.zip', temp) temp_dir <- tempdir() unzip(temp, exdir = temp_dir, junkpaths = TRUE) statedata <- read_csv(paste(temp_dir, 'state_household.csv', sep='/'), guess_max = 40000) statedata <- statedata %>% filter(YEAR == 2015) %>% # create accurate state FIPS code variable mutate(state_fips = ifelse(str_length(state) == 1, paste0("0", state), state)) %>% mutate(hhpop = OWNERSHP_1 + OWNERSHP_2, horate = OWNERSHP_1 / hhpop) %>% select(year = YEAR, state_fips, state_name = STATENAME, hhpop, horate, medhhincome = HHINCOME_P50) save(statedata, file = 'data/statedata.rda', compress = 'bzip2') ================================================ FILE: data-raw/states.R ================================================ # load utility functions source('data-raw/utils.R') # get state shapefile, tidy, add fips data states <- get_shapefile(2016, 'state', '5m') %>% tidy(region = "STATEFP") %>% rename(state_fips = id) %>% as_tibble() %>% left_join(get_state_fips(), by = "state_fips") %>% filter(!state_fips %in% c("66", "69", "72", "78", "60")) # compress and save save(states, file = 'data/states.rda', compress = 'bzip2') ================================================ FILE: data-raw/states_labels.R ================================================ # states labels # to be called only by generate_sysdata.R for internal package use states_labels <- readr::read_csv( "state_name, lat, long, state_abbv Alabama, 32.7794, -86.8287, AL Alaska, 27.3, -116.5, AK Arizona, 34.2744, -111.6602, AZ Arkansas, 34.8938, -92.4426, AR California, 37.1841, -119.4696, CA Colorado, 38.9972, -105.5478, CO Connecticut, 41, -71.7, CT Delaware, 39, -73.6, DE District of Columbia, 39, -78, DC Florida, 28.6305, -81.6, FL Georgia, 32.6415, -83.4426, GA Hawaii, 26, -107, HI Idaho, 44.3509, -115, ID Illinois, 40.0417, -89.1965, IL Indiana, 39.8942, -86.2816, IN Iowa, 42.0751, -93.4960, IA Kansas, 38.4937, -98.3804, KS Kentucky, 37.5347, -85.3021, KY Louisiana, 31.5, -92.7, LA Maine, 45.3695, -69.2428, ME Maryland, 38, -74, MD Massachusetts, 42.2596, -69, MA Michigan, 43, -84.5, MI Minnesota, 46.2807, -94.3053, MN Mississippi, 32.7364, -89.6678, MS Missouri, 38.3566, -92.4580, MO Montana, 47.0527, -109.6333, MT Nebraska, 41.5378, -99.7951, NE Nevada, 39.3289, -116.6312, NV New Hampshire, 45.8, -71.7, NH New Jersey, 40.1907, -73, NJ New Mexico, 34.4071, -106.1126, NM New York, 42.9538, -75, NY North Carolina, 35.5557, -79.3877, NC North Dakota, 47.4501, -100.4659, ND Ohio, 40.2862, -82.7937, OH Oklahoma, 35.5889, -97.4943, OK Oregon, 43.9336, -120.5583, OR Pennsylvania, 40.8781, -77.7996, PA Rhode Island, 41, -69.6, RI South Carolina, 33.9169, -80.8964, SC South Dakota, 44.4443, -100.2263, SD Tennessee, 35.8580, -86.3505, TN Texas, 31.4757, -99.3312, TX Utah, 39.3055, -111.6703, UT Vermont, 45.5, -74, VT Virginia, 37.6, -78.3, VA Washington, 47.3826, -120, WA West Virginia, 38.6409, -80.6227, WV Wisconsin, 44.6243, -89.9941, WI Wyoming, 42.9957, -107.5512, WY") # create identical SF version states_labels_sf <- states_labels %>% # convert to SF sf::st_as_sf(coords = c("long", "lat")) %>% # set CRS sf::st_set_crs(4326) %>% # transform CRS sf::st_transform(crs = 2163) %>% # add FIPS codes left_join(get_state_fips(), by = c("state_name", "state_abbv")) ================================================ FILE: data-raw/states_sf.R ================================================ # get state shapefile, convert to SF, add fips data states_sf <- get_shapefile(2016, 'state', '5m') %>% sf::st_as_sf() %>% # set prejection to US National Atlas Equal Area sf::st_transform(crs = 2163) %>% select(state_fips = STATEFP) %>% left_join(get_state_fips(), by = "state_fips") %>% filter(!state_fips %in% c("66", "69", "72", "78", "60")) ================================================ FILE: data-raw/territories.R ================================================ # American Samoa needs multiple transformations. The transformation are simpler # with the county data. get American Samoa, tidy, add fips data, and remove # county data american_samoa <- get_shapefile(2016, 'county', '5m') %>% tidy(region = "GEOID") %>% rename(county_fips = id) %>% as_tibble() %>% left_join(get_county_fips(), by = "county_fips") %>% filter(state_name == "American Samoa") %>% select(-county_fips, -county_name, -fips_class) %>% mutate(group = as.character(group), piece = as.character(piece)) # get state shapefile, tidy, add fips data territories <- get_shapefile(2016, 'state', '5m') %>% tidy(region = "GEOID") %>% rename(state_fips = id) %>% as_tibble() %>% left_join(get_state_fips(), by = "state_fips") %>% filter(state_fips %in% c("02", "15", "66", "69", "72", "78")) %>% mutate(group = as.character(group), piece = as.character(piece)) territories <- bind_rows(territories, american_samoa) ================================================ FILE: data-raw/territories_counties.R ================================================ # get state shapefile, tidy, add fips data territories_counties <- get_shapefile(2016, 'county', '5m') %>% tidy(region = "GEOID") %>% rename(county_fips = id) %>% as_tibble() %>% left_join(get_county_fips(), by = "county_fips") %>% filter(state_fips %in% c("02", "15", "60", "66", "69", "72", "78")) ================================================ FILE: data-raw/territories_counties_sf.R ================================================ # get county shapefile, convert to SF, add fips data territories_counties_sf <- get_shapefile(2016, 'county', '5m') %>% sf::st_as_sf() %>% # set prejection to US National Atlas Equal Area sf::st_transform(crs = 2163) %>% mutate(county_fips = paste0(STATEFP, COUNTYFP)) %>% select(county_fips) %>% left_join(get_county_fips(), by = "county_fips") %>% filter(state_fips %in% c("02", "15", "60", "66", "69", "72", "78")) ================================================ FILE: data-raw/territories_labels.R ================================================ # territories lables # to be called only by generate_sysdata.R for internal package use territories_labels <- readr::read_csv( "county_name, state_name, county_fips, state_fips, fips_class, lat, long, state_abbv American Samoa, American Samoa, NA, 60, NA, 19.5, -90, AS Guam, Guam, NA, 66, NA, 20, -100, GU Mariana Islands, Mariana Islands, NA, 69, NA, 22, -78.5, MP Puerto Rico, Puerto Rico, NA, 43, NA, 21, -94, PR Virgin Islands, Virgin Islands, NA, 78, NA, 18, -81, VI", col_types = cols(county_name = col_character(), state_name = col_character(), county_fips = col_character(), state_fips = col_character(), fips_class = col_character(), lat = col_double(), long = col_double(), state_abbv = col_character())) territories_labels_sf <- territories_labels %>% # convert to SF sf::st_as_sf(coords = c("long", "lat")) %>% # set crs to match states sf::st_set_crs(4326) %>% # transform CRS sf::st_transform(crs = 2163) %>% # get rid of county variables select(-county_name, -fips_class, -county_fips) ================================================ FILE: data-raw/territories_sf.R ================================================ # American Samoa needs multiple transformations. The transformation are simpler # with the county data. get American Samoa, tidy, add fips data, and remove # county data american_samoa_sf <- get_shapefile(2016, 'county', '5m') %>% sf::st_as_sf() %>% # set prejection to US National Atlas Equal Area sf::st_transform(crs = 2163) %>% mutate(county_fips = paste0(STATEFP, COUNTYFP)) %>% select(county_fips) %>% left_join(get_county_fips(), by = "county_fips") %>% filter(state_name == "American Samoa") %>% select(-county_fips, -county_name, -fips_class) %>% group_by(state_name, state_abbv, state_fips) %>% summarize() %>% sf::st_as_sf() # get state shapefile, tidy, add fips data territories_sf <- get_shapefile(2016, 'state', '5m') %>% sf::st_as_sf() %>% # set prejection to US National Atlas Equal Area sf::st_transform(crs = 2163) %>% select(state_fips = STATEFP) %>% left_join(get_state_fips(), by = "state_fips") %>% filter(state_fips %in% c("02", "15", "66", "69", "72", "78")) territories_sf <- rbind(territories_sf, american_samoa_sf) ================================================ FILE: data-raw/utils.R ================================================ ### helper functions for parsing shapefile data -------------------------------- # load necessary libraries ----------------------------------------------------- library(dplyr) library(readr) library(rgeos) library(maptools) library(rgdal) library(magrittr) library(broom) # transform AK/HI from shapefile ----------------------------------------------- # see https://github.com/wmurphyrd/fiftystater --------------------------------- transform_state <- function(object, rot, scale, shift) { object %>% elide(rotate = rot) %>% elide(scale = max(apply(bbox(object), 1, diff)) / scale) %>% elide(shift = shift) } # retrieve shapefile from census and apply AK/HI transformations --------------- get_shapefile <- function(year, level, resolution) { # set shapefile url url_base <- 'http://www2.census.gov/geo/tiger/GENZ2016/shp/' shape_base <- paste('cb', year, 'us', level, resolution, sep = '_') url <- paste0(url_base, shape_base, '.zip') # download data and unzip temp <- tempfile(fileext = '.zip') download.file(url, temp) temp_dir <- tempdir() unzip(temp, exdir = temp_dir) # read shapefile shapes <- readOGR(dsn = temp_dir, layer = shape_base, verbose = F) %>% spTransform(CRS("+init=epsg:2163")) # transform AK alaska <- shapes[shapes$STATEFP == "02", ] %>% transform_state(-35, 2, c(-2600000, -2300000)) proj4string(alaska) <- proj4string(shapes) # transform HI hawaii <- shapes[shapes$STATEFP == "15", ] %>% transform_state(-35, 0.8, c(-1170000, -2363000)) proj4string(hawaii) <- proj4string(shapes) # transform Guam guam <- shapes[shapes$STATEFP %in% c("66"), ] %>% transform_state(rot = -35, scale = 0.2, shift = c(-180000, -2700000)) proj4string(guam) <- proj4string(shapes) # transform Puerto Rico puerto_rico <- shapes[shapes$STATEFP %in% c("72"), ] %>% transform_state(rot = 20, scale = .5, shift = c(200000, -2500000)) proj4string(puerto_rico) <- proj4string(shapes) # transform American Samoa american_samoa <- shapes[shapes$STATEFP %in% c("60"), ] %>% transform_state(rot = 0, scale = 0.1, shift = c(-1250000, -5050000)) proj4string(american_samoa) <- proj4string(shapes) # treat islands differently as1 <- american_samoa[!american_samoa$NAME %in% c("Rose Island", "Swains Island", "Manu'a"), ] %>% transform_state(rot = 0, scale = 1.2, shift = c(950000, -2350000)) proj4string(as1) <- proj4string(shapes) as2 <- american_samoa[american_samoa$NAME %in% c("Manu'a"), ] %>% transform_state(rot = 0, scale = 1.2, shift = c(1450000, -2800000)) proj4string(as2) <- proj4string(shapes) american_samoa <- rbind(as1, as2) %>% # angle and size need to be slightly adjusted transform_state(rot = 15, scale = 1, shift = c(1000000,-3000000)) proj4string(american_samoa) <- proj4string(shapes) # transform US Virgin Islands virgin_islands <- shapes[shapes$STATEFP %in% c("78"), ] %>% transform_state(rot = 0, scale = 0.2, shift = c(1550000, -2700000)) proj4string(virgin_islands) <- proj4string(shapes) # transform Mariana Islands mariana_islands <- shapes[shapes$STATEFP %in% c("69"), ] %>% transform_state(rot = -35, scale = 0.3, shift = c(2150000, -2450000)) proj4string(mariana_islands) <- proj4string(shapes) # recombine shapefile exclude <- c("02", "15", "60", "66", "69", "72", "78") mapdata <- shapes[!shapes$STATEFP %in% exclude, ] %>% rbind(alaska, hawaii, guam, puerto_rico, virgin_islands, mariana_islands, american_samoa) %>% # convert from EPSG2163 to (US National Atlas Equal Area) WGS84 spTransform(CRS("+init=epsg:4326")) mapdata } # retrieve shapefile from census and apply AK/HI transformations --------------- get_ccdf_shapefile <- function(year, level, resolution) { # set shapefile url url_base <- 'http://www2.census.gov/geo/tiger/GENZ2016/shp/' shape_base <- paste('cb', year, 'us', level, resolution, sep = '_') url <- paste0(url_base, shape_base, '.zip') # download data and unzip temp <- tempfile(fileext = '.zip') download.file(url, temp) temp_dir <- tempdir() unzip(temp, exdir = temp_dir) # read shapefile shapes <- readOGR(dsn = temp_dir, layer = shape_base, verbose = F) %>% spTransform(CRS("+init=epsg:2163")) # transform AK alaska <- shapes[shapes$STATEFP == "02", ] %>% transform_state(-5, 2, c(-3500000, -200000)) proj4string(alaska) <- proj4string(shapes) # transform HI hawaii <- shapes[shapes$STATEFP == "15", ] %>% transform_state(0, 0.8, c(-2500000, -1000000)) proj4string(hawaii) <- proj4string(shapes) # transform Guam guam <- shapes[shapes$STATEFP %in% c("66"), ] %>% transform_state(rot = -35, scale = 0.3, shift = c(-2600000, -700000)) proj4string(guam) <- proj4string(shapes) # transform Puerto Rico puerto_rico <- shapes[shapes$STATEFP %in% c("72"), ] %>% transform_state(rot = 0, scale = 1, shift = c(-1350000, 1000000)) proj4string(puerto_rico) <- proj4string(shapes) # transform American Samoa american_samoa <- shapes[shapes$STATEFP %in% c("60"), ] %>% transform_state(rot = 0, scale = 0.1, shift = c(-1250000, -5050000)) proj4string(american_samoa) <- proj4string(shapes) # treat islands differently as1 <- american_samoa[!american_samoa$NAME %in% c("Rose Island", "Swains Island", "Manu'a"), ] %>% transform_state(rot = 0, scale = 1.2, shift = c(200000, -2800000)) proj4string(as1) <- proj4string(shapes) as2 <- american_samoa[american_samoa$NAME %in% c("Manu'a"), ] %>% transform_state(rot = 0, scale = 1.2, shift = c(400000, -2800000)) proj4string(as2) <- proj4string(shapes) american_samoa <- rbind(as1, as2) %>% # angle and size need to be slightly adjusted transform_state(rot = 15, scale = 1, shift = c(-2800000,-1300000)) proj4string(american_samoa) <- proj4string(shapes) # transform US Virgin Islands virgin_islands <- shapes[shapes$STATEFP %in% c("78"), ] %>% transform_state(rot = 0, scale = 0.2, shift = c(2200000, -1850000)) proj4string(virgin_islands) <- proj4string(shapes) # transform Mariana Islands mariana_islands <- shapes[shapes$STATEFP %in% c("69"), ] %>% transform_state(rot = -35, scale = 0.1, shift = c(-3600000, -1250000)) proj4string(mariana_islands) <- proj4string(shapes) mariana_islands <- mariana_islands %>% # transforms into longitude/latitude spTransform(CRS("+init=epsg:4326")) %>% # prime meridian/equator tidy(region = "STATEFP") %>% as_tibble() %>% filter(piece %in% 1:2) # combine, transform, and tidy ellided_areas <- c("02", "14", "15", "43", "52", "60", "66", "69", "72", "78") fifty_states <- shapes[!shapes$STATEFP %in% ellided_areas, ] %>% rbind(alaska) %>% rbind(hawaii) %>% rbind(puerto_rico) %>% rbind(virgin_islands) %>% rbind(guam) %>% rbind(american_samoa) %>% # convert from EPSG2163 to (US National Atlas Equal Area) WGS84 spTransform(CRS("+init=epsg:4326")) %>% tidy(region = "STATEFP") %>% mutate(id = id) %>% as_tibble() %>% rbind(mariana_islands) # star for Washington, D.C. ----------------------------------------------- star <- tribble( ~x, ~y, ~order, ~hole, ~piece, ~group, ~id, 1, 0, 1, FALSE, 1, "11", "11", 0.3, -0.2, 2, FALSE, 1, "11", "11", 0.3, -0.95, 3, FALSE, 1, "11", "11", -0.1, -0.375, 4, FALSE, 1, "11", "11", -0.8, -0.6, 5, FALSE, 1, "11", "11", -0.39, 0, 6, FALSE, 1, "11", "11", -0.8, 0.6, 7, FALSE, 1, "11", "11", -0.1, 0.375, 8, FALSE, 1, "11", "11", 0.3, 0.95, 9, FALSE, 1, "11", "11", 0.3, 0.2, 10, FALSE, 1, "11", "11", 1, 0, 11, FALSE, 1, "11", "11" ) %>% # roate star by mutliplying points by rotation matrix mutate(long = x * cos(pi / 2) + y * -sin(pi / 2), lat = x * sin(pi / 2) + y * cos(pi / 2)) %>% # scale the plots big time mutate(long = long, lat = lat) %>% # transpose the plot to near DC mutate(long = long - 75, lat = lat + 37) %>% select(-x, -y) # combine states and territories ------------------------------------------ ccdf <- rbind(fifty_states, star) %>% filter(id %in% c("11", ellided_areas)) %>% rename(state_fips = id) ids <- tribble(~state_name, ~state_abbv, ~state_fips, "Alaska", "AK", "02", "Hawaii", "HI", "15", "American Samoa", "AS", "60", "Commonwealth of the Northern Mariana Islands", "MP", "69", "Guam", "GU", "66", "Puerto Rico", "PR", "72", "United States Virgin Islands", "VI", "52", "United States Virgin Islands", "VI", "78", "Washington, D.C.", "DC", "11") ccdf <- left_join(ccdf, ids, by = "state_fips") ccdf } # download and clean state fips data from census get_state_fips <- function() { state_fips <- tribble(~state_fips, ~state_abbv, ~state_name, "01", "AL", "Alabama", "02", "AK", "Alaska", "04", "AZ", "Arizona", "05", "AR", "Arkansas", "06", "CA", "California", "08", "CO", "Colorado", "09", "CT", "Connecticut", "10", "DE", "Delaware", "11", "DC", "District of Columbia", "12", "FL", "Florida", "13", "GA", "Georgia", "15", "HI", "Hawaii", "16", "ID", "Idaho", "17", "IL", "Illinois", "18", "IN", "Indiana", "19", "IA", "Iowa", "20", "KS", "Kansas", "21", "KY", "Kentucky", "22", "LA", "Louisiana", "23", "ME", "Maine", "24", "MD", "Maryland", "25", "MA", "Massachusetts", "26", "MI", "Michigan", "27", "MN", "Minnesota", "28", "MS", "Mississippi", "29", "MO", "Missouri", "30", "MT", "Montana", "31", "NE", "Nebraska", "32", "NV", "Nevada", "33", "NH", "New Hampshire", "34", "NJ", "New Jersey", "35", "NM", "New Mexico", "36", "NY", "New York", "37", "NC", "North Carolina", "38", "ND", "North Dakota", "39", "OH", "Ohio", "40", "OK", "Oklahoma", "41", "OR", "Oregon", "42", "PA", "Pennsylvania", "44", "RI", "Rhode Island", "45", "SC", "South Carolina", "46", "SD", "South Dakota", "47", "TN", "Tennessee", "48", "TX", "Texas", "49", "UT", "Utah", "50", "VT", "Vermont", "51", "VA", "Virginia", "53", "WA", "Washington", "54", "WV", "West Virginia", "55", "WI", "Wisconsin", "56", "WY", "Wyoming", "60", "AS", "American Samoa", "66", "GU", "Guam", "69", "MP", "Mariana Islands", "72", "PR", "Puerto Rico", "78", "VI", "Virgin Islands") state_fips } # download and clean county fips data from census get_county_fips <- function() { url <- 'https://www2.census.gov/geo/docs/reference/codes/national_county.txt' county_fips <- read_csv(url, col_names = c('state_abbv', 'state_fips', 'county_fips', 'county_name', 'fips_class'), col_types = 'ccccc') %>% mutate(county_fips = paste0(state_fips, county_fips)) %>% # recode county changes - see https://www.census.gov/geo/reference/county-changes.html # Shannon County, SD changed name to Oglala Lakota County effective May 1, 2015 mutate(county_name = if_else(county_fips == '46113', 'Oglala Lakota County', county_name)) %>% mutate(county_fips = if_else(county_fips == '46113', '46102', county_fips)) %>% # Wade Hampton Census Area, AK changed name and code to Kusilvak Census Area effective July 1, 2015 mutate(county_name = if_else(county_fips == '02270', 'Kusilvak Census Area', county_name)) %>% mutate(county_fips = if_else(county_fips == '02270', '02158', county_fips)) %>% # add in state name from state fips file left_join(get_state_fips()) county_fips } ================================================ FILE: docs/CODE_OF_CONDUCT.html ================================================ Contributor Code of Conduct • urbnmapr

As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.

We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion.

Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.

Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.

This Code of Conduct is adapted from the Contributor Covenant, version 1.0.0, available at https://www.contributor-covenant.org/version/1/0/0/code-of-conduct.html

Site built with pkgdown 1.3.0.

================================================ FILE: docs/articles/index.html ================================================ Articles • urbnmapr

All vignettes

Site built with pkgdown 1.3.0.

================================================ FILE: docs/articles/introducing-urbnmapr.html ================================================ Introducing urbnmapr • urbnmapr

The urbnmapr package provides state, county, and other shapefiles in tibble format that is compatible to map with ggplot2. Shapefiles include Alaska and Hawaii, transformed to be displayed as insets within the continental United States.

This package is heavily inspired by and derived in part from the fiftystater package by William Murphy. In contrast, urbnmapr:

  • Uses shapefiles from the US Census Bureau
  • Converts the shapefile data to a tibble data frame
  • Adds various identifiers for merging
  • Includes a county-level shapefile

Getting data

There are two methods for accessing map data in urbnmapr. First, urbnmapr contains two tibble data frames, states and counties, for easily accessing simple state and county map data.

The states and counties tibbles can be used with geom_polygon() and coord_map() to create base maps of the continental United States, with Alaska and Hawaii displayed as insets:

library(tidyverse)
library(urbnmapr)

states %>%
  ggplot(aes(long, lat, group = group)) +
    geom_polygon(fill = "grey", color = "#ffffff", size = 0.25) +
    coord_map(projection = "albers", lat0 = 39, lat1 = 45)

counties %>%
  ggplot(aes(long, lat, group = group)) +
    geom_polygon(fill = "grey", color = "#ffffff", size = 0.05) +
    coord_map(projection = "albers", lat0 = 39, lat1 = 45)

Second, the function get_urbn_map() accesses additional maps including “ccdf”, which includes elided territories roughly positioned in the direction of their true location, and “territories_counties”, which includes territories below the continuous 48 states.

ccdf <- get_urbn_map(map = "territories_counties")

ccdf %>%
  ggplot(aes(long, lat, group = group)) +
    geom_polygon(fill = "grey", color = "#ffffff", size = 0.25) +
    scale_x_continuous(limits = c(-141, -55)) +
    scale_y_continuous(limits = c(24, 50)) +  
    coord_map(projection = "albers", lat0 = 39, lat1 = 45)

Merging data

All tibbles include various identifiers to simplify merging data. The states states tibble contains state_fips, state_abbv, and state_name. The counties tibble contains county_fips, state_abbv, state_fips, county_name, and state_name. Both tibbles can be piped into ggplot2 to create a choropleth map.

statedata %>% 
  left_join(states, by = "state_name") %>% 
  ggplot(mapping = aes(long, lat, group = group, fill = horate)) +
  geom_polygon(color = "#ffffff", size = 0.25) +
  coord_map(projection = "albers", lat0 = 39, lat1 = 45) +
  labs(fill = "Homeownership rate")

household_data <- left_join(countydata, counties, by = "county_fips") 

household_data %>%
  ggplot(aes(long, lat, group = group, fill = medhhincome)) +
    geom_polygon(color = "#ffffff", size = 0.05) +
    coord_map(projection = "albers", lat0 = 39, lat1 = 45)

Labels

The function get_urbn_labels() accesses additional labels including “ccdf”, which includes elided territories roughly positioned in the direction of their true location, and “territories_counties”, which includes territories below the continuous 48 states.

library(tidyverse)
library(urbnmapr)

ccdf <- get_urbn_map(map = "ccdf")
ccdf_labels <- get_urbn_labels(map = "ccdf")

ccdf %>%
  ggplot() +
    geom_polygon(aes(long, lat, group = group), 
                 fill = "grey", color = "#ffffff", size = 0.25) +
    geom_text(data = ccdf_labels, aes(long, lat, label = state_abbv), size = 3) +  
    scale_x_continuous(limits = c(-141, -55)) +
    scale_y_continuous(limits = c(24, 50)) +  
    coord_map(projection = "albers", lat0 = 39, lat1 = 45)

Styles

library(urbnmapr) works well with the library(urbnthemes)

library(urbnthemes)

set_urbn_defaults(style = "map")

statedata %>% 
  left_join(states, by = "state_name") %>% 
  ggplot(mapping = aes(long, lat, group = group, fill = horate)) +
  geom_polygon(color = "#ffffff", size = 0.25) +
  coord_map(projection = "albers", lat0 = 39, lat1 = 45) +
  scale_fill_gradientn(labels = scales::percent) +
   theme(legend.position = "right",
         legend.direction = "vertical",
         legend.title = element_text(face = "bold", size = 11),
         legend.key.height = unit(.2, "in")) +
  labs(fill = "Homeownership rate")

household_data %>%
  filter(state_name %in% c("Virginia", "Maryland", "District of Columbia")) %>%
  ggplot(aes(long, lat, group = group, fill = medhhincome)) +
    geom_polygon(color = "#ffffff", size = 0.05) +
    coord_map(projection = "albers", lat0 = 39, lat1 = 45) +
    scale_fill_gradientn(labels = scales::dollar) +
    theme(legend.position = "right",
          legend.direction = "vertical",
          legend.title = element_text(face = "bold", size = 11),
          legend.key.height = unit(.25, "in")) +
  labs(fill = "Median household income")

Site built with pkgdown 1.3.0.

================================================ FILE: docs/articles/start-to-finish.html ================================================ Start to finish • urbnmapr

State choropleth

Packages

library(tidyverse)
library(urbnmapr)

source("https://raw.githubusercontent.com/UrbanInstitute/urban_R_theme/urban_R_theme_revamp/urban_theme.R")
## Warning: New theme missing the following elements: plot.tag,
## plot.tag.position

Merge data

USArrests_merged <- USArrests %>%
  rownames_to_column("state_name") %>%
  select(state_name, Murder) %>%
  left_join(states, by = "state_name")

Pick a projection

The world is approximately a 3-dimensional sphere. Maps are two-dimensional. Projections are transformations from points on the sphere to points on a map. Different situations require different projections. The Albers Equal-Area Conic Projection is a common choice for choropleths of the entire United States.

Add coord_map(projection = "albers", lat0 = 39, lat1 = 45) to your ggplot2 call to use this projection.

Plot

Plot the merged data set from above using library(ggplot2). long, lat, and group

 USArrests_merged %>%
  ggplot(aes(long, lat, group = group, fill = Murder)) +
    geom_polygon(color = "#ffffff", size = 0.25) +
    coord_map(projection = "albers", lat0 = 39, lat1 = 45) +
    scale_fill_gradientn() +
    urban_map +
    theme(legend.position = "right",
          legend.direction = "vertical",
          legend.title = element_text(face = "bold", size = 11))

Save

Export

Site built with pkgdown.

================================================ FILE: docs/authors.html ================================================ Authors • urbnmapr
  • Sarah Strochak. Author, maintainer.

  • Kyle Ueyama. Author.

  • Aaron Williams. Author.

  • Urban Institute. Copyright holder.

  • William Murphy. Contributor, copyright holder.
    Original author for copied and derived code for fiftystater

  • Barry Rowlingson. Contributor.
    Original author for copied and derived code for fiftystater

Site built with pkgdown 1.3.0.

================================================ FILE: docs/docsearch.css ================================================ /* Docsearch -------------------------------------------------------------- */ /* Source: https://github.com/algolia/docsearch/ License: MIT */ .algolia-autocomplete { display: block; -webkit-box-flex: 1; -ms-flex: 1; flex: 1 } .algolia-autocomplete .ds-dropdown-menu { width: 100%; min-width: none; max-width: none; padding: .75rem 0; background-color: #fff; background-clip: padding-box; border: 1px solid rgba(0, 0, 0, .1); box-shadow: 0 .5rem 1rem rgba(0, 0, 0, .175); } @media (min-width:768px) { .algolia-autocomplete .ds-dropdown-menu { width: 175% } } .algolia-autocomplete .ds-dropdown-menu::before { display: none } .algolia-autocomplete .ds-dropdown-menu [class^=ds-dataset-] { padding: 0; background-color: rgb(255,255,255); border: 0; max-height: 80vh; } .algolia-autocomplete .ds-dropdown-menu .ds-suggestions { margin-top: 0 } .algolia-autocomplete .algolia-docsearch-suggestion { padding: 0; overflow: visible } .algolia-autocomplete .algolia-docsearch-suggestion--category-header { padding: .125rem 1rem; margin-top: 0; font-size: 1.3em; font-weight: 500; color: #00008B; border-bottom: 0 } .algolia-autocomplete .algolia-docsearch-suggestion--wrapper { float: none; padding-top: 0 } .algolia-autocomplete .algolia-docsearch-suggestion--subcategory-column { float: none; width: auto; padding: 0; text-align: left } .algolia-autocomplete .algolia-docsearch-suggestion--content { float: none; width: auto; padding: 0 } .algolia-autocomplete .algolia-docsearch-suggestion--content::before { display: none } .algolia-autocomplete .ds-suggestion:not(:first-child) .algolia-docsearch-suggestion--category-header { padding-top: .75rem; margin-top: .75rem; border-top: 1px solid rgba(0, 0, 0, .1) } .algolia-autocomplete .ds-suggestion .algolia-docsearch-suggestion--subcategory-column { display: block; padding: .1rem 1rem; margin-bottom: 0.1; font-size: 1.0em; font-weight: 400 /* display: none */ } .algolia-autocomplete .algolia-docsearch-suggestion--title { display: block; padding: .25rem 1rem; margin-bottom: 0; font-size: 0.9em; font-weight: 400 } .algolia-autocomplete .algolia-docsearch-suggestion--text { padding: 0 1rem .5rem; margin-top: -.25rem; font-size: 0.8em; font-weight: 400; line-height: 1.25 } .algolia-autocomplete .algolia-docsearch-footer { width: 110px; height: 20px; z-index: 3; margin-top: 10.66667px; float: right; font-size: 0; line-height: 0; } .algolia-autocomplete .algolia-docsearch-footer--logo { background-image: url("data:image/svg+xml;utf8,"); background-repeat: no-repeat; background-position: 50%; background-size: 100%; overflow: hidden; text-indent: -9000px; width: 100%; height: 100%; display: block; transform: translate(-8px); } .algolia-autocomplete .algolia-docsearch-suggestion--highlight { color: #FF8C00; background: rgba(232, 189, 54, 0.1) } .algolia-autocomplete .algolia-docsearch-suggestion--text .algolia-docsearch-suggestion--highlight { box-shadow: inset 0 -2px 0 0 rgba(105, 105, 105, .5) } .algolia-autocomplete .ds-suggestion.ds-cursor .algolia-docsearch-suggestion--content { background-color: rgba(192, 192, 192, .15) } ================================================ FILE: docs/docsearch.js ================================================ $(function() { // register a handler to move the focus to the search bar // upon pressing shift + "/" (i.e. "?") $(document).on('keydown', function(e) { if (e.shiftKey && e.keyCode == 191) { e.preventDefault(); $("#search-input").focus(); } }); $(document).ready(function() { // do keyword highlighting /* modified from https://jsfiddle.net/julmot/bL6bb5oo/ */ var mark = function() { var referrer = document.URL ; var paramKey = "q" ; if (referrer.indexOf("?") !== -1) { var qs = referrer.substr(referrer.indexOf('?') + 1); var qs_noanchor = qs.split('#')[0]; var qsa = qs_noanchor.split('&'); var keyword = ""; for (var i = 0; i < qsa.length; i++) { var currentParam = qsa[i].split('='); if (currentParam.length !== 2) { continue; } if (currentParam[0] == paramKey) { keyword = decodeURIComponent(currentParam[1].replace(/\+/g, "%20")); } } if (keyword !== "") { $(".contents").unmark({ done: function() { $(".contents").mark(keyword); } }); } } }; mark(); }); }); /* Search term highlighting ------------------------------*/ function matchedWords(hit) { var words = []; var hierarchy = hit._highlightResult.hierarchy; // loop to fetch from lvl0, lvl1, etc. for (var idx in hierarchy) { words = words.concat(hierarchy[idx].matchedWords); } var content = hit._highlightResult.content; if (content) { words = words.concat(content.matchedWords); } // return unique words var words_uniq = [...new Set(words)]; return words_uniq; } function updateHitURL(hit) { var words = matchedWords(hit); var url = ""; if (hit.anchor) { url = hit.url_without_anchor + '?q=' + escape(words.join(" ")) + '#' + hit.anchor; } else { url = hit.url + '?q=' + escape(words.join(" ")); } return url; } ================================================ FILE: docs/index.html ================================================ State and county shapefiles in tibble format • urbnmapr

The urbnmapr package provides state and county shapefiles that are compatible to map with ggplot2.

Shapefiles include Alaska and Hawaii, transformed to be displayed as insets within the continental United States. There are options to include the territories for both the state and county maps.

This package is heavily inspired by and derived in part from the fiftystater package by William Murphy. In contrast, urbnmapr:

  • Uses shapefiles from the US Census Bureau
  • Converts the shapefile data to sf format
  • Adds various identifiers for merging
  • Includes a county-level shapefile and options to add territories

Stay up-to-date

Sign up here to stay up-to-date with R package releases and R resources from the Urban Institute. We will not share your information and we will not email more than once per month.

Installation

You can install the latest version of urbnmapr from GitHub:

# install.packages("devtools")
devtools::install_github("UrbanInstitute/urbnmapr")

Usage

Quick maps

The get_urbn_map() function can be used to call shapefiles. Using the sf = TRUE option will load sf objects. These can be used with geom_sf() to create base maps of the continental United States, with Alaska and Hawaii displayed as insets:

library(tidyverse)
library(urbnmapr)

states_sf <- get_urbn_map("states", sf = TRUE)

states_sf %>% 
  ggplot(aes()) +
  geom_sf(fill = "grey", color = "#ffffff")

library(tidyverse)
library(urbnmapr)

counties_sf <- get_urbn_map("counties", sf = TRUE)

counties_sf %>% 
  ggplot(aes()) +
  geom_sf(fill = "grey", color = "#ffffff")

The default projection is US National Atlas Equal Area.

More maps

Maps with US territories can also be called with get_urbn_map().

territories_counties <- get_urbn_map(map = "territories_counties", sf = TRUE)

ggplot() +
  geom_sf(territories_counties,
          mapping = aes(),
          fill = "grey", color = "#ffffff")

Labels

Labels for states maps can be accessed with get_urbn_labels(). Only state labels are custom, so they can be displayed next to smaller states. Use the function to call the appropriate labels and then label the map with geom_sf_text().

states_sf <- get_urbn_map(map = "states", sf = TRUE)

states_sf %>%
  ggplot() +
  geom_sf(aes(), 
          fill = "grey", color = "#ffffff", size = 0.25) +
  geom_sf_text(data = get_urbn_labels(map = "states", sf = TRUE), 
                aes(label = state_abbv), 
            size = 3)

Merging Data

The states and counties spatial data include various identifiers to simplify merging data. The states states tibble contains state_fips, state_abbv, and state_name. The counties tibble contains county_fips, state_abbv, state_fips, county_name, and state_name.

Continuous data can be mapping on a color scale.

spatial_data <- left_join(statedata,
                          get_urbn_map(map = "states", sf = TRUE),
                          by = "state_name")

ggplot() +
  geom_sf(spatial_data,
          mapping = aes(fill = horate),
          color = "#ffffff", size = 0.25) +
  labs(fill = "Homeownership rate")

Categorical data can be mapped on a discrete color scale.

counties_sf <- get_urbn_map(map = "counties", sf = TRUE)
county_groups <- countydata %>% 
  mutate(cat_var = paste0("Group ",
                          sample(1:4, nrow(countydata), replace = TRUE)))

household_data <- left_join(county_groups, counties_sf, by = "county_fips")

household_data %>%
  ggplot() +
  geom_sf(mapping = aes(fill = cat_var),
          color = NA, size = 0.05) +
  labs(fill = "Categorical variable")

Styles

library(urbnmapr) works well with the Urban Institute ggplot2 theme.

library(urbnthemes)

set_urbn_defaults(style = "map")
states_sf <- get_urbn_map(map = "states", sf = TRUE)

statedata %>% 
  left_join(states_sf, by = "state_name") %>% 
  ggplot() +
  geom_sf(mapping = aes(fill = horate),
          color = "#ffffff", size = 0.25) +
  scale_fill_gradientn(labels = scales::percent) +
  labs(fill = "Homeownership rate") +
  coord_sf(datum = NA)

Map smaller geographies with filter(). You may need to reproject the data based on which areas you are mapping.

household_data %>%
  filter(state_name == "California") %>%
  ggplot() +
    geom_sf(mapping = aes(fill = medhhincome),
                 color = "#ffffff", size = 0.05) +
    coord_sf(datum = NA) +
    scale_fill_gradientn(labels = scales::dollar) +
  labs(fill = "Median household income")

A discrete color scale can also be used for categorical data.

state_categorical <- statedata %>% 
  mutate(cat_var = paste0("Group ",
                          sample(1:4, nrow(statedata), replace = TRUE))) %>% 
  left_join(get_urbn_map(map = "states", sf = TRUE), by = "state_name")


ggplot() +
  geom_sf(state_categorical, mapping = aes(fill = cat_var),
          color = "#ffffff") +
  scale_fill_discrete() +
  coord_sf(datum = NA) +
  labs(fill = "Categorical variable")

License

Code released under the GNU General Public License v3.0.

Code of conduct

Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.

Site built with pkgdown 1.3.0.

================================================ FILE: docs/news/index.html ================================================ Changelog • urbnmapr

urbnmapr 0.0.0.9002

urbnmapr 0.0.0.9001

Two functions have been added to the package, with two additional shape options:

  • get_urbn_map will return the requested shapefile, parsed into a tibble
  • get_urbn_labels will return a tibble of coordinates and map labels

The valid options for each are:

  1. states
  2. counties
  3. ccdf
  4. territories
  5. territories_counties

urbnmapr 0.0.0.9000

This is the initial release of the urbnmapr package. It includes state and county-level shapefiles parsed into a tibble for easy plotting with ggplot2.

Site built with pkgdown 1.3.0.

================================================ FILE: docs/pkgdown.css ================================================ /* Sticky footer */ /** * Basic idea: https://philipwalton.github.io/solved-by-flexbox/demos/sticky-footer/ * Details: https://github.com/philipwalton/solved-by-flexbox/blob/master/assets/css/components/site.css * * .Site -> body > .container * .Site-content -> body > .container .row * .footer -> footer * * Key idea seems to be to ensure that .container and __all its parents__ * have height set to 100% * */ html, body { height: 100%; } body > .container { display: flex; height: 100%; flex-direction: column; padding-top: 60px; } body > .container .row { flex: 1 0 auto; } footer { margin-top: 45px; padding: 35px 0 36px; border-top: 1px solid #e5e5e5; color: #666; display: flex; flex-shrink: 0; } footer p { margin-bottom: 0; } footer div { flex: 1; } footer .pkgdown { text-align: right; } footer p { margin-bottom: 0; } img.icon { float: right; } img { max-width: 100%; } /* Fix bug in bootstrap (only seen in firefox) */ summary { display: list-item; } /* Typographic tweaking ---------------------------------*/ .contents .page-header { margin-top: calc(-60px + 1em); } /* Section anchors ---------------------------------*/ a.anchor { margin-left: -30px; display:inline-block; width: 30px; height: 30px; visibility: hidden; background-image: url(./link.svg); background-repeat: no-repeat; background-size: 20px 20px; background-position: center center; } .hasAnchor:hover a.anchor { visibility: visible; } @media (max-width: 767px) { .hasAnchor:hover a.anchor { visibility: hidden; } } /* Fixes for fixed navbar --------------------------*/ .contents h1, .contents h2, .contents h3, .contents h4 { padding-top: 60px; margin-top: -40px; } /* Static header placement on mobile devices */ @media (max-width: 767px) { .navbar-fixed-top { position: absolute; } .navbar { padding: 0; } } /* Sidebar --------------------------*/ #sidebar { margin-top: 30px; } #sidebar h2 { font-size: 1.5em; margin-top: 1em; } #sidebar h2:first-child { margin-top: 0; } #sidebar .list-unstyled li { margin-bottom: 0.5em; } .orcid { height: 16px; vertical-align: middle; } /* Reference index & topics ----------------------------------------------- */ .ref-index th {font-weight: normal;} .ref-index td {vertical-align: top;} .ref-index .icon {width: 40px;} .ref-index .alias {width: 40%;} .ref-index-icons .alias {width: calc(40% - 40px);} .ref-index .title {width: 60%;} .ref-arguments th {text-align: right; padding-right: 10px;} .ref-arguments th, .ref-arguments td {vertical-align: top;} .ref-arguments .name {width: 20%;} .ref-arguments .desc {width: 80%;} /* Nice scrolling for wide elements --------------------------------------- */ table { display: block; overflow: auto; } /* Syntax highlighting ---------------------------------------------------- */ pre { word-wrap: normal; word-break: normal; border: 1px solid #eee; } pre, code { background-color: #f8f8f8; color: #333; } pre code { overflow: auto; word-wrap: normal; white-space: pre; } pre .img { margin: 5px 0; } pre .img img { background-color: #fff; display: block; height: auto; } code a, pre a { color: #375f84; } a.sourceLine:hover { text-decoration: none; } .fl {color: #1514b5;} .fu {color: #000000;} /* function */ .ch,.st {color: #036a07;} /* string */ .kw {color: #264D66;} /* keyword */ .co {color: #888888;} /* comment */ .message { color: black; font-weight: bolder;} .error { color: orange; font-weight: bolder;} .warning { color: #6A0366; font-weight: bolder;} /* Clipboard --------------------------*/ .hasCopyButton { position: relative; } .btn-copy-ex { position: absolute; right: 0; top: 0; visibility: hidden; } .hasCopyButton:hover button.btn-copy-ex { visibility: visible; } /* mark.js ----------------------------*/ mark { background-color: rgba(255, 255, 51, 0.5); border-bottom: 2px solid rgba(255, 153, 51, 0.3); padding: 1px; } /* vertical spacing after htmlwidgets */ .html-widget { margin-bottom: 10px; } ================================================ FILE: docs/pkgdown.js ================================================ /* http://gregfranko.com/blog/jquery-best-practices/ */ (function($) { $(function() { $("#sidebar") .stick_in_parent({offset_top: 40}) .on('sticky_kit:bottom', function(e) { $(this).parent().css('position', 'static'); }) .on('sticky_kit:unbottom', function(e) { $(this).parent().css('position', 'relative'); }); $('body').scrollspy({ target: '#sidebar', offset: 60 }); $('[data-toggle="tooltip"]').tooltip(); var cur_path = paths(location.pathname); var links = $("#navbar ul li a"); var max_length = -1; var pos = -1; for (var i = 0; i < links.length; i++) { if (links[i].getAttribute("href") === "#") continue; // Ignore external links if (links[i].host !== location.host) continue; var nav_path = paths(links[i].pathname); var length = prefix_length(nav_path, cur_path); if (length > max_length) { max_length = length; pos = i; } } // Add class to parent
  • , and enclosing
  • if in dropdown if (pos >= 0) { var menu_anchor = $(links[pos]); menu_anchor.parent().addClass("active"); menu_anchor.closest("li.dropdown").addClass("active"); } }); function paths(pathname) { var pieces = pathname.split("/"); pieces.shift(); // always starts with / var end = pieces[pieces.length - 1]; if (end === "index.html" || end === "") pieces.pop(); return(pieces); } // Returns -1 if not found function prefix_length(needle, haystack) { if (needle.length > haystack.length) return(-1); // Special case for length-0 haystack, since for loop won't run if (haystack.length === 0) { return(needle.length === 0 ? 0 : -1); } for (var i = 0; i < haystack.length; i++) { if (needle[i] != haystack[i]) return(i); } return(haystack.length); } /* Clipboard --------------------------*/ function changeTooltipMessage(element, msg) { var tooltipOriginalTitle=element.getAttribute('data-original-title'); element.setAttribute('data-original-title', msg); $(element).tooltip('show'); element.setAttribute('data-original-title', tooltipOriginalTitle); } if(ClipboardJS.isSupported()) { $(document).ready(function() { var copyButton = ""; $(".examples, div.sourceCode").addClass("hasCopyButton"); // Insert copy buttons: $(copyButton).prependTo(".hasCopyButton"); // Initialize tooltips: $('.btn-copy-ex').tooltip({container: 'body'}); // Initialize clipboard: var clipboardBtnCopies = new ClipboardJS('[data-clipboard-copy]', { text: function(trigger) { return trigger.parentNode.textContent; } }); clipboardBtnCopies.on('success', function(e) { changeTooltipMessage(e.trigger, 'Copied!'); e.clearSelection(); }); clipboardBtnCopies.on('error', function() { changeTooltipMessage(e.trigger,'Press Ctrl+C or Command+C to copy'); }); }); } })(window.jQuery || window.$) ================================================ FILE: docs/pkgdown.yml ================================================ pandoc: 1.19.2.1 pkgdown: 1.3.0 pkgdown_sha: ~ articles: introducing-urbnmapr: introducing-urbnmapr.html ================================================ FILE: docs/reference/ccdf_labels.html ================================================ Child Care and Development Fund labels data — ccdf_labels • urbnmapr

    Child Care and Development Fund labels data

    ccdf_labels

    Format

    Data frame with columns

    long, lat

    Longitude and latitude

    state_name, state_abbv

    State name and state abbreviation

    Site built with pkgdown 1.3.0.

    ================================================ FILE: docs/reference/counties.html ================================================ County shapefile data — counties • urbnmapr

    County shapefile data, cleaned and parsed into a tibble for easy mapping. Includes various state identifiers for easy merging.

    counties

    Format

    Data frame with columns

    long, lat

    Longitude and latitude

    county_name, county_fips, fips_class

    County name, five-digit FIPS and FIPS class code

    state_name, state_abbv, state_fips

    State name, postal abbreviation, and two-digit FIPS code

    Source

    United States Census Bureau, https://www.census.gov/geo/maps-data/data/tiger-cart-boundary.html

    Site built with pkgdown 1.3.0.

    ================================================ FILE: docs/reference/counties_labels.html ================================================ County labels data — counties_labels • urbnmapr

    Includes various state identifiers for easy merging.

    counties_labels

    Format

    Data frame with columns

    long, lat

    Longitude and latitude

    county_name, county_fips, fips_class

    County name, five-digit FIPS and FIPS class code

    state_name, state_abbv, state_fips

    State name, postal abbreviation, and two-digit FIPS code

    Site built with pkgdown 1.3.0.

    ================================================ FILE: docs/reference/countydata.html ================================================ County data for mapping — countydata • urbnmapr

    County-level data to use for example maps. Includes county FIPS code to match with county shapefile data.

    countydata

    Format

    Data frame with columns

    year

    Year of data

    county_fips

    Five-digit FIPS code

    hhhpop

    Household population

    horate

    Homeownership rate

    medhhincome

    Median household income

    Source

    Urban Institute Sloan ADRF Database, https://adrf.urban.org

    Site built with pkgdown 1.3.0.

    ================================================ FILE: docs/reference/get_urbn_labels.html ================================================ Import different map labels. — get_urbn_labels • urbnmapr

    get_urbn_labels() loads labels and coordinates for maps from the get_urbn_map() functions. Note: there are currently only sf options for states and territories_states, as these are the only options that have custom labels. To label counties and territories_counties, use geom_sf_text() or geom_sf_label().

    get_urbn_labels(map = "states", sf = FALSE)

    Arguments

    map

    Selection of custom labels. Current options are "states", "counties", "ccdf", "territories", and "territories_counties".

    sf

    Option indicates whether data is loaded as a tibble() or an sf object

    Site built with pkgdown 1.3.0.

    ================================================ FILE: docs/reference/get_urbn_map.html ================================================ Import different maps — get_urbn_map • urbnmapr

    get_urbn_map() loads maps that are different than states and counties

    get_urbn_map(map = "states", sf = FALSE)

    Arguments

    map

    Selection of custom map. Current options are "states", "counties", "ccdf", "territories_states", and "territories_counties".

    sf

    Option indicates whether data is loaded as a tibble() or an sf object

    Site built with pkgdown 1.3.0.

    ================================================ FILE: docs/reference/index.html ================================================ Function reference • urbnmapr

    All functions

    ccdf_labels

    Child Care and Development Fund labels data

    counties

    County shapefile data

    counties_labels

    County labels data

    countydata

    County data for mapping

    get_urbn_labels()

    Import different map labels.

    get_urbn_map()

    Import different maps

    statedata

    State data for mapping

    states

    State shapefile data

    states_labels

    States labels data

    territories_counties

    County shapefile data with U.S. territories

    territories_labels

    Territories labels data

    Site built with pkgdown 1.3.0.

    ================================================ FILE: docs/reference/statedata.html ================================================ State data for mapping — statedata • urbnmapr

    State-level data to use for example maps. Includes state FIPS code to match with state shapefile data.

    statedata

    Format

    Data frame with columns

    year

    Year of data

    state_fips, state_name

    Two-digit FIPS code and state name

    hhhpop

    Household population

    horate

    Homeownership rate

    medhhincome

    Median household income

    Source

    Urban Institute Sloan ADRF Database, https://adrf.urban.org

    Site built with pkgdown 1.3.0.

    ================================================ FILE: docs/reference/states.html ================================================ State shapefile data — states • urbnmapr

    State shapefile data, cleaned and parsed into a tibble for easy mapping. Includes various state identifiers for easy merging.

    states

    Format

    Data frame with columns

    long, lat

    Longitude and latitude

    state_name, state_abbv, state_fips

    State name, postal abbreviation, and two-digit FIPS code

    Source

    United States Census Bureau, https://www.census.gov/geo/maps-data/data/tiger-cart-boundary.html

    Site built with pkgdown 1.3.0.

    ================================================ FILE: docs/reference/states_labels.html ================================================ States labels data — states_labels • urbnmapr

    States labels data

    states_labels

    Format

    Data frame with columns

    long, lat

    Longitude and latitude

    state_name, state_abbv

    State name and state abbreviation

    Site built with pkgdown 1.3.0.

    ================================================ FILE: docs/reference/territories_counties.html ================================================ County shapefile data with U.S. territories — territories_counties • urbnmapr

    County shapefile data with territories, cleaned and parsed into a tibble for easy mapping. Includes various state identifiers for easy merging.

    territories_counties

    Format

    Data frame with columns

    long, lat

    Longitude and latitude

    county_name, county_fips, fips_class

    County name, five-digit FIPS and FIPS class code

    state_name, state_abbv, state_fips

    State name, postal abbreviation, and two-digit FIPS code

    Source

    United States Census Bureau, https://www.census.gov/geo/maps-data/data/tiger-cart-boundary.html

    Site built with pkgdown 1.3.0.

    ================================================ FILE: docs/reference/territories_labels.html ================================================ Territories labels data — territories_labels • urbnmapr

    Territories labels data

    territories_labels

    Format

    Data frame with columns

    long, lat

    Longitude and latitude

    state_name, state_abbv

    State name and state abbreviation

    ================================================ FILE: hexsticker.R ================================================ library(tidyverse) library(urbnmapr) library(urbnthemes) library(hexSticker) set_urbn_defaults("map") urbnmapr1 <- states %>% ggplot(mapping = aes(long, lat, group = group)) + geom_polygon(color = "#1696d2", fill = "#1696d2", size = 0.25) + coord_map(projection = "albers", lat0 = 39, lat1 = 45) + theme(panel.background = element_rect(fill = "#000000"), plot.margin = margin(0, 0, 0, 0)) sticker(urbnmapr1, package="urbnmapr", filename="man/figures/hexsticker.png", p_size=8, s_x = 1, # subplot position s_y = 0.75, # subplot position s_width = 1.3, # subplot width s_height = 1, # subplot height p_color = "#ffffff", p_family = "Lato", h_fill = "#000000", h_size = 0 # no border ) ================================================ FILE: man/ccdf_labels.Rd ================================================ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/ccdf_labels.R \docType{data} \name{ccdf_labels} \alias{ccdf_labels} \title{Child Care and Development Fund labels data} \format{Data frame with columns \describe{ \item{long, lat}{Longitude and latitude} \item{state_name, state_abbv}{State name and state abbreviation} }} \usage{ ccdf_labels } \description{ Child Care and Development Fund labels data } \keyword{datasets} ================================================ FILE: man/counties.Rd ================================================ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/counties.R \docType{data} \name{counties} \alias{counties} \title{County shapefile data} \format{Data frame with columns \describe{ \item{long, lat}{Longitude and latitude} \item{county_name, county_fips, fips_class}{County name, five-digit FIPS and FIPS class code} \item{state_name, state_abbv, state_fips}{State name, postal abbreviation, and two-digit FIPS code} }} \source{ United States Census Bureau, \url{https://www.census.gov/geo/maps-data/data/tiger-cart-boundary.html} } \usage{ counties } \description{ County shapefile data, cleaned and parsed into a tibble for easy mapping. Includes various state identifiers for easy merging. } \keyword{datasets} ================================================ FILE: man/counties_labels.Rd ================================================ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/counties_labels.R \docType{data} \name{counties_labels} \alias{counties_labels} \title{County labels data} \format{Data frame with columns \describe{ \item{long, lat}{Longitude and latitude} \item{county_name, county_fips, fips_class}{County name, five-digit FIPS and FIPS class code} \item{state_name, state_abbv, state_fips}{State name, postal abbreviation, and two-digit FIPS code} }} \usage{ counties_labels } \description{ Includes various state identifiers for easy merging. } \keyword{datasets} ================================================ FILE: man/countydata.Rd ================================================ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/countydata.R \docType{data} \name{countydata} \alias{countydata} \title{County data for mapping} \format{Data frame with columns \describe{ \item{year}{Year of data} \item{county_fips}{Five-digit FIPS code} \item{hhhpop}{Household population} \item{horate}{Homeownership rate} \item{medhhincome}{Median household income} }} \source{ Urban Institute Sloan ADRF Database, \url{https://adrf.urban.org} } \usage{ countydata } \description{ County-level data to use for example maps. Includes county FIPS code to match with county shapefile data. } \keyword{datasets} ================================================ FILE: man/get_urbn_labels.Rd ================================================ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/get_urbn_labels.R \name{get_urbn_labels} \alias{get_urbn_labels} \title{Import different map labels.} \usage{ get_urbn_labels(map = "states", sf = FALSE) } \arguments{ \item{map}{Selection of custom labels. Current options are \code{"states"}, \code{"counties"}, \code{"ccdf"}, \code{"territories"}, and \code{"territories_counties"}.} \item{sf}{Option indicates whether data is loaded as a \code{tibble()} or an \code{sf} object} } \description{ \code{get_urbn_labels()} loads labels and coordinates for maps from the \code{get_urbn_map()} functions. Note: there are currently only \code{sf} options for \code{states} and \code{territories_states}, as these are the only options that have custom labels. To label \code{counties} and \code{territories_counties}, use \code{geom_sf_text()} or \code{geom_sf_label()}. } ================================================ FILE: man/get_urbn_map.Rd ================================================ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/get_urbn_map.R \name{get_urbn_map} \alias{get_urbn_map} \title{Import different maps} \usage{ get_urbn_map(map = "states", sf = FALSE) } \arguments{ \item{map}{Selection of custom map. Current options are \code{"states"}, \code{"counties"}, \code{"ccdf"}, \code{"territories_states"}, and \code{"territories_counties"}.} \item{sf}{Option indicates whether data is loaded as a \code{tibble()} or an \code{sf} object} } \description{ \code{get_urbn_map()} loads maps that are different than \code{states} and \code{counties} } ================================================ FILE: man/statedata.Rd ================================================ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/statedata.R \docType{data} \name{statedata} \alias{statedata} \title{State data for mapping} \format{Data frame with columns \describe{ \item{year}{Year of data} \item{state_fips, state_name}{Two-digit FIPS code and state name} \item{hhhpop}{Household population} \item{horate}{Homeownership rate} \item{medhhincome}{Median household income} }} \source{ Urban Institute Sloan ADRF Database, \url{https://adrf.urban.org} } \usage{ statedata } \description{ State-level data to use for example maps. Includes state FIPS code to match with state shapefile data. } \keyword{datasets} ================================================ FILE: man/states.Rd ================================================ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/states.R \docType{data} \name{states} \alias{states} \title{State shapefile data} \format{Data frame with columns \describe{ \item{long, lat}{Longitude and latitude} \item{state_name, state_abbv, state_fips}{State name, postal abbreviation, and two-digit FIPS code} }} \source{ United States Census Bureau, \url{https://www.census.gov/geo/maps-data/data/tiger-cart-boundary.html} } \usage{ states } \description{ State shapefile data, cleaned and parsed into a tibble for easy mapping. Includes various state identifiers for easy merging. } \keyword{datasets} ================================================ FILE: man/states_labels.Rd ================================================ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/states_labels.R \docType{data} \name{states_labels} \alias{states_labels} \title{States labels data} \format{Data frame with columns \describe{ \item{long, lat}{Longitude and latitude} \item{state_name, state_abbv}{State name and state abbreviation} }} \usage{ states_labels } \description{ States labels data } \keyword{datasets} ================================================ FILE: man/territories_counties.Rd ================================================ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/territories_counties.R \docType{data} \name{territories_counties} \alias{territories_counties} \title{County shapefile data with U.S. territories} \format{Data frame with columns \describe{ \item{long, lat}{Longitude and latitude} \item{county_name, county_fips, fips_class}{County name, five-digit FIPS and FIPS class code} \item{state_name, state_abbv, state_fips}{State name, postal abbreviation, and two-digit FIPS code} }} \source{ United States Census Bureau, \url{https://www.census.gov/geo/maps-data/data/tiger-cart-boundary.html} } \usage{ territories_counties } \description{ County shapefile data with territories, cleaned and parsed into a tibble for easy mapping. Includes various state identifiers for easy merging. } \keyword{datasets} ================================================ FILE: man/territories_labels.Rd ================================================ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/territories_labels.R \docType{data} \name{territories_labels} \alias{territories_labels} \title{Territories labels data} \format{Data frame with columns \describe{ \item{long, lat}{Longitude and latitude} \item{state_name, state_abbv}{State name and state abbreviation} }} \usage{ territories_labels } \description{ Territories labels data } \keyword{datasets} ================================================ FILE: urbnmapr.Rproj ================================================ Version: 1.0 RestoreWorkspace: Default SaveWorkspace: Default AlwaysSaveHistory: Default EnableCodeIndexing: Yes UseSpacesForTab: Yes NumSpacesForTab: 2 Encoding: UTF-8 RnwWeave: Sweave LaTeX: pdfLaTeX AutoAppendNewline: Yes StripTrailingWhitespace: Yes BuildType: Package PackageUseDevtools: Yes PackageInstallArgs: --no-multiarch --with-keep.source ================================================ FILE: vignettes/introducing-urbnmapr.Rmd ================================================ --- title: "Introducing urbnmapr" author: "Vignette Author" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Vignette Title} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set(echo = TRUE) knitr::opts_chunk$set(warning = FALSE) knitr::opts_chunk$set(message = FALSE) options(scipen = 999) ``` The `urbnmapr` package provides state, county, and other shapefiles in `tibble` format that is compatible to map with `ggplot2`. Shapefiles include Alaska and Hawaii, transformed to be displayed as insets within the continental United States. This package is heavily inspired by and derived in part from the [fiftystater package](https://cran.r-project.org/package=fiftystater) by William Murphy. In contrast, `urbnmapr`: - Uses shapefiles from the US Census Bureau - Converts the shapefile data to a `tibble` data frame - Adds various identifiers for merging - Includes a county-level shapefile ## Getting data There are two methods for accessing map data in `urbnmapr`. First, `urbnmapr` contains two `tibble` data frames, `states` and `counties`, for easily accessing simple state and county map data. The `states` and `counties` tibbles can be used with `geom_polygon()` and `coord_map()` to create base maps of the continental United States, with Alaska and Hawaii displayed as insets: ```{r blank-states} library(tidyverse) library(urbnmapr) states %>% ggplot(aes(long, lat, group = group)) + geom_polygon(fill = "grey", color = "#ffffff", size = 0.25) + coord_map(projection = "albers", lat0 = 39, lat1 = 45) ``` ```{r blank-counties} counties %>% ggplot(aes(long, lat, group = group)) + geom_polygon(fill = "grey", color = "#ffffff", size = 0.05) + coord_map(projection = "albers", lat0 = 39, lat1 = 45) ``` Second, the function `get_urbn_map()` accesses additional maps including "ccdf", which includes elided territories roughly positioned in the direction of their true location, and "territories_counties", which includes territories below the continuous 48 states. ```{r blank-territories-counties} ccdf <- get_urbn_map(map = "territories_counties") ccdf %>% ggplot(aes(long, lat, group = group)) + geom_polygon(fill = "grey", color = "#ffffff", size = 0.25) + scale_x_continuous(limits = c(-141, -55)) + scale_y_continuous(limits = c(24, 50)) + coord_map(projection = "albers", lat0 = 39, lat1 = 45) ``` ## Merging data All tibbles include various identifiers to simplify merging data. The states `states` tibble contains `state_fips`, `state_abbv`, and `state_name`. The `counties` tibble contains `county_fips`, `state_abbv`, `state_fips`, `county_name`, and `state_name`. Both tibbles can be piped into `ggplot2` to create a choropleth map. ```{r us-choropleth} statedata %>% left_join(states, by = "state_name") %>% ggplot(mapping = aes(long, lat, group = group, fill = horate)) + geom_polygon(color = "#ffffff", size = 0.25) + coord_map(projection = "albers", lat0 = 39, lat1 = 45) + labs(fill = "Homeownership rate") ``` ```{r county} household_data <- left_join(countydata, counties, by = "county_fips") household_data %>% ggplot(aes(long, lat, group = group, fill = medhhincome)) + geom_polygon(color = "#ffffff", size = 0.05) + coord_map(projection = "albers", lat0 = 39, lat1 = 45) ``` ## Labels The function `get_urbn_labels()` accesses additional labels including "ccdf", which includes elided territories roughly positioned in the direction of their true location, and "territories_counties", which includes territories below the continuous 48 states. ```{r blank-ccdf-labels} library(tidyverse) library(urbnmapr) ccdf <- get_urbn_map(map = "ccdf") ccdf_labels <- get_urbn_labels(map = "ccdf") ccdf %>% ggplot() + geom_polygon(aes(long, lat, group = group), fill = "grey", color = "#ffffff", size = 0.25) + geom_text(data = ccdf_labels, aes(long, lat, label = state_abbv), size = 3) + scale_x_continuous(limits = c(-141, -55)) + scale_y_continuous(limits = c(24, 50)) + coord_map(projection = "albers", lat0 = 39, lat1 = 45) ``` ## Styles `library(urbnmapr)` works well with the [library(urbnthemes)](https://github.com/UI-Research/urbnthemes) ```{r theme-state} library(urbnthemes) set_urbn_defaults(style = "map") statedata %>% left_join(states, by = "state_name") %>% ggplot(mapping = aes(long, lat, group = group, fill = horate)) + geom_polygon(color = "#ffffff", size = 0.25) + coord_map(projection = "albers", lat0 = 39, lat1 = 45) + scale_fill_gradientn(labels = scales::percent) + theme(legend.position = "right", legend.direction = "vertical", legend.title = element_text(face = "bold", size = 11), legend.key.height = unit(.2, "in")) + labs(fill = "Homeownership rate") ``` ```{r theme-counties} household_data %>% filter(state_name %in% c("Virginia", "Maryland", "District of Columbia")) %>% ggplot(aes(long, lat, group = group, fill = medhhincome)) + geom_polygon(color = "#ffffff", size = 0.05) + coord_map(projection = "albers", lat0 = 39, lat1 = 45) + scale_fill_gradientn(labels = scales::dollar) + theme(legend.position = "right", legend.direction = "vertical", legend.title = element_text(face = "bold", size = 11), legend.key.height = unit(.25, "in")) + labs(fill = "Median household income") ```