maps

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.5
✔ forcats   1.0.0     ✔ stringr   1.5.1
✔ ggplot2   3.4.4     ✔ tibble    3.2.1
✔ lubridate 1.9.3     ✔ tidyr     1.3.0
✔ purrr     1.0.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(lubridate)
library(scales)

Attaching package: 'scales'

The following object is masked from 'package:purrr':

    discard

The following object is masked from 'package:readr':

    col_factor
library(tidycensus)      # gets census data that we can use to create maps
Warning: package 'tidycensus' was built under R version 4.3.3
library(sf)              # helper package for mapping
Warning: package 'sf' was built under R version 4.3.3
Linking to GEOS 3.11.2, GDAL 3.8.2, PROJ 9.3.1; sf_use_s2() is TRUE
library(leaflet)         # interactive mapping package
Warning: package 'leaflet' was built under R version 4.3.3
library(usdata)          # this package has a conversion utility for state abbreviations to full names
Warning: package 'usdata' was built under R version 4.3.3
library(plotly)
Warning: package 'plotly' was built under R version 4.3.3

Attaching package: 'plotly'

The following object is masked from 'package:ggplot2':

    last_plot

The following object is masked from 'package:stats':

    filter

The following object is masked from 'package:graphics':

    layout
states <- get_acs(geography = "state",               # gets state by state data
                  variables = "B01003_001",          # this is state population
                  geometry = TRUE,                   # gets geometry (the maps)
                  shift_geo = T)                     # shifts Hawaii and Alaska
Getting data from the 2018-2022 5-year ACS
Warning: The `shift_geo` argument is deprecated and will be removed in a future
release. We recommend using `tigris::shift_geometry()` instead.
Using feature geometry obtained from the albersusa package
Please note: Alaska and Hawaii are being shifted and are not to scale.
old-style crs object detected; please recreate object with a recent sf::st_crs()
suicide <- read_csv("Suicide_rates_by_state.csv")
Rows: 450 Columns: 5
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (2): STATE, URL
dbl (2): YEAR, RATE
num (1): DEATHS

ℹ 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.
suicide_states <- suicide |> 
  filter(YEAR == 2020) |> 
  mutate(NAME = abbr2state(STATE)) 
states |> 
  inner_join(suicide_states) |> 
  ggplot() + 
  geom_sf(aes(fill = DEATHS)) + 
  coord_sf(datum = NA) +
  theme_minimal() + 
  scale_fill_viridis_c(labels = label_comma()) +
  labs(title = "Suicide rates in 2020")
Joining with `by = join_by(NAME)`

suicide_states |> 
  ggplot(aes(x = DEATHS)) +
  geom_histogram(binwidth = 50) +
  scale_x_continuous(labels = comma) +
  theme_minimal() +
  xlab("Suicide rates in 2020")

suicide_leaflet <- get_acs(geography = "state",       # gets state by state data
                  variables = "B19013_001",          # this is state income
                  geometry = TRUE,                   # gets geometry (the maps)
                  shift_geo = F)                    # we're not shifting Hawaii and Alaska!
Getting data from the 2018-2022 5-year ACS
Downloading feature geometry from the Census website.  To cache shapefiles for use in future sessions, set `options(tigris_use_cache = TRUE)`.

  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |=                                                                     |   1%
  |                                                                            
  |=                                                                     |   2%
  |                                                                            
  |==                                                                    |   2%
  |                                                                            
  |==                                                                    |   3%
  |                                                                            
  |===                                                                   |   4%
  |                                                                            
  |===                                                                   |   5%
  |                                                                            
  |====                                                                  |   5%
  |                                                                            
  |====                                                                  |   6%
  |                                                                            
  |=====                                                                 |   6%
  |                                                                            
  |=====                                                                 |   7%
  |                                                                            
  |=====                                                                 |   8%
  |                                                                            
  |======                                                                |   8%
  |                                                                            
  |======                                                                |   9%
  |                                                                            
  |=======                                                               |  10%
  |                                                                            
  |========                                                              |  11%
  |                                                                            
  |========                                                              |  12%
  |                                                                            
  |=========                                                             |  12%
  |                                                                            
  |=========                                                             |  13%
  |                                                                            
  |==========                                                            |  14%
  |                                                                            
  |==========                                                            |  15%
  |                                                                            
  |===========                                                           |  15%
  |                                                                            
  |===========                                                           |  16%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |============                                                          |  18%
  |                                                                            
  |=============                                                         |  18%
  |                                                                            
  |=============                                                         |  19%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |==============                                                        |  21%
  |                                                                            
  |===============                                                       |  21%
  |                                                                            
  |===============                                                       |  22%
  |                                                                            
  |================                                                      |  23%
  |                                                                            
  |================                                                      |  24%
  |                                                                            
  |=================                                                     |  24%
  |                                                                            
  |=================                                                     |  25%
  |                                                                            
  |==================                                                    |  25%
  |                                                                            
  |==================                                                    |  26%
  |                                                                            
  |===================                                                   |  27%
  |                                                                            
  |===================                                                   |  28%
  |                                                                            
  |====================                                                  |  28%
  |                                                                            
  |====================                                                  |  29%
  |                                                                            
  |=====================                                                 |  31%
  |                                                                            
  |======================                                                |  31%
  |                                                                            
  |======================                                                |  32%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |========================                                              |  34%
  |                                                                            
  |========================                                              |  35%
  |                                                                            
  |=========================                                             |  36%
  |                                                                            
  |==========================                                            |  37%
  |                                                                            
  |===========================                                           |  39%
  |                                                                            
  |============================                                          |  40%
  |                                                                            
  |============================                                          |  41%
  |                                                                            
  |=============================                                         |  41%
  |                                                                            
  |==============================                                        |  42%
  |                                                                            
  |==============================                                        |  43%
  |                                                                            
  |===============================                                       |  44%
  |                                                                            
  |===============================                                       |  45%
  |                                                                            
  |================================                                      |  45%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |==================================                                    |  48%
  |                                                                            
  |==================================                                    |  49%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |====================================                                  |  52%
  |                                                                            
  |======================================                                |  54%
  |                                                                            
  |========================================                              |  57%
  |                                                                            
  |==========================================                            |  60%
  |                                                                            
  |============================================                          |  63%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |================================================                      |  69%
  |                                                                            
  |==================================================                    |  72%
  |                                                                            
  |========================================================              |  80%
  |                                                                            
  |===========================================================           |  84%
  |                                                                            
  |=============================================================         |  87%
  |                                                                            
  |==============================================================        |  89%
  |                                                                            
  |=================================================================     |  93%
  |                                                                            
  |====================================================================  |  97%
  |                                                                            
  |======================================================================|  99%
  |                                                                            
  |======================================================================| 100%
suicide_colors <- colorNumeric(palette = "viridis", domain = suicide_states$DEATHS)
suicide_leaflet |>
  inner_join(suicide_states) |> 
  leaflet() |> 
  addTiles() |> 
  addPolygons(weight = 1, fillColor = ~suicide_colors(DEATHS),
              label = ~paste0(NAME, ", Suicides = ", DEATHS),
              highlight = highlightOptions(weight = 2)) |> 
  setView(-95, 40, zoom = 4) |> 
  addLegend(pal = suicide_colors, values = ~DEATHS)                   # we're not shifting Hawaii and Alaska!
Joining with `by = join_by(NAME)`
Warning: sf layer has inconsistent datum (+proj=longlat +datum=NAD83 +no_defs).
Need '+proj=longlat +datum=WGS84'

Number of Suicides in each state in the year 2020

suicide_states |> 
  plot_ly(x = ~DEATHS) |> 
  add_histogram()
shootings <- read_csv("fatal-police-shootings-data.csv")
Rows: 8002 Columns: 17
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr  (9): name, manner_of_death, armed, gender, race, city, state, threat_le...
dbl  (4): id, age, longitude, latitude
lgl  (3): signs_of_mental_illness, body_camera, is_geocoding_exact
date (1): date

ℹ 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.
shootings |> 
filter(state == "NV") -> NV_shootings
NV_shootings |>
  leaflet() |>
  addTiles() |>
  addCircleMarkers(stroke = F, fillOpacity = .6, radius = 5)
Assuming "longitude" and "latitude" are longitude and latitude, respectively
Warning in validateCoords(lng, lat, funcName): Data contains 7 rows with either
missing or invalid lat/lon values and will be ignored

Fatal Shootings in Nevada

NV_shootings |> 
 count(armed, race, signs_of_mental_illness) |> 
  arrange(-n)
# A tibble: 45 × 4
   armed        race  signs_of_mental_illness     n
   <chr>        <chr> <lgl>                   <int>
 1 gun          W     FALSE                      22
 2 gun          <NA>  FALSE                      16
 3 gun          H     FALSE                      15
 4 gun          W     TRUE                       10
 5 gun          B     FALSE                       8
 6 gun          H     TRUE                        5
 7 knife        W     FALSE                       5
 8 knife        W     TRUE                        4
 9 undetermined <NA>  FALSE                       3
10 <NA>         H     FALSE                       3
# ℹ 35 more rows