library(tidyverse)
## ── Attaching packages ──────────────────────────────────────── tidyverse 1.2.1 ──
## ✔ ggplot2 3.2.1     ✔ purrr   0.3.2
## ✔ tibble  2.1.3     ✔ dplyr   0.8.3
## ✔ tidyr   0.8.3     ✔ stringr 1.4.0
## ✔ readr   1.3.1     ✔ forcats 0.4.0
## ── Conflicts ─────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
library(sf)
## Linking to GEOS 3.6.1, GDAL 2.1.3, PROJ 4.9.3
denuncias_acumar <- read.csv("~/Desktop/Ciencia de Datos para Ciudades II/Ejercicio IV/acumar_modif.csv", stringsAsFactors = FALSE)
summary(denuncias_acumar)
##        Id         fecha.de.creacion  hora_de_creacion      canal          
##  Min.   :   1.0   Length:1412        Length:1412        Length:1412       
##  1st Qu.: 353.8   Class :character   Class :character   Class :character  
##  Median : 706.5   Mode  :character   Mode  :character   Mode  :character  
##  Mean   : 706.7                                                           
##  3rd Qu.:1059.2                                                           
##  Max.   :1413.0                                                           
##  denuncia_tipo      denuncia_motivo    denuncia_localidad      lat        
##  Length:1412        Length:1412        Length:1412        Min.   :-35.05  
##  Class :character   Class :character   Class :character   1st Qu.:-34.77  
##  Mode  :character   Mode  :character   Mode  :character   Median :-34.70  
##                                                           Mean   :-34.72  
##                                                           3rd Qu.:-34.66  
##                                                           Max.   :-33.90  
##       lon         denuncia_estado    fecha_de_cierre   
##  Min.   :-60.59   Length:1412        Length:1412       
##  1st Qu.:-58.62   Class :character   Class :character  
##  Median :-58.40   Mode  :character   Mode  :character  
##  Mean   :-58.48                                        
##  3rd Qu.:-58.40                                        
##  Max.   :-58.27                                        
##  denuncia_hora_de_cierre denuncia_motivo_cierre
##  Length:1412             Length:1412           
##  Class :character        Class :character      
##  Mode  :character        Mode  :character      
##                                                
##                                                
## 
library(tidyverse)
library(lubridate)
## 
## Attaching package: 'lubridate'
## The following object is masked from 'package:base':
## 
##     date
denuncias_acumar<-denuncias_acumar%>% mutate(fecha.de.creacion=dmy (fecha.de.creacion))
set.seed("99")
muestra_de_fechas <- denuncias_acumar %>% 
    sample_n(5) %>% 
    pull(fecha.de.creacion)

muestra_de_fechas
## [1] "2016-04-18" "2011-12-19" "2014-01-16" "2013-06-12" "2013-11-15"
wday(muestra_de_fechas)
## [1] 2 2 5 4 6
wday(muestra_de_fechas, label=TRUE)
## [1] Mon Mon Thu Wed Fri
## Levels: Sun < Mon < Tue < Wed < Thu < Fri < Sat
month(muestra_de_fechas, label=TRUE)
## [1] Apr Dec Jan Jun Nov
## 12 Levels: Jan < Feb < Mar < Apr < May < Jun < Jul < Aug < Sep < ... < Dec
year(muestra_de_fechas)
## [1] 2016 2011 2014 2013 2013
week(muestra_de_fechas)
## [1] 16 51  3 24 46
options(scipen = 20)

ggplot(denuncias_acumar) + 
    geom_bar(aes(x = year(fecha.de.creacion)))

denuncias_acumar %>% 
    filter(year(fecha.de.creacion) == 2012) %>% 
    ggplot() +
        geom_bar(aes(x = month(fecha.de.creacion, label = TRUE)))

denuncias_acumar%>% 
    count(denuncia_tipo) %>% 
    top_n(5) %>% 
    arrange(desc(n))
## Selecting by n
## # A tibble: 5 x 2
##   denuncia_tipo        n
##   <chr>            <int>
## 1 establecimiento   1210
## 2 basural            145
## 3 establecimientos    25
## 4 margenes            15
## 5 no informa           5
denuncias_frecuentes <- denuncias_acumar %>% 
    count(denuncia_tipo) %>% 
    top_n(5) %>% 
    pull(denuncia_tipo)
## Selecting by n
denuncias_acumar %>% 
    filter(year(fecha.de.creacion) == 2012,
           denuncia_tipo %in% denuncias_frecuentes) %>% 
    ggplot() +
        geom_bar(aes(x = month(fecha.de.creacion, label = TRUE), fill = denuncia_tipo))

denuncias_acumar%>% 
    filter(year(fecha.de.creacion) == 2012,
           denuncia_tipo %in% denuncias_frecuentes) %>% 
    ggplot() +
        geom_bar(aes(x = month(fecha.de.creacion, label = TRUE), fill = denuncia_tipo),
                 position = "dodge")

# Primero realizamos un conteo de denuncias por tipo y por mes del año
conteo <-  denuncias_acumar %>% 
    filter(year(fecha.de.creacion) == 2012,
           denuncia_tipo %in% denuncias_frecuentes) %>% 
    count(denuncia_tipo, mes = month(fecha.de.creacion, label = TRUE))
   
# Y ahora a mostras las cantidades mensuales como líneas 
ggplot(conteo) +
    geom_line(aes(x = mes, y = n, group = denuncia_tipo, color = denuncia_tipo))

# Primero realizamos un conteo de delitos por tipo y por día de la semana
conteo <-  denuncias_acumar %>% 
    filter(year(fecha.de.creacion) == 2012,
           denuncia_tipo %in% denuncias_frecuentes) %>% 
    count(denuncia_tipo, diasemana = wday(fecha.de.creacion, label = TRUE))
   
# Y ahora a mostras las cantidades mensuales como líneas 
ggplot(conteo) +
    geom_line(aes(x = diasemana, y = n, group = denuncia_tipo, color = denuncia_tipo))+
  geom_point(aes(x = diasemana, y = n, group = denuncia_tipo, color = denuncia_tipo))

conteo <-  conteo  %>% 
    group_by(denuncia_tipo) %>% 
    mutate(porcentaje = n / sum(n) * 100)

ggplot(conteo) +
    geom_line(aes(x = diasemana, y = porcentaje, group = denuncia_tipo, color = denuncia_tipo))

ggplot(conteo) +
    geom_line(aes(x = diasemana, y = porcentaje, group = denuncia_tipo, color = denuncia_tipo))+
    expand_limits(y = 0)

conteo_establecimiento <-  denuncias_acumar %>% 
    filter(year(fecha.de.creacion) == 2012,
           denuncia_tipo == "establecimiento") %>% 
    count(denuncia_tipo, diasemana = wday(fecha.de.creacion, label = TRUE)) %>%
    group_by(denuncia_tipo) %>% 
    mutate(porcentaje = n / sum(n) *100)
por_hora <-  denuncias_acumar %>% 
    filter(year(fecha.de.creacion) == 2012,
           denuncia_tipo %in% denuncias_frecuentes) %>% 
    count(denuncia_tipo, hora_de_creacion = hour(hms(hora_de_creacion))) %>%
    group_by(denuncia_tipo) %>% 
    mutate(porcentaje = n / sum(n) *100)
ggplot(conteo) +
    geom_line(aes(x = diasemana, y = porcentaje, group = denuncia_tipo, color = denuncia_tipo)) +
    geom_line(data = conteo_establecimiento,
              aes(x = diasemana, y = porcentaje, group = denuncia_tipo)) +
    labs(title = "Distribución diaria por tipo de denuncia",
         subtitle = "La línea negra representa establecimiento",
         x = "día", y = "%",
         color = "De más frecuentes") +
    expand_limits(y = 0)

por_hora <-  denuncias_acumar %>% 
    filter(year(fecha.de.creacion) == 2012,
           denuncia_tipo %in% denuncias_frecuentes) %>% 
    count(denuncia_tipo, hora_de_creacion = hour(hms(hora_de_creacion))) %>%
    group_by(denuncia_tipo) %>% 
    mutate(porcentaje = n / sum(n) *100)
ggplot(por_hora) +
    geom_line(aes(x = hora_de_creacion, y = porcentaje, group = denuncia_tipo, color = denuncia_tipo)) +
    labs(title = "Distribución horaria por tipo de denuncia",
         x = "hora", y = "%",
         color = "Denuncias más frecuentes") +
    expand_limits(y = 0) +
    scale_x_continuous(breaks = 0:23)

library(ggmap)
## Google's Terms of Service: https://cloud.google.com/maps-platform/terms/.
## Please cite ggmap if you use it! See citation("ggmap") for details.
library(osmdata)
## Data (c) OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright
denuncias_acumar <- denuncias_acumar %>% 
    filter(lat <0, lon <0)

denuncias_acumar <- denuncias_acumar %>% 
filter(denuncia_localidad!="San Vicente")

bbox <- c(min(denuncias_acumar$lon),
min(denuncias_acumar$lat),
max(denuncias_acumar$lon),
max(denuncias_acumar$lat))


PBA <- get_stamenmap(bbox = bbox, 
                      maptype = "toner-lite")
## Source : http://tile.stamen.com/toner-lite/10/344/616.png
## Source : http://tile.stamen.com/toner-lite/10/345/616.png
## Source : http://tile.stamen.com/toner-lite/10/346/616.png
## Source : http://tile.stamen.com/toner-lite/10/344/617.png
## Source : http://tile.stamen.com/toner-lite/10/345/617.png
## Source : http://tile.stamen.com/toner-lite/10/346/617.png
## Source : http://tile.stamen.com/toner-lite/10/344/618.png
## Source : http://tile.stamen.com/toner-lite/10/345/618.png
## Source : http://tile.stamen.com/toner-lite/10/346/618.png
ggmap(PBA)

ggmap(PBA) +
    geom_point(data = denuncias_acumar, aes(x = lon, y = lat),
               color = "orange", size = 0.1, alpha = 0.1)

ggmap(PBA) +
    geom_bin2d(data = denuncias_acumar , 
               aes(x = lon, y = lat))
## Warning: Removed 2 rows containing missing values (geom_tile).

ggmap(PBA) +
    geom_point(data = filter(denuncias_acumar, denuncia_tipo %in% denuncias_frecuentes), 
               aes(x = lon, y = lat, color = denuncia_tipo),
               size = 0.1, alpha = 0.1)

ggmap(PBA) +
    geom_point(data = filter(denuncias_acumar, denuncia_tipo %in% denuncias_frecuentes),
               aes(x = lon, y = lat, color = denuncia_tipo),
               size = 0.1, alpha = 0.1) +
    scale_color_brewer(palette = "Set1") +
    facet_wrap(~denuncia_tipo)

Combinando espacio y tiempo El facetado también nos permite visualizar el cambio de posición a través del tiempo.

Por ejemplo, podemos comparar los motivos de las denuncias (efluentes y residuos especiales) mostrando dónde ocuren en cada día de la semana.

denuncias_acumar <- denuncias_acumar %>% 
    mutate(dia_semana = wday(fecha.de.creacion, label = TRUE))

ggmap(PBA) +
    geom_point(data = filter(denuncias_acumar, 
                             denuncia_motivo %in% c("residuos especiales", "efluentes")),
               aes(x = lon, y = lat, color = denuncia_motivo), alpha = .5, size = .2) +
    facet_wrap(~dia_semana)

denuncias_acumar <- denuncias_acumar %>% 
    mutate(hora_de_creacion = hour(hms(hora_de_creacion)))

ggmap(PBA) +
    geom_density2d(data = filter(denuncias_acumar, 
                                 denuncia_motivo == "residuos especiales",
                                 !(wday(fecha.de.creacion) %in% 2:5) ),
                   aes(x = lon, 
                       y = lat, 
                       color = stat(level))) +
    scale_color_viridis_c() +
    facet_wrap(~hora_de_creacion, nrow = 4) +
    labs(title = "Concentración espacial de denuncias por residuos espaciales",
         subtitle = "según hora del día")
## Warning: Computation failed in `stat_density2d()`:
## missing value where TRUE/FALSE needed
## Warning: Computation failed in `stat_density2d()`:
## bandwidths must be strictly positive
## Warning: Computation failed in `stat_density2d()`:
## missing value where TRUE/FALSE needed