maps

library(tidyverse)
Warning: package 'tidyverse' was built under R version 4.3.2
Warning: package 'lubridate' was built under R version 4.3.2
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.2     ✔ readr     2.1.4
✔ forcats   1.0.0     ✔ stringr   1.5.0
✔ ggplot2   3.4.2     ✔ tibble    3.2.1
✔ lubridate 1.9.3     ✔ tidyr     1.3.0
✔ purrr     1.0.1     
── 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)      
Warning: package 'tidycensus' was built under R version 4.3.3
library(sf)              
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)         
Warning: package 'leaflet' was built under R version 4.3.3
library(usdata) 
Warning: package 'usdata' was built under R version 4.3.3
library(readxl)
library(plotly)
Warning: package 'plotly' was built under R version 4.3.2

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
census_api_key("")
To install your API key for use in future sessions, run this function with `install = TRUE`.
teen <- read_csv("data-table.csv")
Rows: 450 Columns: 4
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (2): STATE, URL
dbl (2): YEAR, RATE

ℹ 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.
teen |> 
  filter(YEAR == 2021) |> 
  mutate(NAME = abbr2state(STATE)) -> teen_states
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.
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()

This is all stats stuff and setting up the data.

states |> 
  inner_join(teen_states) |> 
  ggplot() + 
  geom_sf(aes(fill = RATE)) + 
  coord_sf(datum = NA) +
  scale_fill_viridis_c(labels = label_comma()) +
  theme_minimal() +
  labs(title = "Teen Birth Rate by State")
Joining with `by = join_by(NAME)`

This is a chloropleth map of the rate of teen pregnancy/birth by state. The more yellow the color, the higher the rate.

teen_states |> 
  ggplot(aes(x = RATE)) +
  geom_histogram()  +
  scale_x_continuous(labels = comma) +
  theme_minimal() +
  xlab("Teen Birth Rate")
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

This is a histogram of the teen birth rate nationally. Note to Dr. M- any time I adjusted the binwidth it looked pretty ugly; the automatic width looked the best.

states_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%
  |                                                                            
  |===========                                                           |  16%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |==============                                                        |  21%
  |                                                                            
  |===============                                                       |  21%
  |                                                                            
  |===============                                                       |  22%
  |                                                                            
  |================                                                      |  22%
  |                                                                            
  |================                                                      |  23%
  |                                                                            
  |==================                                                    |  26%
  |                                                                            
  |===================                                                   |  27%
  |                                                                            
  |===================                                                   |  28%
  |                                                                            
  |=====================                                                 |  29%
  |                                                                            
  |==============================                                        |  43%
  |                                                                            
  |===============================                                       |  44%
  |                                                                            
  |===============================                                       |  45%
  |                                                                            
  |================================                                      |  45%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |=================================                                     |  47%
  |                                                                            
  |==================================                                    |  48%
  |                                                                            
  |==================================                                    |  49%
  |                                                                            
  |===================================                                   |  49%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |========================================                              |  57%
  |                                                                            
  |=========================================                             |  58%
  |                                                                            
  |=========================================                             |  59%
  |                                                                            
  |==========================================                            |  60%
  |                                                                            
  |===========================================                           |  61%
  |                                                                            
  |===========================================                           |  62%
  |                                                                            
  |============================================                          |  63%
  |                                                                            
  |=============================================                         |  64%
  |                                                                            
  |=============================================                         |  65%
  |                                                                            
  |==============================================                        |  66%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |===============================================                       |  68%
  |                                                                            
  |================================================                      |  68%
  |                                                                            
  |================================================                      |  69%
  |                                                                            
  |=================================================                     |  69%
  |                                                                            
  |=================================================                     |  70%
  |                                                                            
  |==================================================                    |  71%
  |                                                                            
  |==================================================                    |  72%
  |                                                                            
  |===================================================                   |  72%
  |                                                                            
  |===================================================                   |  73%
  |                                                                            
  |====================================================                  |  74%
  |                                                                            
  |=====================================================                 |  75%
  |                                                                            
  |======================================================                |  77%
  |                                                                            
  |======================================================                |  78%
  |                                                                            
  |=======================================================               |  79%
  |                                                                            
  |========================================================              |  79%
  |                                                                            
  |========================================================              |  80%
  |                                                                            
  |=========================================================             |  81%
  |                                                                            
  |=============================================================         |  87%
  |                                                                            
  |==============================================================        |  88%
  |                                                                            
  |==============================================================        |  89%
  |                                                                            
  |===============================================================       |  89%
  |                                                                            
  |===============================================================       |  90%
  |                                                                            
  |===============================================================       |  91%
  |                                                                            
  |================================================================      |  91%
  |                                                                            
  |================================================================      |  92%
  |                                                                            
  |=================================================================     |  92%
  |                                                                            
  |=================================================================     |  93%
  |                                                                            
  |==================================================================    |  94%
  |                                                                            
  |==================================================================    |  95%
  |                                                                            
  |===================================================================   |  95%
  |                                                                            
  |===================================================================   |  96%
  |                                                                            
  |===================================================================== |  99%
  |                                                                            
  |======================================================================|  99%
  |                                                                            
  |======================================================================| 100%

This is stats stuff.

teen_colors <- colorNumeric(palette = "viridis", domain = teen_states$RATE) 

states_leaflet |> 
  inner_join(teen_states) |> 
  leaflet()|> 
  addTiles() |> 
  addPolygons(weight = 1, 
              fillColor = ~teen_colors(RATE), 
              label = ~paste0(NAME, ", Teen birth rate = ", RATE), 
              highlight = highlightOptions(weight = 2)) |> 
  setView(-95, 40, zoom = 4) |> 
  addLegend(pal = teen_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'

This is an interactive choropleth map of the same variables. Hover over each state to see its birth rate.

teen_states |> 
  plot_ly(x = ~RATE) |> 
  add_histogram()

This is a histogram of the birth rates nationally.

crime_open_database_core_all_2022 <- readRDS("crime_open_database_core_all_2022.Rds")
crime_open_database_core_all_2022 |> 
  filter(city_name == "Mesa") |> 
  filter(month(date_single) == 10) |> 
  filter(day(date_single) == 24) -> oct_24


oct_24
# A tibble: 63 × 14
        uid city_name offense_code offense_type    offense_group offense_against
      <int> <chr>     <chr>        <chr>           <chr>         <chr>          
 1 16228952 Mesa      90D          driving under … driving unde… society        
 2 16228953 Mesa      90C          disorderly con… disorderly c… society        
 3 16228954 Mesa      90Z          all other offe… all other of… other          
 4 16228955 Mesa      13B          simple assault  assault offe… persons        
 5 16228956 Mesa      26C          impersonation   fraud offens… property       
 6 16228957 Mesa      90Z          all other offe… all other of… other          
 7 16228958 Mesa      13B          simple assault  assault offe… persons        
 8 16228959 Mesa      90Z          all other offe… all other of… other          
 9 16228960 Mesa      290          destruction/da… destruction/… property       
10 16228961 Mesa      90C          disorderly con… disorderly c… society        
# ℹ 53 more rows
# ℹ 8 more variables: date_single <chr>, longitude <dbl>, latitude <dbl>,
#   location_type <chr>, location_category <chr>, census_block <chr>,
#   date_start <chr>, date_end <chr>

This is setting up the data. I picked my birthday in a city I want to live in.

oct_24 |>
  leaflet() |>
  addTiles() |>
  addCircleMarkers(stroke = F, fillOpacity = .6, radius = 5)
Assuming "longitude" and "latitude" are longitude and latitude, respectively

This is a map of crime stops on that day in Mesa.

oct_24 |>
  count(offense_type, offense_against) |>
  arrange(-n)
# A tibble: 21 × 3
   offense_type                       offense_against     n
   <chr>                              <chr>           <int>
 1 all other offenses                 other              14
 2 drug equipment violations          society             5
 3 simple assault                     persons             5
 4 driving under the influence        society             4
 5 other burglary/breaking & entering property            4
 6 shoplifting                        property            4
 7 all other larceny                  property            3
 8 disorderly conduct                 society             3
 9 drug/narcotic violations           society             3
10 theft from building                property            3
# ℹ 11 more rows

This is a table of the offenses on 10/24/2022 by type and who the offense was against.