library(readr)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(lubridate)
## 
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
library(plotly)
## Loading required package: ggplot2
## 
## 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
library(ggplot2)
library(ggmap)
## Warning: package 'ggmap' was built under R version 4.3.3
## ℹ Google's Terms of Service: <https://mapsplatform.google.com>
##   Stadia Maps' Terms of Service: <https://stadiamaps.com/terms-of-service/>
##   OpenStreetMap's Tile Usage Policy: <https://operations.osmfoundation.org/policies/tiles/>
## ℹ Please cite ggmap if you use it! Use `citation("ggmap")` for details.
## 
## Attaching package: 'ggmap'
## The following object is masked from 'package:plotly':
## 
##     wind
library(plotly)
library(rgdax)
## Warning: package 'rgdax' was built under R version 4.3.3
## Loading required package: digest
## Loading required package: jsonlite
## Loading required package: RCurl
## Warning: package 'RCurl' was built under R version 4.3.2
## Loading required package: httr
## 
## Attaching package: 'httr'
## The following object is masked from 'package:plotly':
## 
##     config
## Loading required package: plyr
## ------------------------------------------------------------------------------
## You have loaded plyr after dplyr - this is likely to cause problems.
## If you need functions from both plyr and dplyr, please load plyr first, then dplyr:
## library(plyr); library(dplyr)
## ------------------------------------------------------------------------------
## 
## Attaching package: 'plyr'
## The following objects are masked from 'package:plotly':
## 
##     arrange, mutate, rename, summarise
## The following objects are masked from 'package:dplyr':
## 
##     arrange, count, desc, failwith, id, mutate, rename, summarise,
##     summarize
myLocation <- "San Francisco"
mykey = "AIzaSyABAXSsDR-f9qby3LK2o6bh0BypFWlKrm4"
register_google(key = mykey)

myMap <- get_map(location = myLocation, zoom = 12)
## ℹ <https://maps.googleapis.com/maps/api/staticmap?center=San%20Francisco&zoom=12&size=640x640&scale=2&maptype=terrain&language=en-EN&key=xxx-f9qby3LK2o6bh0BypFWlKrm4>
## ℹ <https://maps.googleapis.com/maps/api/geocode/json?address=San+Francisco&key=xxx-f9qby3LK2o6bh0BypFWlKrm4>
crime_data <- read_csv("violent_crimes.csv")
## Rows: 878049 Columns: 9
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (6): Category, Descript, DayOfWeek, PdDistrict, Resolution, Address
## dbl  (2): X, Y
## dttm (1): Dates
## 
## ℹ 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.
crime_data2 <- crime_data
crime_data <- subset(crime_data, Category %in% c("FRAUD", "BURGLARY", "DRUG/NARCOTIC"))
crime_data
## # A tibble: 107,405 × 9
##    Dates               Category Descript DayOfWeek PdDistrict Resolution Address
##    <dttm>              <chr>    <chr>    <chr>     <chr>      <chr>      <chr>  
##  1 2015-05-13 19:52:00 BURGLARY BURGLAR… Wednesday PARK       ARREST, B… 1500 B…
##  2 2015-05-13 18:30:00 BURGLARY BURGLAR… Wednesday BAYVIEW    NONE       1300 B…
##  3 2015-05-13 18:00:00 BURGLARY BURGLAR… Wednesday SOUTHERN   NONE       0 Bloc…
##  4 2015-05-13 17:55:00 BURGLARY BURGLAR… Wednesday SOUTHERN   ARREST, B… 1200 B…
##  5 2015-05-13 17:47:00 DRUG/NA… POSSESS… Wednesday BAYVIEW    NONE       0 Bloc…
##  6 2015-05-13 17:20:00 BURGLARY BURGLAR… Wednesday CENTRAL    NONE       600 Bl…
##  7 2015-05-13 17:12:00 DRUG/NA… POSSESS… Wednesday SOUTHERN   ARREST, B… 6TH ST…
##  8 2015-05-13 17:00:00 BURGLARY BURGLAR… Wednesday NORTHERN   NONE       500 Bl…
##  9 2015-05-13 14:45:00 BURGLARY BURGLAR… Wednesday SOUTHERN   NONE       800 Bl…
## 10 2015-05-13 14:31:00 DRUG/NA… POSSESS… Wednesday PARK       ARREST, B… 1600 B…
## # ℹ 107,395 more rows
## # ℹ 2 more variables: X <dbl>, Y <dbl>
# Distribución de crimenes en San Francisico
ggmap(myMap) + geom_point(data=crime_data, aes(x = X, y = Y))
## Warning: Removed 1 rows containing missing values (`geom_point()`).

Notemos que el registro de crímenes está distribuido uniformemente en San Francisco, como se puede observar en el mapa.

crime_data <- crime_data %>%
  mutate(
    YEAR = year(ymd_hms(Dates)) 
  )


crime_data <- mutate(crime_data, 
                     THREEYEARS = ifelse(YEAR %in% 2003:2006, "2003-2006", 
                                  ifelse(YEAR %in% 2007:2010, "2007-2010", 
                                  ifelse(YEAR %in% 2011:2014, "2011-2014", 
                                  ifelse(YEAR %in% 2015, "2015", "-99")))))

last_plot <- ggmap(myMap) + 
  geom_point(data=crime_data, aes(x = X, y = Y, colour= THREEYEARS,   alpha = 0.2))
gg <- ggplot_build(last_plot)$plot
plotly_plot <- ggplotly(gg)
plotly_plot
myMap <- get_map(location = "San Francisco", zoom = 12)
## ℹ <https://maps.googleapis.com/maps/api/staticmap?center=San%20Francisco&zoom=12&size=640x640&scale=2&maptype=terrain&language=en-EN&key=xxx-f9qby3LK2o6bh0BypFWlKrm4>
## ℹ <https://maps.googleapis.com/maps/api/geocode/json?address=San+Francisco&key=xxx-f9qby3LK2o6bh0BypFWlKrm4>
ggmap(myMap) + 
  geom_point(data=crime_data, 
             aes(x = X, y = Y, colour= THREEYEARS, size = Category,   alpha = 0.5))
## Warning: Using size for a discrete variable is not advised.
## Warning: Removed 1 rows containing missing values (`geom_point()`).

En el mapa se visualizan los datos cada 3 años; sin embargo, estos se superponen, por lo tanto, solo es fácil visualizar los registros en el rango de 2003 a 2006.

myMap <- get_map(location = "San Francisco", zoom = 14)
## ℹ <https://maps.googleapis.com/maps/api/staticmap?center=San%20Francisco&zoom=14&size=640x640&scale=2&maptype=terrain&language=en-EN&key=xxx-f9qby3LK2o6bh0BypFWlKrm4>
## ℹ <https://maps.googleapis.com/maps/api/geocode/json?address=San+Francisco&key=xxx-f9qby3LK2o6bh0BypFWlKrm4>
ggmap(myMap, extent = "device") + 
  geom_density2d(data = crime_data, aes(x =X, y = Y), size = 0.3) +
  stat_density2d(data = crime_data, 
                 aes(x = X, y = Y, fill = ..level.., 
                     alpha =..level..), 
                 size = 0.01, bins = 16, geom = "polygon") + 
  scale_fill_gradient(low = "green", high ="red") + 
  scale_alpha(range = c(0, 0.3), guide = FALSE)
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## Warning: The dot-dot notation (`..level..`) was deprecated in ggplot2 3.4.0.
## ℹ Please use `after_stat(level)` instead.
## ℹ The deprecated feature was likely used in the ggmap package.
##   Please report the issue at <https://github.com/dkahle/ggmap/issues>.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## Warning: Removed 37268 rows containing non-finite values (`stat_density2d()`).
## Removed 37268 rows containing non-finite values (`stat_density2d()`).
## Warning: The `guide` argument in `scale_*()` cannot be `FALSE`. This was deprecated in
## ggplot2 3.3.4.
## ℹ Please use "none" instead.
## ℹ The deprecated feature was likely used in the ggmap package.
##   Please report the issue at <https://github.com/dkahle/ggmap/issues>.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

ggmap(myMap, extent = "device",  zoom = 14) + 
  stat_density2d(data = crime_data, 
                 aes(x =X, y = Y, fill = ..level.., 
                     alpha = ..level..), 
                 size = 0.01,bins = 16, geom = "polygon") + 
  scale_fill_gradient(low = "green", high ="red") + 
  scale_alpha(range = c(0, 0.3), guide = FALSE)
## Warning: Removed 37268 rows containing non-finite values (`stat_density2d()`).

En estos Heatmaps se puede ver que los c están dispersos por toda la ciudad, pero parece haber concentraciones más altas en ciertas áreas, lo cual podría sugerir puntos de interés o preocupación

crime_data <- filter(crime_data, YEAR %in% c(2003, 2006, 2009, 2012, 2015))

gg <- ggmap(myMap, extent = "device",  zoom = 14) + 
  stat_density2d(data = crime_data, aes(x = X, y = Y, fill = ..level.., alpha = ..level..),
                 size = 0.01, bins = 16, geom = "polygon") +
  scale_fill_gradient(low = "green", high ="red") + 
  scale_alpha(range = c(0, 0.3), guide = FALSE) + 
  facet_wrap(~YEAR, ncol = 3)
  theme(plot.title = element_text(size = 20)) +
  theme(plot.margin = margin(1, 1, 1, 1, "cm"))
## List of 2
##  $ plot.title :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : num 20
##   ..$ hjust        : NULL
##   ..$ vjust        : NULL
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : NULL
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi FALSE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ plot.margin: 'margin' num [1:4] 1cm 1cm 1cm 1cm
##   ..- attr(*, "unit")= int 1
##  - attr(*, "class")= chr [1:2] "theme" "gg"
##  - attr(*, "complete")= logi FALSE
##  - attr(*, "validate")= logi TRUE
print(gg)
## Warning: Removed 13577 rows containing non-finite values (`stat_density2d()`).

Cada mapa muestra cómo la distribución y la intensidad de los eventos han cambiado a lo largo de los años. Los puntos más rojos indican áreas con la mayor densidad de eventos, mientras que los verdes indican una densidad menor. Por ejemplo, se puede observar un punto particularmente rojo en el mapa de 2009, lo cual sugiere una concentración alta de eventos en esa área y año específico.

sf_map <- get_map(location = c(lon = mean(crime_data$X), lat = mean(crime_data$Y)), zoom = 12)
## ℹ <https://maps.googleapis.com/maps/api/staticmap?center=37.769813,-122.421859&zoom=12&size=640x640&scale=2&maptype=terrain&language=en-EN&key=xxx-f9qby3LK2o6bh0BypFWlKrm4>
# Crear el mapa con puntos
ggmap(sf_map) +
  geom_point(data = crime_data2, aes(x = X, y = Y, color = Category), alpha = 0.5) +
  labs(title = "Mapa de Delitos Violentos", x = "Longitud", y = "Latitud") +
  theme_minimal() +
  theme(legend.text = element_text(size = 8))
## Warning: Removed 67 rows containing missing values (`geom_point()`).

Este mapa muestra los diferentes delitos. Cada punto está codificado por colores que corresponden a diferentes tipos de delitos, como se puede ver en la leyenda a la derecha del mapa.