Reading Outside Data Packages

texas <- read_sf("Texas_County_Boundaries_Detailed", "County")
txcrash <- read_csv("txcrash.csv")
## Rows: 365 Columns: 14
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (1): county
## num (13): fatal_crashes, fatalities, sus_serious_crash, sus_serious_injury, ...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
txpop2020 <- read_csv("txpop2020.csv")
## Rows: 255 Columns: 5
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (3): rank, county, metro_area
## num (2): population, pop_density
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.

Manipulating Data

txdata <- txcrash %>%
  left_join(txpop2020, by = c("county" = "county")) %>%
  relocate(rank, .after = county) %>%
  relocate(population, .after = rank) %>%
  relocate(pop_density, .after = population) %>%
  mutate(pop_10000 = population / 10000) %>%
  mutate(crash_10000 = total_crashes / pop_10000) %>%
  left_join(texas, by = c("county" = "CNTY_NM")) %>%
  select(-metro_area) %>%
  filter_all(all_vars(!is.na(.)))

txdata_sf <- st_as_sf(txdata)

Starting the Map

map <- leaflet(txdata_sf) %>%
  addTiles()

Setting Crash Data Classes and Creating Color Palette

bins <- c(0, 100, 125, 150, 175, 200, 250, 300, 500, 1000, 10000)
pal <- colorBin("RdBu", domain = txdata$crash_10000, bins = bins)

Creating the labels for the Interactive Map

labels <- sprintf("<strong>%s</strong><br/>%g Crashes Per 10,000 People",
                  txdata_sf$county, txdata_sf$crash_10000) %>% 
  lapply(htmltools::HTML)

Creating the Title and Subtitle for the Map

title <- "Car Crashes in Texas"
subtitle <- "The Number of Car Crashes per 10,000 People in Each Texas County"
map <- map %>%
  addControl(html = paste0("<div class='map-title'><strong>", 
                           title, "</strong><br/>", subtitle, "</div>"),
             position = "topright")

Creating the Map

mymap <- map %>%
  addPolygons(
    data = txdata_sf, 
    fillColor = ~pal(txdata_sf$crash_10000), fillOpacity = 1, color = "white",
    weight = 0.5,
    highlight = highlightOptions(weight = 1, color = "black", bringToFront = TRUE), 
    label = labels,
    labelOptions = labelOptions(style = list("font-weight" = "normal", 
                                             padding = "3px 8px"), 
                                textsize = "15px",direction = "auto")) %>%
  addLegend("bottomright", pal = pal, values = ~crash_10000,
            title = "Crashes Per 10,000 People",
            opacity = 1)

Running the Map

mymap