#PRACTICA 5

##Acciones Iniciales

delitos <- read.csv("https://cdaj.netlify.app/data/delitos_fecha_lugar.csv")
## Warning in scan(file = file, what = what, sep = sep, quote = quote, dec = dec,
## : embedded nul(s) found in input
library(lubridate)
## 
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
delitos$franja <- (delitos$franja)
library(tidyverse)
## ── 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
## āœ” purrr   1.0.1     āœ” tidyr   1.3.0
## ── 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

##I. Utilizando la información disponible en el dataset de delitos, creemos un grĆ”fico un grĆ”fico de lĆ­neas con geom_line() que muestre el ritmo horario para cada tipo. ĀæQuĆ© patrones se vislumbran? ĀæQuĆ© franja horaria representan la ā€œhora picoā€ (u ā€œhora puntaā€) para cada categorĆ­a?

delitos1 <- delitos %>%
  group_by(tipo, franja) %>%
  summarise(count = n())
## `summarise()` has grouped output by 'tipo'. You can override using the
## `.groups` argument.
Delito <- delitos %>%
  group_by(tipo) %>%
  summarise(total = sum( ))
ggplot(delitos1, aes(x = franja, y = count, color = tipo)) +
  geom_line() +
  labs(x = "Hora del dĆ­a", y = "Recuento de delitos", title = "Ritmo horario de delitos por tipo")
## Warning: Removed 2 rows containing missing values (`geom_line()`).

ggplot(delitos1, aes(x = franja, y = count, color = tipo)) +
  geom_line() +
  labs(x = "Hora del dĆ­a", y = "Recuento de delitos", title = "Ritmo horario de delitos por tipo")+facet_wrap(vars(tipo))
## Warning: Removed 2 rows containing missing values (`geom_line()`).

ggplot(delitos1, aes(x = franja, y = count, color = tipo)) +
  geom_line() +
  labs(x = "Hora del dĆ­a", y = "Recuento de delitos", title = "Ritmo horario de delitos por tipo")+facet_wrap(vars(tipo), scales = "free")
## Warning: Removed 2 rows containing missing values (`geom_line()`).

##Instalando paquetes

options(repos = c(CRAN = "http://cran.rstudio.com/"))
install.packages("ggmap")
## Installing package into 'C:/Users/USUARIO/AppData/Local/R/win-library/4.3'
## (as 'lib' is unspecified)
## package 'ggmap' successfully unpacked and MD5 sums checked
## 
## The downloaded binary packages are in
##  C:\Users\USUARIO\AppData\Local\Temp\RtmpC0PtrW\downloaded_packages
library(ggmap)
## The legacy packages maptools, rgdal, and rgeos, underpinning this package
## will retire shortly. Please refer to R-spatial evolution reports on
## https://r-spatial.org/r/2023/05/15/evolution4.html for details.
## This package is now running under evolution status 0
## ℹ Google's Terms of Service: <https://mapsplatform.google.com>
## ℹ Please cite ggmap if you use it! Use `citation("ggmap")` for details.
citation("ggmap")
## To cite package 'ggmap' in publications use:
## 
##   D. Kahle and H. Wickham. ggmap: Spatial Visualization with ggplot2.
##   The R Journal, 5(1), 144-161. URL
##   http://journal.r-project.org/archive/2013-1/kahle-wickham.pdf
## 
## A BibTeX entry for LaTeX users is
## 
##   @Article{,
##     author = {David Kahle and Hadley Wickham},
##     title = {ggmap: Spatial Visualization with ggplot2},
##     journal = {The R Journal},
##     year = {2013},
##     volume = {5},
##     number = {1},
##     pages = {144--161},
##     url = {https://journal.r-project.org/archive/2013-1/kahle-wickham.pdf},
##   }
library(ggplot2)

##MAPAS

###MAPA DE LOS ECHOS

ggplot(delitos) +
    geom_point(data = delitos,
               aes(x = longitud, y = latitud, color = tipo),
               size = 0.2, alpha = 0.2) +
    guides(color = guide_legend(override.aes = list(size = 2, alpha = 2)))
## Warning: Removed 411 rows containing missing values (`geom_point()`).

bbox <- make_bbox(delitos$longitud, delitos$latitud)
bbox
##      left    bottom     right       top 
## -58.54046 -34.71247 -58.33403 -34.52172

###MAPA DE CABA

CABA <- get_stamenmap(bbox = bbox, maptype = "toner", zoom = 12)
## ℹ Map tiles by Stamen Design, under CC BY 3.0. Data by OpenStreetMap, under ODbL.
CABA
## 676x601 toner map image from Stamen Maps; use `ggmap::ggmap()` to plot it.
ggmap(CABA)

###AMBOS MAPAS JUNTOS

ggmap(CABA) +
    geom_point(data = delitos,
               aes(x = longitud, y = latitud, color = tipo),
               size = 0.1, alpha = 0.1) +
    guides(color = guide_legend(override.aes = list(size = 1, alpha = 1)))
## Warning: Removed 411 rows containing missing values (`geom_point()`).

####MAPA POR HORAS

ggmap(CABA) +
    geom_point(data = delitos,
               aes(x = longitud, y = latitud, color = tipo),
               size = 0.1, alpha = 0.1) +
    guides(color = guide_legend(override.aes = list(size = 1, alpha = 1)))+
    facet_wrap(vars(franja), nrow = 4) +
    labs(title = "Ciudad de Buenos Aires",
         subtitle = "según hora del día, durante el año 2020",
         caption = "fuente: https://mapa.seguridadciudad.gob.ar") +
    theme_void()
## Warning: Removed 411 rows containing missing values (`geom_point()`).

#####POR HORAS Y TIPO ESPECIFICO

ggmap(CABA) +
    geom_density2d_filled(data = filter(delitos, !is.na(franja), tipo == "Hurto (sin violencia)"),
               aes(x = longitud, y = latitud), alpha = .5) +
    guides(fill = FALSE) +
    facet_wrap(vars(franja), nrow = 4) +
    labs(title = "Ciudad de Buenos Aires: concentración espacial de hurtos",
         subtitle = "según hora del día, durante el año 2020",
         caption = "fuente: https://mapa.seguridadciudad.gob.ar") +
    theme_void()
## Warning: The `<scale>` argument of `guides()` cannot be `FALSE`. Use "none" instead as
## of ggplot2 3.3.4.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## Warning: Removed 42 rows containing non-finite values
## (`stat_density2d_filled()`).

######Hurto (sin violencia)

ggmap(CABA) +
    geom_point(data = filter(delitos, !is.na(franja), tipo == "Hurto (sin violencia)"),
               aes(x = longitud, y = latitud, color = tipo),
               size = 0.1, alpha = 0.1) +
    guides(color = guide_legend(override.aes = list(size = 1, alpha = 1)))+
    facet_wrap(vars(franja), nrow = 4) +
    labs(title = "Ciudad de Buenos Aires: concentración espacial de hurtos",
         subtitle = "según hora del día, durante el año 2020",
         caption = "fuente: https://mapa.seguridadciudad.gob.ar") +
    theme_void()
## Warning: Removed 42 rows containing missing values (`geom_point()`).

######Homicidios

ggmap(CABA) +
    geom_point(data = filter(delitos, !is.na(franja), tipo == "Homicidio"),
               aes(x = longitud, y = latitud, color = tipo),
               size = 0.1, alpha = 0.1) +
    guides(color = guide_legend(override.aes = list(size = 1, alpha = 1)))+
    facet_wrap(vars(franja), nrow = 4) +
    labs(title = "Ciudad de Buenos Aires: concentración espacial de Homicidios",
         subtitle = "según hora del día, durante el año 2020",
         caption = "fuente: https://mapa.seguridadciudad.gob.ar") +
    theme_void()

######Lesiones

ggmap(CABA) +
    geom_point(data = filter(delitos, !is.na(franja), tipo == "Lesiones"),
               aes(x = longitud, y = latitud, color = tipo),
               size = 0.1, alpha = 0.1) +
    guides(color = guide_legend(override.aes = list(size = 1, alpha = 1)))+
    facet_wrap(vars(franja), nrow = 4) +
    labs(title = "Ciudad de Buenos Aires: concentración espacial de Lesiones",
         subtitle = "según hora del día, durante el año 2020",
         caption = "fuente: https://mapa.seguridadciudad.gob.ar") +
    theme_void()
## Warning: Removed 306 rows containing missing values (`geom_point()`).

######Robos (con violencia)

ggmap(CABA) +
    geom_point(data = filter(delitos, !is.na(franja), tipo == "Robo (con violencia)"),
               aes(x = longitud, y = latitud, color = tipo),
               size = 0.1, alpha = 0.1) +
    guides(color = guide_legend(override.aes = list(size = 1, alpha = 1)))+
    facet_wrap(vars(franja), nrow = 4) +
    labs(title = "Ciudad de Buenos Aires: concentración espacial de Robos (con violencia)",
         subtitle = "según hora del día, durante el año 2020",
         caption = "fuente: https://mapa.seguridadciudad.gob.ar") +
    theme_void()
## Warning: Removed 49 rows containing missing values (`geom_point()`).

###seguimos la sugerencia ¿Qué otras técnicas podemos usar para lidiar con el exceso de información volcada en pantalla? Sugerencia: intentar con geom_count()

delitos$Recuento <- 1:nrow(delitos)
ggplot(delitos, aes(x = fecha, y = Recuento, group = tipo, color = tipo)) +
  geom_count() +
  labs(x = "Fecha", y = "Recuento acumulativo de Delitos", title = "Recuento acumulativo de delitos por tipo")

####reduciendo tamaƱo de los puntos

ggplot(delitos, aes(x = fecha, y = Recuento, group = tipo, color = tipo)) +
  geom_count(size = 0.8) +
  labs(x = "Fecha", y = "Recuento acumulativo de Delitos", title = "Recuento acumulativo de delitos por tipo")