Maps_assignment

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.5.0     ✔ 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)   
library(sf)             
Linking to GEOS 3.11.0, GDAL 3.5.3, PROJ 9.1.0; sf_use_s2() is TRUE
library(leaflet)     
library(usdata) 
library(plotly)

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
 install = TRUE
census_api_key("")
To install your API key for use in future sessions, run this function with `install = TRUE`.
states <- get_acs(geography = "state",               
                  variables = "B01003_001",        
                  geometry = TRUE, 
                  shift_geo = T) 
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.
Warning: • You have not set a Census API key. Users without a key are limited to 500
queries per day and may experience performance limitations.
ℹ For best results, get a Census API key at
http://api.census.gov/data/key_signup.html and then supply the key to the
`census_api_key()` function to use it throughout your tidycensus session.
This warning is displayed once per session.
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()
states |> 
  ggplot() +  
  geom_sf(aes(fill = estimate)) +

scale_fill_viridis_c(labels = label_comma()) +
coord_sf(datum = NA) +
  theme_minimal() +
labs(title = "State Populations")

state_income <- get_acs(geography = "state", 
                        variables = "B19013_001", 
                        shift_geo = T, 
                        geometry = TRUE)
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()
state_income |> 
  ggplot() + 
  geom_sf(aes(fill = estimate)) + 
  coord_sf(datum = NA) + 
  theme_minimal() + 
  scale_fill_viridis_c(labels = label_comma()) +
  labs(title = "Median state income")

states_leaflet <- get_acs(geography = "state",               
                  variables = "B01003_001",        
                  geometry = TRUE, 
                  shift_geo = F) 
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%
  |                                                                            
  |=                                                                     |   1%
  |                                                                            
  |=                                                                     |   2%
  |                                                                            
  |==                                                                    |   3%
  |                                                                            
  |==                                                                    |   4%
  |                                                                            
  |===                                                                   |   4%
  |                                                                            
  |===                                                                   |   5%
  |                                                                            
  |====                                                                  |   5%
  |                                                                            
  |====                                                                  |   6%
  |                                                                            
  |=====                                                                 |   7%
  |                                                                            
  |=====                                                                 |   8%
  |                                                                            
  |======                                                                |   8%
  |                                                                            
  |======                                                                |   9%
  |                                                                            
  |=======                                                               |   9%
  |                                                                            
  |=======                                                               |  10%
  |                                                                            
  |========                                                              |  11%
  |                                                                            
  |========                                                              |  12%
  |                                                                            
  |=========                                                             |  13%
  |                                                                            
  |=========                                                             |  14%
  |                                                                            
  |==========                                                            |  14%
  |                                                                            
  |==========                                                            |  15%
  |                                                                            
  |===========                                                           |  15%
  |                                                                            
  |===========                                                           |  16%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |============                                                          |  18%
  |                                                                            
  |=============                                                         |  19%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |==============                                                        |  21%
  |                                                                            
  |===============                                                       |  22%
  |                                                                            
  |================                                                      |  23%
  |                                                                            
  |=================                                                     |  24%
  |                                                                            
  |=================                                                     |  25%
  |                                                                            
  |==================                                                    |  25%
  |                                                                            
  |==================                                                    |  26%
  |                                                                            
  |===================                                                   |  27%
  |                                                                            
  |===================                                                   |  28%
  |                                                                            
  |====================                                                  |  28%
  |                                                                            
  |====================                                                  |  29%
  |                                                                            
  |=====================                                                 |  30%
  |                                                                            
  |======================                                                |  31%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |========================                                              |  34%
  |                                                                            
  |========================                                              |  35%
  |                                                                            
  |=========================                                             |  35%
  |                                                                            
  |=========================                                             |  36%
  |                                                                            
  |==========================                                            |  38%
  |                                                                            
  |===========================                                           |  39%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |=================================                                     |  48%
  |                                                                            
  |==================================                                    |  48%
  |                                                                            
  |==================================                                    |  49%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |====================================                                  |  51%
  |                                                                            
  |=====================================                                 |  53%
  |                                                                            
  |======================================                                |  54%
  |                                                                            
  |======================================                                |  55%
  |                                                                            
  |=======================================                               |  55%
  |                                                                            
  |========================================                              |  57%
  |                                                                            
  |==========================================                            |  60%
  |                                                                            
  |==============================================                        |  66%
  |                                                                            
  |===============================================                       |  68%
  |                                                                            
  |================================================                      |  68%
  |                                                                            
  |=================================================                     |  69%
  |                                                                            
  |======================================================                |  77%
  |                                                                            
  |========================================================              |  80%
  |                                                                            
  |============================================================          |  86%
  |                                                                            
  |===================================================================== |  98%
  |                                                                            
  |======================================================================| 100%
state_colors <- colorNumeric(palette = "viridis", domain = states_leaflet$estimate)

states_leaflet |>
leaflet() |> 
  addTiles() |>   
  addPolygons(weight = 1, fillColor = ~state_colors(estimate),
              label = ~paste0(NAME, "income = ", estimate), highlight = highlightOptions(weight = 2)) |>
  setView(-95, 40, zoom = 4) |>
  addLegend(pal = state_colors, values = ~estimate)
Warning: sf layer has inconsistent datum (+proj=longlat +datum=NAD83 +no_defs).
Need '+proj=longlat +datum=WGS84'

Income estimates by state, 2021

homicides <- read_csv("homicides.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.
homicide_states <- homicides |> 
  filter(YEAR == 2021) |> 
  mutate(NAME = abbr2state(STATE)) 
states |> 
  inner_join(homicide_states) |> 
  ggplot() + 
  geom_sf(aes(fill = RATE)) + 
  coord_sf(datum = NA) + theme_minimal() + 
  scale_fill_viridis_c(labels = label_comma()) +
  labs(title = "State homicide rates in 2021")
Joining with `by = join_by(NAME)`

  1. Choropleth map of state homicide rates using ggplot.
homicides |> 
  ggplot(aes(x = RATE)) +
  geom_histogram(binwidth = 2) +
  scale_x_continuous(labels = comma) +
  theme_minimal() +
  xlab("State homicides")

  1. Histogram of state homicide rates using ggplot.
state_colors <- colorNumeric(palette = "viridis", domain = states_leaflet$estimate)
states_leaflet |>
  leaflet() |>
  addTiles() |>
  addPolygons(weight = 1)
Warning: sf layer has inconsistent datum (+proj=longlat +datum=NAD83 +no_defs).
Need '+proj=longlat +datum=WGS84'
state_colors <- colorNumeric(palette = "viridis", domain = states_leaflet$estimate)

states_leaflet |>
  leaflet() |>
  addTiles() |>
  addPolygons(weight = 1,
              fillColor = ~state_colors(estimate),
              label = ~paste0(NAME, "state income = ", estimate),
              highlight = highlightOptions(weight = 2)) |>
      setView(-95, 40, zoom = 4) |>
addLegend(pal = state_colors, values = ~estimate)
Warning: sf layer has inconsistent datum (+proj=longlat +datum=NAD83 +no_defs).
Need '+proj=longlat +datum=WGS84'
homicide_colors <- colorNumeric(palette = "viridis", domain = homicide_states$RATE)

states_leaflet |>
    inner_join(homicide_states) |> 
  leaflet() |> 
  addTiles() |>   
  addPolygons(weight = 1, 
              fillColor = ~homicide_colors(RATE),
              label = ~paste0(NAME, "homicide rate = ", RATE),
              highlight = highlightOptions(weight = 2)) |>
  setView(-95, 40, zoom = 4) |>
  addLegend(pal = homicide_colors, values = ~RATE)
Joining with `by = join_by(NAME)`
Warning: sf layer has inconsistent datum (+proj=longlat +datum=NAD83 +no_defs).
Need '+proj=longlat +datum=WGS84'
  1. Choropleth of homicide rates by state in 2021 using leaflet.
homicide_states |> 
  plot_ly(x = ~RATE) |> 
  add_histogram()
  1. Histogram of state homicide rates in 2021 using plotly.
fatals <- read.csv("fatal-police-shootings-data.csv")
fatals |>
    filter(state == "MT") -> MT_fatals
fatals |>
    count(state)
   state    n
1     AK   60
2     AL  181
3     AR  135
4     AZ  427
5     CA 1325
6     CO  342
7     CT   30
8     DC   29
9     DE   20
10    FL  610
11    GA  358
12    HI   45
13    IA   58
14    ID   83
15    IL  198
16    IN  186
17    KS   92
18    KY  167
19    LA  185
20    MA   59
21    MD  122
22    ME   42
23    MI  173
24    MN   99
25    MO  243
26    MS  128
27    MT   60
28    NC  277
29    ND   20
30    NE   47
31    NH   29
32    NJ  103
33    NM  200
34    NV  159
35    NY  180
36    OH  267
37    OK  251
38    OR  152
39    PA  207
40    RI    8
41    SC  154
42    SD   31
43    TN  268
44    TX  906
45    UT  120
46    VA  173
47    VT   14
48    WA  257
49    WI  152
50    WV   92
51    WY   31

This table shows the number of shootings in each state.

fatals |>
    count(threat_type)
   threat_type    n
1                68
2     accident   53
3       attack 1373
4         flee  178
5         move  488
6        point 1768
7        shoot 2689
8       threat 2554
9 undetermined  384

This table shows the number of threats by their type.

MT_fatals |>
  leaflet() |>
  addTiles() |>
  addCircleMarkers(stroke = F, fillOpacity = .6, radius = 5, label = ~threat_type)
Assuming "longitude" and "latitude" are longitude and latitude, respectively
Warning in validateCoords(lng, lat, funcName): Data contains 11 rows with
either missing or invalid lat/lon values and will be ignored

The above is a dot map from leaflet showing the reported shooting incidents around Montana and their type of threat.