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")

library(data.table)
library(readr)
library(tidyverse)
library(dplyr)
library(magrittr)
library(ggplot2)
library(sf)

Se quiere conocer la distribución de la población en el área metropolitana de Puebla, por municipio y por grupos de edad

Carga de base de datos censales del Estado de Puebla 2010 y 2020, por manzana (tipo csv)

CensoPue <- read.csv("entradas/CensoPue10_20.csv", encoding = "UTF-8")

#head(CensoPue)

#summary(CensoPue)
table(CensoPue$ALUMPUB_)
## 
##     1     2     3     4     5 
## 23140 31582  3153  1015  1367

Filtrado de datos, solamente municipios del Área Metropolitana de Puebla, por clave de municipio

CensoAMP <- CensoPue %>%
  filter(MUN %in% c("15","34","40","41","74","90","106","114","119","140","181"))
table(CensoAMP$NOM_MUN)
## 
##             Amozoc          Coronango Cuautinch<U+FFFD>n      Cuautlancingo 
##               1566                423                343               1112 
##        Huejotzingo    Juan C. Bonilla           Ocoyucan             Puebla 
##                956                257                577              17484 
## San Andr<U+FFFD>s Cholula  San Pedro Cholula        Tlaltenango 
##               1346               1159                 81
#colnames(CensoAMP)
CensoAMP_pob <- CensoAMP %>% 
  select(1, 28:36 , 76:136)

#head(CensoAMP_pob)
#str(CensoAMP_pob)

#summary(CensoAMP_pob)
class(CensoAMP_pob$X2020_POBTOT)
## [1] "integer"
CensoAMP_pob$POBTOT10 <- as.numeric(CensoAMP_pob$POBTOT)

class(CensoAMP_pob$POBTOT10)
## [1] "numeric"
CensoAMP_pob$POBTOT20 <- as.numeric(CensoAMP_pob$X2020_POBTOT)

class(CensoAMP_pob$POBTOT20)
## [1] "numeric"
CensoAMP_pob$POBFEM20 <- as.numeric(CensoAMP_pob$X2020_POBFEM)
CensoAMP_pob$POBMAS20 <- as.numeric(CensoAMP_pob$X2020_POBMAS)
#SE OCULTA SÓLO PARA EL KNIT
#CensoAMP_pob %>% 
#mutate(difpobtot10_20 = POBTOT20 + POBTOT10)

#colnames(CensoAMP_pob)

Selección de Población total de 2010 y 2020, por municipio

Graficar población total por cada municipio del AMP

tabla1 %>%
  ggplot(aes(x = NOM_MUN,y = POBTOT20/1000)) +
  geom_col(aes(fill = NOM_MUN)) +
  labs(title = "Población total por municipio",
       subtitle = "Área metropolitana de Puebla",
       x = "Municipio",
       y = "Población en millares",
       fill = "Municipio") +
    theme_gray() +
  theme(axis.text.x = element_text(size = 10, angle = 90, hjust = 1, vjust = 0.5)) +
  scale_y_continuous(labels=scales::comma)+  
  theme(legend.position = "none") 

### Graficar estadísticas de población por cada municipio del AMP

Graficar estadísticas de población por cada municipio del AMP

tabla2 %>%
  ggplot(aes(x = NOM_MUN,y = desvio)) +
  geom_col(aes(fill = NOM_MUN)) +
  labs(title = "Desviación estándar de población por municipio",
       subtitle = "Área metropolitana de Puebla",
       x = "Municipio",
       y = "Desviación",
       fill = "Municipio") +
    theme_gray() +
  theme(axis.text.x = element_text(angle = 0,  hjust = 1, vjust = 0.5)) +
  coord_flip()

tabla3 <- tabla2 %>%
  select(1,4:6) %>%
  pivot_longer(cols = c(media, mediana, desvio),
              names_to = "Estadisticos",
              values_to = "Cantidad")

colnames(tabla3)
## [1] "NOM_MUN"      "Estadisticos" "Cantidad"

Gráfica de estadísticas - opción 1

tabla3 %>% 
  ggplot() +
  geom_col(mapping = aes(x = Estadisticos, y = Cantidad, fill=Estadisticos), 
           stat = "identity",position = "dodge") +
  labs(title = paste("Estadísticas de población por municipio"), 
       subtitle = "Área metropolitana de Puebla" , 
       caption = "Fuente: Censo General de Población y Vivienda, INEGI, 2020",
       y = "",
       x = "")+
  theme(axis.text.x = element_text(angle = 0,  hjust = 0.5, vjust = 0.5)) +
  theme(legend.position = "none") +
    facet_wrap(~ NOM_MUN, ncol=3) 
## Warning: Ignoring unknown parameters: stat

### Gráfica de estadísticas - opción 2

tabla3 %>% 
  ggplot() +
  geom_bar(mapping = aes(x = NOM_MUN, y = Cantidad, fill = Estadisticos), 
           stat = "identity",position = "dodge") +
  labs(title = paste("Estadísticas de población por municipio"), 
       subtitle = "Área metropolitana de Puebla" , 
       caption = "Fuente: Censo General de Población y Vivienda, INEGI, 2020",
       y = "",
       x = "")+
  theme(axis.text.x = element_text(angle = 90,  hjust = 1, vjust = 0.5))

Selección de columnas con rangos de edad para hacer pirámide de población

Borrar columnas que tienen grupos de x edad y más

RangosEdad <- CensoAMP_pob %>% 
  select(1, starts_with("X2020_")) %>% 
  select(-contains("YMAS")) %>%
  select(-ends_with("_F"), -ends_with("_M")) %>%
  group_by(X2020_NOM_MUN)

names(RangosEdad)
##  [1] "CVEGEO"          "X2020_ENTIDAD2"  "X2020_MUN2"      "X2020_LOC2"     
##  [5] "X2020_AGEB2"     "X2020_MAN2"      "X2020_ENTIDAD"   "X2020_NOM_ENT"  
##  [9] "X2020_MUN"       "X2020_NOM_MUN"   "X2020_LOC"       "X2020_NOM_LOC"  
## [13] "X2020_AGEB"      "X2020_MZA"       "X2020_POBTOT"    "X2020_POBFEM"   
## [17] "X2020_POBMAS"    "X2020_P_0A2"     "X2020_P_3A5"     "X2020_P_6A11"   
## [21] "X2020_P_8A14"    "X2020_P_12A14"   "X2020_P_15A17"   "X2020_P_18A24"  
## [25] "X2020_POB0_14"   "X2020_POB15_64"  "X2020_POB65_MAS"
#Tabla por rangos de edad en una sola columna
RangoEdad1 <- RangosEdad %>% 
  select(X2020_NOM_MUN, X2020_MUN, X2020_POB0_14,X2020_POB15_64,X2020_POB65_MAS) %>%
  #corregir títulos
  rename(Municipio = X2020_NOM_MUN) %>%
  pivot_longer(cols=c(X2020_POB0_14,X2020_POB15_64,X2020_POB65_MAS),
    names_to = "RangoEprevio", 
    values_to = "cuenta")

tablaR <- RangoEdad1 %>% 
  count(Municipio, RangoEprevio, cuenta)
tablaR <- tablaR %>%
  mutate(RangoE = case_when(RangoEprevio == "X2020_POB0_14" ~ "0 a 14",
                             RangoEprevio == "X2020_POB15_64" ~ "15 a 64",
                             RangoEprevio == "X2020_POB65_MAS" ~ "65 y más"))

colnames(tablaR)
## [1] "Municipio"    "RangoEprevio" "cuenta"       "n"            "RangoE"

Gráfico de rangos de edad

tablaR %>% 
  ggplot() +
  geom_col(mapping = aes(x = RangoE, 
                         y = cuenta, 
                         fill=RangoE), 
                         alpha = 0.7) +
  labs(title = "Rangos de edad por municipio",
       subtitle = "Área metropolitana de Puebla, 2020",
       caption = "Fuente: Censo General de Población y Vivienda, INEGI, 2020",
       x= "Rangos de edad en años") +
    facet_wrap(facets = "Municipio",nrow = 3) +
  theme_gray() +
  theme(legend.position = "none")+
  theme(axis.line=element_blank(),
        axis.text.x=element_text(size = 9, angle = 0,  hjust = 0.5, vjust = 0.5),
        axis.text.y=element_blank(),
        axis.ticks=element_blank(),
        axis.title.y=element_blank())