Instalación de paquetes y carga de librerías

#install.packages("data.table") 
#install.packages("readr")
#install.packages("tidyverse")
#install.packages("dplyr")
#install.packages("tidyr")
#install.packages("ggplot2")
#install.packages("sf")
#install.packages("ggmap")
#install.packages("osmdata")
#install.packages("lubridate")

library(data.table)
library(readr)
library(tidyverse)
library(dplyr)
library(magrittr)
library(ggplot2)
library(sf)
library(viridis)
library(viridisLite)
library(ggmap)
library(osmdata)
library(leaflet)
library(Rcpp)
library(lubridate)

# Se quiere conocer la distribución de la población en el área metropolitana de Puebla (AMP), por municipio y más adelante por ageb

## 1. Carga de base de datos censales del Estado de Puebla 2020, escala ageb y manzana (tipo csv)


```r
CensoPue <- read.csv("trabajofinal/RESAGEBURB_21CSV20_CVE.csv", encoding = "UTF-8")

#head(CensoPue)

#summary(CensoPue)

Filtrado de datos, solamente tres municipios del surponiente del Área Metropolitana de Puebla (Puebla, San Andrés Cholula, Ocoyucan) involucrados con el corredor urban Angelópolis y el proyecto Lomas de Angelópolis, por clave de municipio

CensoSPAMP <- CensoPue %>%
  filter(MUN %in% c("106","114","119"))
table(CensoSPAMP$NOM_MUN)
## 
##           Ocoyucan             Puebla San Andrés Cholula 
##                784              17078               1410
#colnames(CensoSPAMP)

2. Carga de información espacial, escalas municipio, ageb (área geoestadística básica de INEGI) y manzana

municipios <- st_read("trabajofinal/municipiosPuebla.geojson")
## Reading layer `municipiosPuebla' from data source 
##   `C:\Users\711167\OneDrive\00-R\Geo\trabajofinal\municipiosPuebla.geojson' 
##   using driver `GeoJSON'
## Simple feature collection with 217 features and 4 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: 2809222 ymin: 657198.7 xmax: 3056419 ymax: 987530.6
## Projected CRS: Mexico ITRF2008 / LCC
head(municipios)
## Simple feature collection with 6 features and 4 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: 2843746 ymin: 659550.4 xmax: 3007994 ymax: 917818.2
## Projected CRS: Mexico ITRF2008 / LCC
##   CVEGEO CVE_ENT CVE_MUN     NOMGEO                       geometry
## 1  21001      21     001    Acajete MULTIPOLYGON (((2926444 802...
## 2  21002      21     002    Acateno MULTIPOLYGON (((2990846 917...
## 3  21003      21     003    Acatlán MULTIPOLYGON (((2901730 677...
## 4  21004      21     004  Acatzingo MULTIPOLYGON (((2940203 797...
## 5  21005      21     005   Acteopan MULTIPOLYGON (((2849259 762...
## 6  21006      21     006 Ahuacatlán MULTIPOLYGON (((2933647 904...
#summary(municipioSPAMP)
ggplot(municipios)+
  geom_sf(data=municipios, aes(fill=CVE_MUN))+ theme(legend.position="none")

Unión espacial y estadística por municipio. Filtro de datos de clave geográfica, población, hogares, viviendas

CensoPuePob <- CensoPue %>% 
  select(CVEGEOL, ENTIDAD, NOM_ENT, MUN, NOM_MUN, LOC, NOM_LOC, POBTOT, TOTHOG, VIVTOT) %>%
  mutate(CVEGEO = substr(CVEGEOL, start = 1, stop = 5))%>%
  filter(NOM_LOC %in% c("Total del municipio")) %>%
  select(CVEGEO, ENTIDAD, NOM_ENT, MUN, NOM_MUN, POBTOT, TOTHOG, VIVTOT) 

head(CensoPuePob)
##   CVEGEO ENTIDAD NOM_ENT MUN    NOM_MUN POBTOT TOTHOG VIVTOT
## 1  21001      21  Puebla   1    Acajete  72894  15226  18617
## 2  21002      21  Puebla   2    Acateno   9170   2611   3161
## 3  21003      21  Puebla   3    Acatlán  37955  10158  15496
## 4  21004      21  Puebla   4  Acatzingo  63743  13486  15749
## 5  21005      21  Puebla   5   Acteopan   3070    850   1147
## 6  21006      21  Puebla   6 Ahuacatlán  14542   3643   4588

Unión de geojson y base de datos con información censal 2020, por municipio

municipios <- left_join(municipios,CensoPuePob, by="CVEGEO")

head(municipios)
## Simple feature collection with 6 features and 11 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: 2843746 ymin: 659550.4 xmax: 3007994 ymax: 917818.2
## Projected CRS: Mexico ITRF2008 / LCC
##   CVEGEO CVE_ENT CVE_MUN     NOMGEO ENTIDAD NOM_ENT MUN    NOM_MUN POBTOT
## 1  21001      21     001    Acajete      21  Puebla   1    Acajete  72894
## 2  21002      21     002    Acateno      21  Puebla   2    Acateno   9170
## 3  21003      21     003    Acatlán      21  Puebla   3    Acatlán  37955
## 4  21004      21     004  Acatzingo      21  Puebla   4  Acatzingo  63743
## 5  21005      21     005   Acteopan      21  Puebla   5   Acteopan   3070
## 6  21006      21     006 Ahuacatlán      21  Puebla   6 Ahuacatlán  14542
##   TOTHOG VIVTOT                       geometry
## 1  15226  18617 MULTIPOLYGON (((2926444 802...
## 2   2611   3161 MULTIPOLYGON (((2990846 917...
## 3  10158  15496 MULTIPOLYGON (((2901730 677...
## 4  13486  15749 MULTIPOLYGON (((2940203 797...
## 5    850   1147 MULTIPOLYGON (((2849259 762...
## 6   3643   4588 MULTIPOLYGON (((2933647 904...

Mapa de municipios del Estado de Puebla

ggplot(municipios)+
  geom_sf(aes(fill=POBTOT), color="white")+
     labs(title="Municipios",
       subtitle="Puebla")+ 
        theme(legend.position="none")

carga de base con superficie de mucnicipios por kilómetro cuadrado

mpiosareas <- read.csv("trabajofinal/mpiosareas.csv", encoding = "UTF-8")

head(mpiosareas)
##   X.U.FEFF.CVEGEO CVE_MUN  MUNICIPIO             CABECERA POB2020 SUPKM2 NOLOC
## 1           21001       1    Acajete              Acajete   72894 185.46    57
## 2           21002       2    Acateno     San José Acateno    9170 180.67    75
## 3           21003       3    Acatlán    Acatlán de Osorio   37955 607.78    73
## 4           21004       4  Acatzingo Acatzingo de Hidalgo   63743 140.53    57
## 5           21005       5   Acteopan             Acteopan    3070  74.84     4
## 6           21006       6 Ahuacatlán           Ahuacatlán   14542  90.98    30
##      IDH CONURB LOMAS
## 1 0.6994             
## 2 0.6706             
## 3 0.7469             
## 4 0.6979             
## 5     NA             
## 6 0.5749
mpiosareas <- mpiosareas %>% 
  mutate(CVEGEO=as.character(X.U.FEFF.CVEGEO))

#summary(municipios)

Unión de geojson y base de datos con superficies

municipios <- left_join(municipios,mpiosareas, by="CVEGEO")

municipios <- municipios %>%
  mutate(DENSIDAD=POBTOT/SUPKM2) %>%
  select(-X.U.FEFF.CVEGEO)

head(municipios)
## Simple feature collection with 6 features and 21 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: 2843746 ymin: 659550.4 xmax: 3007994 ymax: 917818.2
## Projected CRS: Mexico ITRF2008 / LCC
##   CVEGEO CVE_ENT CVE_MUN.x     NOMGEO ENTIDAD NOM_ENT MUN    NOM_MUN POBTOT
## 1  21001      21       001    Acajete      21  Puebla   1    Acajete  72894
## 2  21002      21       002    Acateno      21  Puebla   2    Acateno   9170
## 3  21003      21       003    Acatlán      21  Puebla   3    Acatlán  37955
## 4  21004      21       004  Acatzingo      21  Puebla   4  Acatzingo  63743
## 5  21005      21       005   Acteopan      21  Puebla   5   Acteopan   3070
## 6  21006      21       006 Ahuacatlán      21  Puebla   6 Ahuacatlán  14542
##   TOTHOG VIVTOT CVE_MUN.y  MUNICIPIO             CABECERA POB2020 SUPKM2 NOLOC
## 1  15226  18617         1    Acajete              Acajete   72894 185.46    57
## 2   2611   3161         2    Acateno     San José Acateno    9170 180.67    75
## 3  10158  15496         3    Acatlán    Acatlán de Osorio   37955 607.78    73
## 4  13486  15749         4  Acatzingo Acatzingo de Hidalgo   63743 140.53    57
## 5    850   1147         5   Acteopan             Acteopan    3070  74.84     4
## 6   3643   4588         6 Ahuacatlán           Ahuacatlán   14542  90.98    30
##      IDH CONURB LOMAS  DENSIDAD                       geometry
## 1 0.6994              393.04432 MULTIPOLYGON (((2926444 802...
## 2 0.6706               50.75552 MULTIPOLYGON (((2990846 917...
## 3 0.7469               62.44858 MULTIPOLYGON (((2901730 677...
## 4 0.6979              453.58998 MULTIPOLYGON (((2940203 797...
## 5     NA               41.02084 MULTIPOLYGON (((2849259 762...
## 6 0.5749              159.83733 MULTIPOLYGON (((2933647 904...
summary(municipios)
##     CVEGEO            CVE_ENT           CVE_MUN.x            NOMGEO         
##  Length:217         Length:217         Length:217         Length:217        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##                                                                             
##                                                                             
##                                                                             
##                                                                             
##     ENTIDAD     NOM_ENT               MUN        NOM_MUN         
##  Min.   :21   Length:217         Min.   :  1   Length:217        
##  1st Qu.:21   Class :character   1st Qu.: 55   Class :character  
##  Median :21   Mode  :character   Median :109   Mode  :character  
##  Mean   :21                      Mean   :109                     
##  3rd Qu.:21                      3rd Qu.:163                     
##  Max.   :21                      Max.   :217                     
##                                                                  
##      POBTOT           TOTHOG              VIVTOT         CVE_MUN.y  
##  Min.   :    526   Length:217         Min.   :   277   Min.   :  1  
##  1st Qu.:   5293   Class :character   1st Qu.:  1925   1st Qu.: 55  
##  Median :  11439   Mode  :character   Median :  3789   Median :109  
##  Mean   :  30338                      Mean   : 10004   Mean   :109  
##  3rd Qu.:  22629                      3rd Qu.:  6991   3rd Qu.:163  
##  Max.   :1692181                      Max.   :570222   Max.   :217  
##                                                                     
##   MUNICIPIO           CABECERA            POB2020            SUPKM2      
##  Length:217         Length:217         Min.   :    526   Min.   :  4.10  
##  Class :character   Class :character   1st Qu.:   5293   1st Qu.: 52.38  
##  Mode  :character   Mode  :character   Median :  11439   Median :125.77  
##                                        Mean   :  30288   Mean   :160.83  
##                                        3rd Qu.:  22629   3rd Qu.:222.27  
##                                        Max.   :1692181   Max.   :804.30  
##                                                                          
##      NOLOC             IDH            CONURB             LOMAS          
##  Min.   :  1.00   Min.   :0.5161   Length:217         Length:217        
##  1st Qu.: 10.00   1st Qu.:0.6516   Class :character   Class :character  
##  Median : 19.00   Median :0.6911   Mode  :character   Mode  :character  
##  Mean   : 29.23   Mean   :0.6832                                        
##  3rd Qu.: 38.00   3rd Qu.:0.7224                                        
##  Max.   :161.00   Max.   :0.8269                                        
##                   NA's   :7                                             
##     DENSIDAD                 geometry  
##  Min.   :   5.187   MULTIPOLYGON :217  
##  1st Qu.:  49.788   epsg:6372    :  0  
##  Median : 109.644   +proj=lcc ...:  0  
##  Mean   : 253.380                      
##  3rd Qu.: 250.879                      
##  Max.   :3890.732                      
## 
ggplot(municipios)+
  geom_sf(aes(fill=DENSIDAD), color=NA)+
    labs(title = "Densidad de población por municipio",
         subtitle = "Estado de Puebla",
         fill = "Población/km2",
         caption= "Fuente: Censo General de Población y Vivienda, INEGI, 2020") +
  scale_fill_distiller(palette = "Spectral") +
  theme_light()

ggplot(municipios)+
  geom_sf(aes(fill=DENSIDAD), color=NA)+
    labs(title = "Densidad de población por municipio",
         subtitle = "Estado de Puebla",
         fill = "Población/km2",
         caption= "Fuente: Censo General de Población y Vivienda, INEGI, 2020") +
  scale_fill_viridis_c(breaks=c(0,250,500,750,1500,4000), option = "plasma", direction = -1)+
  theme_light()

ggplot()+
  geom_sf(data=municipios)+
  geom_sf(data=filter(municipios, CONURB=="AMP"), aes(fill=DENSIDAD))+
    labs(title = "Área metropolitana de Puebla",
         fill = "Municipios conurbados")

Solamente municipios conurbados del AMP

ggplot()+
  geom_sf(data=filter(municipios, CONURB=="AMP"), aes(fill=POBTOT/SUPKM2))

ggplot(municipios %>% filter(CONURB=="AMP"))+
  geom_sf(aes(fill=DENSIDAD), color="white")+
  geom_sf_text(data=filter(municipios, CONURB=="AMP"), aes(label=NOMGEO), size=3)+
    labs(title = "Densidad de Población",
         subtitle = "Área metropolitana de Puebla",
         fill = "Población/km2",
         caption= "Fuente: Censo General de Población y Vivienda, INEGI, 2020") +
  scale_fill_viridis_c(option = "plasma", direction=-1) +
  theme_light()

Descarga de Base de datos DENUE (Directorio Estadístico Nacional de Unidades Económicas) de INEGI, del estado de Puebla

denuePue <- read.csv("trabajofinal/denue_inegi_21_.csv", fileEncoding = "latin1")

head(denuePue)
##        id                         clee
## 1 8149429 21158112512000031000000000U5
## 2 6176289 21053114119000052011000000O6
## 3 8983312 21180112512000091000000000U3
## 4 6176457 21058112512000031001000000U7
## 5 9303989 21065112512000021000000000U2
## 6 6468857 21156493130000031010000000S9
##                                                        nom_estab
## 1                           CRIA DE PECES EN ESTANQUE SIN NOMBRE
## 2 ACUACULTURA Y PESCA SUSTENTABLE DE CHIGNAHUAPAN SC DE RL DE CV
## 3                                                 ACUAPONIA KAJE
## 4                                                 ACUARIO MARLIN
## 5                           AQUA PONIA BIO-THERS S DE P R DE R L
## 6                                           AVICOLA 20 MAGDALENA
##                                                       raz_social codigo_act
## 1                                                                    112512
## 2 ACUACULTURA Y PESCA SUSTENTABLE DE CHIGNAHUAPAN SC DE RL DE CV     114119
## 3                                                                    112512
## 4                                                                    112512
## 5                               GRANJA DE TILAPIAS S DE RL DE CV     112512
## 6                                          GRANJAS OJAI SA DE CV     112312
##                                                        nombre_act
## 1        Piscicultura y otra acuicultura, excepto camaronicultura
## 2 Pesca y captura de peces, crustáceos, moluscos y otras especies
## 3        Piscicultura y otra acuicultura, excepto camaronicultura
## 4        Piscicultura y otra acuicultura, excepto camaronicultura
## 5        Piscicultura y otra acuicultura, excepto camaronicultura
## 6  Explotación de gallinas para la producción de huevo para plato
##           per_ocu tipo_vial         nom_vial tipo_v_e_1          nom_v_e_1
## 1  0 a 5 personas     CALLE       SANTA ROSA      CALLE            NINGUNO
## 2  0 a 5 personas     CALLE PUENTE EL VIVERO      CALLE PASEO DE LA LAGUNA
## 3  0 a 5 personas     CALLE 16 DE SEPTIEMBRE      CALLE  Mariano Matamoros
## 4 6 a 10 personas     CALLE           17 SUR    AVENIDA         2 PONIENTE
## 5  0 a 5 personas     CALLE        8 ORIENTE      CALLE            8 NORTE
## 6  0 a 5 personas     CALLE          NINGUNO                              
##           tipo_v_e_2   nom_v_e_2 tipo_v_e_3  nom_v_e_3 numero_ext letra_ext
## 1              CALLE C. San Jose      CALLE    NINGUNO          0        SN
## 2              CALLE     NINGUNO      CALLE    NINGUNO         NA        SN
## 3 OTRO (ESPECIFIQUE)     Cultivo      CALLE CUAUHTÉMOC         21          
## 4              CALLE      17 SUR      CALLE     19 SUR          0        SN
## 5            PRIVADA     NINGUNO      CALLE      PLAYA         NA        SN
## 6                                                              NA          
##   edificio edificio_e numero_int letra_int tipo_asent              nomb_asent
## 1                  NA          0              COLONIA              SANTA ROSA
## 2                  NA         NA        SN     BARRIO TEOCONCHILA O EL VIVERO
## 3                  NA          0               PUEBLO      GUADALUPE ZARAGOZA
## 4                  NA         NA              SECCION  UNIDAD PRIMERA SECCION
## 5                  NA         NA               BARRIO           LA SANTA CRUZ
## 6                  NA         NA        SN  LOCALIDAD     SAN ANTONIO TECOLCO
##          tipoCenCom         nom_CenCom num_local cod_postal cve_ent entidad
## 1                                                     73505      21  PUEBLA
## 2                                                     73300      21  PUEBLA
## 3 OTRO CONGLOMERADO GUADALUPE ZARAGOZA         0      74104      21  PUEBLA
## 4                                                     75070      21  PUEBLA
## 5                                                     75170      21  PUEBLA
## 6                                                     75700      21  PUEBLA
##   cve_mun              municipio cve_loc              localidad ageb manzana
## 1     158             Tenampulco       7              El Chacal 0012      16
## 2      53           Chignahuapan      92      Ixtlahuaca Barrio 0491      54
## 3     180              Tlahuapan       5     Guadalupe Zaragoza 0225      24
## 4      58             Chilchotla       1       Rafael J. García 0106       3
## 5      65 General Felipe Ángeles       1 San Pablo de las Tunas 0098      31
## 6     156               Tehuacán       1               Tehuacán 1088       6
##     telefono                          correoelec www tipoUniEco  latitud
## 1                                                          Fijo 20.22534
## 2            PESCATRUCHACHIGNAHUAPAN@HOTMAIL.COM           Fijo 19.84630
## 3 2482284344                                               Fijo 19.36173
## 4                                                          Fijo 19.25274
## 5                                                          Fijo 18.99485
## 6                GILBERTO.GONZALEZ@GRUPOOJAI.COM           Fijo 18.44992
##    longitud fecha_alta
## 1 -97.45497    2019-11
## 2 -98.01650    2014-12
## 3 -98.54009    2019-11
## 4 -97.19324    2010-07
## 5 -97.70194    2020-11
## 6 -97.40067    2014-12
#summary(denuePue)

Filtro sólo de escuelas

escuelasEdo <- denuePue %>%
  filter(codigo_act %in% c("611111", "611112", "611121", "611122", "611131", "611132", "611142", "611161", "611162", "611171", "611172", "611181", "611182", "611311", "611312", "611411", "611421", "611511", "611512", "611611", "611621", "611622", "611631")) 
bbox <- make_bbox(escuelasEdo$longitud, escuelasEdo$latitud)

mapa_base1 <- get_stamenmap(bbox = bbox,
                           maptype = "toner-lite",
                           zoom = 8)
escuelasEdo <- escuelasEdo %>%
  mutate(tipoe = case_when(
                        str_detect(nombre_act,"sector público") ~ "pública",
                        str_detect(nombre_act, "sector privado") ~ "privada")) %>%
  mutate(nivele = case_when(
                        str_detect(nombre_act,"preescolar") ~ "preescolar",
                        str_detect(nombre_act,"primaria") ~ "primaria",
                        str_detect(nombre_act,"secundaria") ~ "secundaria",
                        str_detect(nombre_act,"media superior") ~ "media superior",
                        str_detect(nombre_act,"superior ") ~ "superior",
                        str_detect(nombre_act,"combinan") ~ "varios")) %>%
  mutate(nivele = replace_na(nivele, "otros"))

Mapeo de escuelas por tipo de escuela

ggmap(mapa_base1) +
   geom_point(data = escuelasEdo, aes(x = longitud, y = latitud, color=tipoe), alpha=0.8)

Mapeo de escuelas por nivel de escolaridad

ggmap(mapa_base1) +
    geom_point(data = escuelasEdo, aes(x = longitud, y = latitud, color=nivele), alpha=0.6)+
     facet_wrap(~tipoe)

Mapeo de densidad de escuelas

ggmap(mapa_base1) +
    geom_bin2d(data = escuelasEdo, 
               aes(x = longitud, y = latitud), bins=25)+
  scale_fill_viridis_c(option = "magma", direction=-1)

Mapeo por nivel de escolaridad

ggmap(mapa_base1) +
    geom_bin2d(data = escuelasEdo %>% filter(nivele %in% c("preescolar","primaria","secundaria","media superior")), 
               aes(x = longitud, y = latitud), bins=30)+
  scale_fill_viridis_c(direction=-1)+
  facet_wrap(~nivele)

escuelasEdo1 <- escuelasEdo %>%
  mutate(fecha=ym(fecha_alta)) %>%
  mutate(mes=month(fecha, label = TRUE)) %>%
  mutate(anno=year(fecha))

Mapeo por año de creación

ggmap(mapa_base1) +
    geom_bin2d(data = escuelasEdo1, 
               aes(x = longitud, y = latitud))+
  facet_wrap(~anno)

ggmap(mapa_base1) +
  stat_density_2d(data = escuelasEdo1, 
                  aes(x = longitud, y = latitud, 
                      fill = stat(level)), geom = "polygon") +
  labs(title="Densidad de escuelas en el estado de Puebla",
       caption= "Fuente: DENUE INEGI, 2021")+
  theme_void()+
  scale_fill_distiller(palette = "Spectral")

Filtro de Cadena de tiendas Oxxos, cadena comercial de minisuper

oxxos <- denuePue %>%
  filter(raz_social == "CADENA COMERCIAL OXXO SA DE CV")

# Solamente una forma para conocer en qué municipios hay más Oxxos
tabla1 <- oxxos %>%
  count(cve_mun, municipio)

Filtro de Oxxos que se localizan en el AMP

oxxosamp <- oxxos %>%
  filter(cve_mun %in% c(15,34,40,41,74,90,106,114,119,140))

Filtro de municipios del AMP

mpiosamp <- municipios %>%
  filter(CONURB=="AMP")
ggplot()+
  geom_sf(data=mpiosamp)+
  geom_point(data=oxxosamp, aes(x=longitud, y=latitud))

mpiosamp <- st_transform(mpiosamp, crs = 4326) #transformación de CRS porque no coincidían
ggplot()+
  geom_sf(data=mpiosamp)+
  geom_point(data=oxxosamp, aes(x=longitud, y=latitud))

oxxos_geo <- oxxosamp %>%
  st_as_sf(coords = c("longitud", "latitud"), crs = 4326)
ggplot()+
  geom_sf(data=mpiosamp)+
  geom_sf(data=oxxos_geo, aes(color=tipo_vial))

#Guardar archivo espacial

#st_write(oxxos_geo, "oxxos_geo.geojson")
oxxos_geook <- st_join(oxxos_geo, mpiosamp)

#Quitar leyenda

ggplot()+
  geom_sf(data=mpiosamp)+
  geom_sf(data=oxxos_geook, aes(color=municipio), show.legend = FALSE)

Ver en qué municipio hay más oxxos

tabla2 <- oxxos_geook %>%
  group_by(municipio) %>%
  summarise(cantidad=n())

#Sacar geometría y calcular densidad de tiendas Oxxo por superficie

tablaoxxos <- oxxos_geook %>%
  group_by(cve_mun) %>%
  summarise(n_oxxo=n()) %>%
  st_set_geometry(NULL) %>%
  rename(MUN=cve_mun)
mpiosamp <- left_join(mpiosamp, tablaoxxos, by="MUN")
ggplot()+
  geom_sf(data=mpiosamp, aes(fill=n_oxxo/SUPKM2))+
  scale_fill_viridis_c(direction=-1)

ggplot()+
  geom_sf(data=mpiosamp, aes(fill=n_oxxo/SUPKM2))+
  scale_fill_viridis_c(direction=-1)

Agebs con más oxxos en e municipio de Puebla

Cargar capa json por ageb

agebs <- st_read("trabajofinal/AgebsAMP.geojson")
## Reading layer `AgebsAMP' from data source 
##   `C:\Users\711167\OneDrive\00-R\Geo\trabajofinal\AgebsAMP.geojson' 
##   using driver `GeoJSON'
## Simple feature collection with 867 features and 243 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: 2866479 ymin: 771095.7 xmax: 2920101 ymax: 813967.2
## Projected CRS: Mexico ITRF2008 / LCC
agebs <- st_transform(agebs, crs = 4326) #transformación de CRS porque no coincidían
tablaoxxos2 <- oxxos_geo2 %>%
  group_by(CVEGEO) %>%
  summarise(n_oxxos=n()) %>%
  st_set_geometry(NULL)
agebs <- left_join(agebs, tablaoxxos2, by="CVEGEO")

#head(agebs)
ggplot()+
  geom_sf(data=agebs, aes(fill=n_oxxos))+
  scale_fill_viridis_c(direction=-1)

Agebs con más oxxos en los municipios de Ocoyucan, Puebla y San Andrés Cholula

ggplot()+
  geom_sf(data=agebs %>%
            filter(CVE_MUN %in% c("106","114","119")), aes(fill=n_oxxos))+
  scale_fill_viridis_c(option = "plasma", direction=-1)

Agebs con más oxxos en el municipio de San Andrés Cholula

ggplot()+
  geom_sf(data=agebs %>%
            filter(CVE_MUN == "119"), aes(fill=n_oxxos))+
  scale_fill_viridis_c(option = "plasma", direction=-1)

Análisis de principales datos sociodemográficos de la zona Lomas de Angelópolis-Valle del paraíso, del área metropolitana de Puebla que involucra tres municipios: Ocoyucan, Puebla y San Andrés Cholula, por agebs.

Contempla algunos agebs que están en la base del Censo 2020, excepto la zona de Lomas de Angelópolis que corresponde al municipio de Ocoyucan

tresmpios <- municipios %>%
  filter(CVE_MUN.x %in% c("106","114","119"))

Puebla: 2111400015682, 2111400015945, 2111400012029, 2111400014716, 2111400014720, 2111400015447, 2111400012033, 2111400016089, 2111400016093, 2111400015080, 2111400015767, 2111400015752, 2111400015748, 2111400015432, 2111400011957, 2111400011961, 2111400011976, 2111400014186, 2111400014167, 2111400014152, 2111400014148, 2111400014650, 2111400015023, 2111400011980, 2111400011995, 2111400015593, 2111400015413, 2111400016271, 211140001645A, 2111400016337, 2111400015589, 2111400016267, 2111400015428, 211140001613A, 2111400016125, 2111400015574, 2111400016322, 2111400016182, 2111400016394, 211140001638A

Cholula: 2111900130546, 2111900130531, 2111900130565, 2111900130550, 2111900130495, 2111900130480, 2111900130508

Ocoyucan: 2110600420016, 2110600420035, 2110600420177, 2110600420181, 2110600420196, 2110600420209, 2110600420213, 2110600420266, 2110600420228, 2110600420251, 2110600420232, 2110600420247, 2110600420270, 2110600420355, 2110600420285, 2110600420302, 2110600420317, 211060042029A, 2110600420336, 2110600420321, 2110600420336, 2110600420340

Selección de agebs de la zona

agebszona <- agebs %>%
  filter(CVEGEO %in% c("2111400015682", "2111400015945", "2111400012029", "2111400014716", "2111400014720", "2111400015447", "2111400012033", "2111400016089", "2111400016093", "2111400015080", "2111400015767", "2111400015752", "2111400015748", "2111400015432", "2111400011957", "2111400011961", "2111400011976", "2111400014186", "2111400014167", "2111400014152", "2111400014148", "2111400014650", "2111400015023", "2111400011980", "2111400011995", "2111400015593", "2111400015413", "2111400016271", "211140001645A", "2111400016337", "2111400015589", "2111400016267", "2111400015428", "211140001613A", "2111400016125", "2111400015574", "2111400016322", "2111400016182", "2111400016394", "211140001638A", "2111900130546", "2111900130531", "2111900130565", "2111900130550", "2111900130495", "2111900130480", "2111900130508", "2110600420016", "2110600420035", "2110600420177", "2110600420181", "2110600420196", "2110600420209", "2110600420213", "2110600420266", "2110600420228", "2110600420251", "2110600420232", "2110600420247", "2110600420270", "2110600420355", "2110600420285", "2110600420302", "2110600420317", "211060042029A", "2110600420336","2110600420321", "2110600420336", "2110600420340"))

Mapa de localización

ggplot()+
  geom_sf(data=tresmpios)+
  geom_sf(data=agebszona, aes(fill=NOM_MUN))+
  geom_sf_text(data=tresmpios, aes(label=NOM_MUN), size=3)+
  labs(title = "Localización zona de estudio (agebs)",
         subtitle = "Lomas de Angelópolis y Valle del Paraíso",
         fill = "Municipio",
         caption= "Fuente: Censo General de Población y Vivienda, INEGI, 2020") +
  theme_light()

ggplot()+
  geom_sf(data=agebszona, aes(fill=POBTOT))+
  scale_fill_distiller(palette = "Spectral", direction=-1)+
  labs(title = "Lomas de Angelópolis y Valle del Paraíso (por ageb)",
         fill = "No. habitantes",
         caption= "Fuente: Censo General de Población y Vivienda, INEGI, 2020") +
  theme_light()

## Análisis temporal de Unidades Económicas del estado de Puebla
r denue_geo <- denuePue %>% st_as_sf(coords = c("longitud", "latitud"), crs = 4326)
r join_espacial <- st_join(denue_geo, agebszona)
```r denuezona <- join_espacial %>% filter(!is.na(CVEGEO))
denue3m <- denue_geo %>% filter(cve_mun %in% c(“106”, “114”, “119”)) ```
```r #denuetemp <- denue3m %>% # mutate(fecha=ym(fecha_alta))
#str(denuetemp) ```
r rm(tabladenue)
## Warning in rm(tabladenue): objeto 'tabladenue' no encontrado
r tabladenue <- denue3m %>% count(codigo_act, nombre_act, municipio, fecha_alta)%>% mutate(fecha=ym(fecha_alta))
### ¿Cuándo se han generado más unidades económicas en la zona?
r ggplot(tabladenue %>% group_by(fecha) %>% summarise(cantidad=n())) + geom_line(aes(x = fecha, y = cantidad))
### ¿En qué mes se crearon más unidades económicas en la zona?
```r tabladenue1 <- tabladenue %>% mutate(mes=month(fecha, label = TRUE)) %>% mutate(dia_semana=wday(fecha, label = TRUE))
head(tabladenue1) ```
## Simple feature collection with 6 features and 8 fields ## Geometry type: GEOMETRY ## Dimension: XY ## Bounding box: xmin: -98.25541 ymin: 18.90584 xmax: -98.11342 ymax: 19.1065 ## Geodetic CRS: WGS 84 ## codigo_act nombre_act ## 1 112512 Piscicultura y otra acuicultura, excepto camaronicultura ## 2 114119 Pesca y captura de peces, crustáceos, moluscos y otras especies ## 3 115111 Servicios de fumigación agrícola ## 4 115113 Beneficio de productos agrícolas ## 5 115119 Otros servicios relacionados con la agricultura ## 6 212311 Minería de piedra caliza ## municipio fecha_alta n geometry fecha mes ## 1 Puebla 2019-11 3 MULTIPOINT ((-98.24195 18.9... 2019-11-01 nov ## 2 Puebla 2014-12 7 MULTIPOINT ((-98.11342 18.9... 2014-12-01 dic ## 3 Puebla 2019-11 2 MULTIPOINT ((-98.22886 19.0... 2019-11-01 nov ## 4 Puebla 2014-12 1 POINT (-98.18231 19.09027) 2014-12-01 dic ## 5 Puebla 2014-12 2 MULTIPOINT ((-98.20117 19.0... 2014-12-01 dic ## 6 Puebla 2010-07 1 POINT (-98.20762 19.1065) 2010-07-01 jul ## dia_semana ## 1 vie\\. ## 2 lun\\. ## 3 vie\\. ## 4 lun\\. ## 5 lun\\. ## 6 jue\\.
r ggplot(tabladenue1) + geom_bar(aes(x = mes))
r ggplot(tabladenue1) + geom_bar(aes(x = mes, fill=municipio)) + labs(title = "Cantidad de Unidades Económicas creadas por mes", subtitle = "Puebla y San Andrés Cholula", x = "Mes", y = "Cantidad", fill = "Municipio", caption = "Fuente: DENUE INEGI 2021")
r ggplot(tabladenue1 %>% group_by(municipio, dia_semana) %>% summarise(cantidad=n())) + geom_line(aes(x = dia_semana, y=cantidad, group = municipio, color = municipio), size=1) + geom_point(aes(x = dia_semana, y=cantidad, color = municipio), size=2)+ geom_text(aes(x = dia_semana, y=cantidad+100, label=cantidad), size=2)+ labs(title = "Cantidad de Unidades Económicas creadas por día de la semana", subtitle = "Puebla y San Andrés Cholula", x = "Día de la Semana", y = "Cantidad", color = "Municipio", caption = "Fuente: DENUE INEGI 2021")
## `summarise()` has grouped output by 'municipio'. You can override using the `.groups` argument.
r ggplot()+ geom_sf(data=agebszona, aes())+ geom_sf(data=denuezona, aes())+ labs(title = "DENUE Lomas de Angelópolis y Valle del Paraíso", caption= "Fuente: CGPyV, INEGI, 2020 y DENUE, INEGI 2021") + theme(legend.position="none")
```r coord <- denuezona %>% select(1:8, 48, 285)
coord <- coord %>% mutate(Geom = gsub(‘[()°]’, ’‘, geometry)) %>% separate(col = Geom, into = c(’latitude’, ‘longitud’), sep = ‘\,’) %>% mutate(latitud = substr(latitude, start = 2, stop = 13)) %>% mutate(latitud = as.numeric(latitud))%>% mutate(longitud = as.numeric(longitud)) ```
r ggplot()+ geom_sf(data=agebszona, aes())+ geom_sf(data=coord, aes(color=per_ocu))+ labs(title = "DENUE Lomas de Angelópolis y Valle del Paraíso", caption= "Fuente: CGPyV, INEGI, 2020 y DENUE, INEGI 2021") + theme(legend.position="none")

Análisis de cantidad y tipo de escuelas que existen en la zona

escuelas <- denuezona %>%
  filter(codigo_act %in% c("611111", "611112", "611121", "611122", "611131", "611132", "611142", "611161", "611162", "611171", "611172", "611181", "611182", "611311", "611312", "611411", "611421", "611511", "611512", "611611", "611621", "611622", "611631")) %>%
  select(1:50,285)
ggplot()+
  geom_sf(data=agebszona, aes())+
  geom_sf(data=escuelas, aes(fill=codigo_act))+
  labs(title = "Escuelas en Lomas de Angelópolis y Valle del Paraíso",
         caption= "Fuente: CGPyV, INEGI, 2020 y DENUE, INEGI 2021") +
  theme(legend.position="none")

### conversión de geometry a latitud y longitud para escuelas y categorización en nivel de escolaridad y tipo de escuela (pública o privada)

escuelas <- escuelas %>%
  mutate(tipoe = case_when(
                        str_detect(nombre_act,"sector público") ~ "pública",
                        str_detect(nombre_act, "sector privado") ~ "privada")) %>%
  mutate(nivele = case_when(
                        str_detect(nombre_act,"preescolar") ~ "preescolar",
                        str_detect(nombre_act,"primaria") ~ "primaria",
                        str_detect(nombre_act,"secundaria") ~ "secundaria",
                        str_detect(nombre_act,"media superior") ~ "media superior",
                        str_detect(nombre_act,"superior ") ~ "superior",
                        str_detect(nombre_act,"combinan") ~ "varios")) %>%
  mutate(nivele = replace_na(nivele, "otros"))
coordesc <- escuelas %>% 
  mutate(Geom = gsub('[()°]', '', geometry)) %>% 
  separate(col = Geom, into = c('latitude', 'longitud'), sep = '\\,') %>% 
  mutate(latitud = substr(latitude, start = 2, stop = 13)) %>% 
  mutate(latitud = as.numeric(latitud))%>% 
  mutate(longitud = as.numeric(longitud)) %>%
  select(-53) %>%
  select(1:54)
ggplot()+
  geom_sf(data=agebszona, aes())+
  geom_sf(data=escuelas, aes(color=tipoe), size = 2)+
  labs(title = "Escuelas en Lomas de Angelópolis y Valle del Paraíso",
       color = "Tipo de escuela",
         caption= "Fuente: CGPyV, INEGI, 2020 y DENUE, INEGI 2021")

Agregar mapa base

bbox_LA <- getbb("Lomas de Angelópolis, Ocoyucan, Puebla, México")
#bbox1 <- make_bbox(coordenadas$longitud, coordenadas$latitud)
mapa_LA <- get_stamenmap(bbox=bbox_LA,
                                  zoom=12)
polygon_lomasang <- getbb("Lomas de Angelópolis, Ocoyucan, Puebla, México",
                          format_out = "sf_polygon")
ggmap(mapa_LA)+
  geom_sf(data=agebszona, fill=NA, color="blue", inherit.aes = FALSE)+
  geom_sf(data=escuelas, aes(color=nivele), inherit.aes = FALSE)+
  geom_sf(data=polygon_lomasang, fill=NA, size=1, color="firebrick3", inherit.aes = FALSE)+
  labs(title = "Escuelas en Lomas de Angelópolis y Valle del Paraíso",
       color = "Nivel escolar",
         caption= "Fuente: CGPyV, INEGI, 2020 y DENUE, INEGI 2021") +
  theme(plot.title = element_text(hjust = 0.5))
## Coordinate system already present. Adding new coordinate system, which will replace the existing one.


Mapa interactivo

leaflet(escuelas) %>%
  addTiles() %>%
  addMarkers()
leaflet(escuelas) %>%
  addTiles() %>%
  addMarkers(clusterOptions = markerClusterOptions(),
             popup = paste("Tipo:", escuelas$tipoe, "<br>",
                           "Nivel:", escuelas$nivele))
#escuelas$tipoe <- escuelas$tipoe %>%
  #        filter(!is.na(name), !is.na(amenity))
rm(factpal)
## Warning in rm(factpal): objeto 'factpal' no encontrado
factpal <- colorFactor(palette = c("seagreen4","deeppink4"), 
               levels = escuelas$tipoe)
## Warning in colorFactor(palette = c("seagreen4", "deeppink4"), levels =
## escuelas$tipoe): Duplicate levels detected
leaflet(escuelas) %>%
  addTiles() %>%
  addCircleMarkers(popup = paste("Tipo:", escuelas$tipoe, "<br>",
                           "Nombre:", escuelas$nivele),
             color = ~factpal(tipoe))%>%
  addLegend("bottomright", pal = factpal, values = ~tipoe,
            title = "Tipo",
            opacity = 1)
factores <- colorFactor(palette = "spectral", 
               levels = escuelas$codigo_act)
## Warning in colorFactor(palette = "spectral", levels = escuelas$codigo_act):
## Duplicate levels detected
leaflet(escuelas) %>%
  addTiles() %>%
  addCircleMarkers(popup = paste("Código:", escuelas$codigo_act, "<br>",
                           "Nombre:", escuelas$nombre_act),
             color = ~factores(codigo_act))%>%
  addLegend("bottomright", pal = factores, values = ~codigo_act,
            title = "Código actividad",
            opacity = 1)