Patrones espaciales y temporales

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.2     ✔ tibble    3.3.0
## ✔ lubridate 1.9.4     ✔ tidyr     1.3.1
## ✔ purrr     1.0.4     
## ── 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(sf)
## Linking to GEOS 3.13.0, GDAL 3.8.5, PROJ 9.5.1; sf_use_s2() is TRUE
library(ggmap)
## ℹ 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.
library(lubridate)
cdmx_transito <- read.csv("data/hechos-transito-cdmx-2024.csv",
                          stringsAsFactors = TRUE)
today()-111
## [1] "2025-03-21"
today()+379
## [1] "2026-07-24"
now(tzone="Europe/Paris")
## [1] "2025-07-11 01:30:25 CEST"
wday("2027-03-08", label=TRUE, abbr=FALSE, locale="es_ES.UTF-8")
## [1] lunes
## 7 Levels: domingo < lunes < martes < miércoles < jueves < ... < sábado
month("2027-03-08", label=TRUE, abbr=FALSE, locale="es_ES.UTF-8")
## [1] marzo
## 12 Levels: enero < febrero < marzo < abril < mayo < junio < ... < diciembre
summary(cdmx_transito)
##                 folio           fecha_evento    hora_evento   
##   C5/20240619/04624:    1   2024-04-19:  134   09:02  :   53  
##  C2C/20240102/00031:    1   2024-02-02:  118   08:54  :   49  
##  C2C/20240104/00056:    1   2024-02-03:  114   08:03  :   47  
##  C2C/20240104/00171:    1   2024-10-10:  114   09:10  :   45  
##  C2C/20240105/00209:    1   2024-02-10:  112   08:25  :   44  
##  C2C/20240108/00100:    1   2024-06-29:  111   08:57  :   43  
##  (Other)           :30644   (Other)   :29947   (Other):30369  
##             tipo_evento       longitud         latitud     
##  ATROPELLADO      : 4822   Min.   :-99.35   Min.   :19.10  
##  CAIDA DE CICLISTA:  761   1st Qu.:-99.17   1st Qu.:19.34  
##  CAIDA DE PASAJERO:  611   Median :-99.14   Median :19.40  
##  CHOQUE           :18109   Mean   :-99.14   Mean   :19.39  
##  DERRAPADO        : 5866   3rd Qu.:-99.10   3rd Qu.:19.44  
##  VOLCADURA        :  481   Max.   :-98.95   Max.   :19.58  
## 
str(cdmx_transito$fecha_evento)
##  Factor w/ 366 levels "2024-01-01","2024-01-02",..: 1 1 1 1 1 1 1 1 1 1 ...

año-mes-dia año-dia-mes dia-mes-año mes-dia-año

ymd()

cdmx_transito <- mutate(cdmx_transito,
                        fecha_evento=ymd(fecha_evento))
str(cdmx_transito$fecha_evento)
##  Date[1:30650], format: "2024-01-01" "2024-01-01" "2024-01-01" "2024-01-01" "2024-01-01" ...
cdmx_transito <- mutate(cdmx_transito,
                        dia_semana=wday(fecha_evento, label=TRUE, abbr=FALSE, locale="es_ES.UTF-8"),
                        mes=month(fecha_evento, label=TRUE, abbr=FALSE, locale="es_ES.UTF-8"))
ggplot()+
  geom_bar(data=cdmx_transito, aes(x=dia_semana))

ggplot()+
  geom_bar(data=cdmx_transito, aes(x=mes, fill=tipo_evento),
           position = position_dodge())+
  scale_fill_manual(values=c("#f94144", "#f8961e", "#f9c74f", "#43aa8b", "#577590", "#277da1"))+
  theme_light()

cdmx_transito_dia <- cdmx_transito %>%
  group_by(fecha_evento) %>%
  summarise(cantidad=n())
ggplot()+
  geom_line(data=cdmx_transito_dia, aes(x=fecha_evento, y=cantidad))

Análisis geográfico

ggplot()+
  geom_point(data=cdmx_transito, aes(x=longitud, y=latitud))

register_stadiamaps("fe33f184-eee0-4e54-9c25-1685fc07ff4e", write = TRUE)
## ℹ Replacing old key (fe33f184) with new key in /Users/angiescetta/.Renviron
cdmx_bbox <- make_bbox(cdmx_transito$longitud, cdmx_transito$latitud) 
cdmx_bbox
##      left    bottom     right       top 
## -99.36838  19.07799 -98.92832  19.60033
mapa_base <- get_stadiamap(bbox = cdmx_bbox,
                           maptype = "alidade_smooth",
                           zoom = 11)
## ℹ © Stadia Maps © Stamen Design © OpenMapTiles © OpenStreetMap contributors.
ggmap(mapa_base)+
  geom_point(data=cdmx_transito, aes(x=longitud, y=latitud), alpha=0.5, size=0.2)

ggmap(mapa_base)+
  geom_bin2d(data=cdmx_transito, aes(x=longitud, y=latitud), bins=50, alpha=0.85)+
  scale_fill_viridis_c(direction = -1)+
  facet_wrap(~dia_semana, ncol=4)+
  theme_void()

ggmap(mapa_base)+
  geom_bin2d(data=cdmx_transito, aes(x=longitud, y=latitud), bins=50, alpha=0.85)+
  scale_fill_viridis_c(direction = -1)+
  facet_wrap(~tipo_evento, ncol=3)+
  theme_void()

ggmap(mapa_base)+
  geom_bin2d(data=cdmx_transito, aes(x=longitud, y=latitud), bins=50, alpha=0.85)+
  scale_fill_viridis_c(direction = -1)+
  facet_wrap(~mes, ncol=6)+
  theme_void()

ggmap(mapa_base)+
  stat_density2d(data=cdmx_transito, aes(x=longitud, y=latitud,
                                         fill =after_stat(level)),
                 geom="polygon", alpha=0.5)+
  scale_fill_distiller(palette = "Spectral")+
  facet_wrap(~dia_semana, ncol=4)+
  theme_void()

library(gganimate)
library(gifski)
mapa_animado <- ggmap(mapa_base)+
  stat_density2d(data=cdmx_transito %>%
                   filter(mes=="diciembre"), aes(x=longitud, y=latitud,
                                         fill =after_stat(level)),
                 geom="polygon", alpha=0.5)+
  scale_fill_distiller(palette = "Spectral")+
  labs(title="Hechos tránsito CDMX",
       subtitle = "CDMX | Dia: {frame_time}")+
  transition_time(fecha_evento)
animate(mapa_animado, renderer=gifski_renderer())