Skip to content

Instantly share code, notes, and snippets.

@dubsnipe
Forked from jclopeztavera/mapeando_sismo.R
Created September 21, 2017 03:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dubsnipe/bd5e290980b11ab7253fffd06badfdd7 to your computer and use it in GitHub Desktop.
Save dubsnipe/bd5e290980b11ab7253fffd06badfdd7 to your computer and use it in GitHub Desktop.
Mapeo de daños por sismo en CDMX
## Cargando los paquetes necesarios para el análisis
if (!require(tidyverse)) {
install.packages(tidyverse)
}
library(tidyverse)
if (!require(googledrive)) {
install.packages("googledrive")
}
library(googledrive)
if (!require(ggmap)) {
install.packages("ggmap")
}
library(ggmap)
if (!require(ggplot2)) {
install.packages("ggplot2")
}
library(ggplot2)
## Seleccionando la URL del link
url <-
"https://docs.google.com/spreadsheets/d/1ijleBcHJH_3V2nbMeXTjH4hTDYsjcdodYvHqhTc8C8c/edit#gid=0"
## Descargando el archivo de Google Drive (require autorizar con Oauth2.0)
drive_download(file = as_id(url),
path = "raw_sismo_cdmx.csv",
overwrite = TRUE)
## ¿cuál es la fecha?
fecha <- Sys.time() %>% format.Date("%d-%m-%Y %H%M %p")
## Cargando los datos en el ambiente de trabajo
sismo <- read_csv("raw_sismo_cdmx.csv")
## Seleccionando las variables de interés
sismo <- sismo %>%
select(
lugar,
tipo_daño,
calle,
numero_exterior,
entrecalles,
colonia,
entidad,
lat,
lon,
link_google_maps
)
## Transformando y limpiando los datos
tidy.sismo <- sismo %>%
mutate_if(is_character, tolower) %>%
mutate(
tipo_daño = ifelse(
test = grepl(
pattern = "derrumbe",
x = .$tipo_daño,
ignore.case = TRUE
),
yes = "derrumbe",
no = "daño"
),
otro_identificador = numero_exterior,
numero_exterior = parse_number(numero_exterior),
colonia = ifelse(
test = is.na(colonia),
yes = NA,
no = paste("colonia", colonia)
),
entidad = ifelse(
test = grepl(
pattern = "ciudad de",
x = .$entidad,
ignore.case = TRUE
),
yes = "CDMX",
no = "CDMX"
),
lat = parse_number(lat),
lon = parse_number(lon)
) %>%
separate(
col = entrecalles,
into = c("calle_1", "calle_2"),
sep = " y ",
remove = TRUE,
extra = "merge",
fill = "right"
)
tidy.sismo$otro_identificador[!is.na(parse_number(tidy.sismo$otro_identificador))] <- NA
tidy.sismo$otro_identificador <- tidy.sismo$otro_identificador[is.na(parse_number(tidy.sismo$otro_identificador))]
## Separando las observaciones que si/no tienen latitud, longitud o liga maps
to_get_latlon <- tidy.sismo %>%
filter(((is.na(lat) |
is.na(lon)) & is.na(link_google_maps)))
got_latlon <- tidy.sismo %>%
filter(!((is.na(lat) |
is.na(lon)) & is.na(link_google_maps)))
## Del API de Google Maps, obteniendo latitud y longitud
addresses <- with(data = to_get_latlon,
paste(test = ifelse(
is.na(calle),
yes = ifelse(
test = is.na(calle_1),
yes = calle_2,
no = calle_1
),
no = calle
), numero_exterior, colonia)) %>%
gsub(pattern = "NA", replacement = "") %>%
paste("Ciudad de Mexico")
lat_lon <- geocode(addresses)
to_get_latlon$lat <- lat_lon$lat
to_get_latlon$lon <- lat_lon$lon
## Uniendo de nuevo los datos, ya con latitud, longitud
tidy.sismo <- bind_rows(got_latlon, to_get_latlon)
## Guardando los datos limpios
write_csv(
x = tidy.sismo,
path = paste("tidy_sismo_cdmx.csv"),
col_names = TRUE,
append = TRUE
)
## Limpiando el espacio de trabajo
rm(list = ls()[!ls() %in% c("tidy.sismo", "fecha")])
## Descargando el mapa de la CDMX
mexico_city <- get_map(
location = "mexico city",
zoom = 11,
scale = "auto",
maptype = "roadmap",
source = "google",
color = "bw",
force = TRUE
) %>%
ggmap() ## en formato google maps
## Mapeando los puntos de daños y derrumbes en el mapa
map_sismo_1 <- mexico_city + geom_point(
data = tidy.sismo,
mapping = aes(x = lon, y = lat, colour = tipo_daño),
alpha = 0.35,
size = 1
) +
scale_colour_manual(
name = "Tipo de Daño",
labels = c("Daño", "Derrumbe"),
values = c("blue", "red")
) +
ggtitle(
list(
title = paste("Reporte de",
nrow(tidy.sismo),
"Daños por el Terremoto en la CDMX"),
subtitle = paste(
"Datos del Mapeo Colaborativo en Google Drive, (última actualización: ",
fecha,
")",
sep = ""
),
x = "Longitud",
y = "Latitud",
caption = "https://gist.github.com/jclopeztavera/c59f595da6553dbf26cd4c2f837a9b70"
)
) +
theme_bw(base_size = 14)
## Guardando el grafico en un archivo png
filename = paste0("sismo_cdmx ", fecha, ".png")
ggsave(
filename = filename,
plot = map_sismo_1,
device = "png",
width = 25,
height = 25,
units = "cm",
dpi = 500
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment