Gráficas. Número de homicidios por estado entre 1990 y 2018, de acuerdo con datos del INEGI

Como ahora dedico más tiempo a discutir de temas de política, entre ellos la violencia en México, decidí hacer un blog en el que puedo poner información accesible para que tanto yo, como otras personas podamos usarlas como argumento en nuestras discusiones y ahorrarnos tiempo. El primer dato que se me ocurrió fue el número de homicidios por entidad federativa.
 

 
 

 
 

 
 

 
 

 

 
 

 

 
 

 


 

 

 
 

 
 
Consulté la página de internet del INEGI el 13 de septiembre del 2020.
 
Supporting information.
Elegí la opción de "Entidad y municipio de ocurrencia" y descagué los datos en formato xls.
Eliminé los datos de homicidios que no especificaban el estado donde ocurrieron, así como el encabezado de la tabla y las secciones que no contenían información acerca del número de homicidos.
Los nombres de los estados no contenían vocales con acentos (en su lugar, contenían otro caracter), así que los sustituí por la vocal correspondiente sin acento.

Después lo guardé como un archivo CSV e hice las gráficas con R.

Aquí está el código que usé. Lo había usado en el pasado, así que solamente lo copié y lo adapté. Como casi todo ya estaba explicado en inglés, pues dejé todo en inglés. 

 

# 1. Script description---------------------------------------------------------

#I pretend to make a set of plots that describe the insecurity scenario in
#Mexico, as well as how it has changed depending on the local government.
#To do so, I want to automatize the generation of the plots (since there are 32
#states in Mexico).
#One of the two main sources of information about the number of homicides in
#Mexico is the INEGI:
# https://www.inegi.org.mx/sistemas/olap/proyectos/bd/continuas/mortalidad/defuncioneshom.asp?s=est

# 2. Setup ---------------------------------------------------------------------
#First I clean the environment, so I know that this program can run from zero.
rm(list=ls())

#Now I define the libraries that I'll be using. I will be changing this from
#time to time.
library(plotly)

# 3. Imput information ------------------------------------------------------------

#I dowloaded the data in my personal folder. In fact, I downloaded the data
#and then I eliminated some rows to make it fit in a rectangular table.
#Path of the file:
path = "C:\\Users\\Juan\\Documents\\La4Times\\200909-AMLODelincuencia\\"
fileName = "INEGI_Exporta_20200913023405.csv"
pathFile = paste0(path, fileName)

#NOrnmally, I like to give a name to the first data set I make in an R file.
#That's what rawFile is. It's the table containing the raw information.
rawFile <- read.table(pathFile, sep = ';' , header = FALSE)

#raW File has some defects that should be corrected so we can use it.
#The first row must be the header.
headers <- rawFile[1,]
resultsTable <- rawFile[2:nrow(rawFile),]
colnames(resultsTable) <- headers
#Now I have a nice table called resultsTable

# 4. We get the information ready for the plots---------------------------------

# How the text should look like.
fontPlotTitle <- list(
  family = "Helvetica",
  size = 20,
  color = "black"
)

fontTitle <- list(
  family = "Helvetica",
  size = 25,
  color = "black"
)

fontTics <- list(
  family = "Helvetica",
  size = 20,
  color = "black"
)

margin <- list(
  l = 150,
  r = 80,
  b = 0,
  t = 200,
  pad = 0
)

#The names of each state are defined. I recicle this information from the
# "header" vector.
statesNames <- headers[3:(length(headers))]


# 5. Plotting-------------------------------------------------------------------
#Actually, I try to plot as many plots as possible. I made this for loop so I
#don't have to code how to plot each one.
for (i in 1:16){
  plotTitle <- paste0('Número de homicidios en el estado de<br>',
                      statesNames[i],
                      ' entre 1990 y 2018,<br>de acuerdo con datos del INEGI.')
 
 
  p <- plot_ly()
 
  p <- add_lines(p,
                 x= ~as.numeric(resultsTable[,1]),
                 y= ~as.numeric(resultsTable[,2+i]),
                 fill = 'tozeroy'
  )
 
  p <- layout(p,
              title = plotTitle,
              font = fontPlotTitle,
              xaxis = list(range = c(1990,2019),
                           title = 'Año',
                           dtick = 5,
                           tickmode = "linear",
                           titlefont = fontTitle,
                           tickfont = fontTics,
                           showline = TRUE,
                           gridcolor = toRGB("gray80"),
                           gridwidth = 2,
                           linecolor = toRGB("black"),
                           mirror = "ticks"
              ),
              
              yaxis = list(range = c(0,6500),
                           title ='Número de homicidios',
                           dtick = 500,
                           tickmode = "linear",
                           titlefont = fontTitle,
                           tickfont = fontTics,
                           showline = TRUE,
                           gridcolor = toRGB("gray80"),
                           gridwidth = 2,
                           linecolor = toRGB("black"),
                           mirror = "ticks"
              ),
              margin = margin,
              showlegend = FALSE
  )
 
 
 
  print(p)
 
}

#My computer (or R, i don't know) cannot keep more than ~20 plots in the memory,
#so, I have to stop here and export the first 16 plots manually, and then go on
#with the second half.

for (i in 17:32){
  plotTitle <- paste0('Número de homicidios en el estado de<br>', statesNames[i],' entre 1990 y 2018,<br>de acuerdo con datos del INEGI.')
 
 
  p <- plot_ly()
 
  p <- add_lines(p,
                 x= ~as.numeric(resultsTable[,1]),
                 y= ~as.numeric(resultsTable[,2+i]),
                 fill = 'tozeroy'
  )
 
  p <- layout(p,
              title = plotTitle,
              font = fontPlotTitle,
              xaxis = list(range = c(1990,2019),
                           title = 'Año',
                           dtick = 5,
                           tickmode = "linear",
                           titlefont = fontTitle,
                           tickfont = fontTics,
                           showline = TRUE,
                           gridcolor = toRGB("gray80"),
                           gridwidth = 2,
                           linecolor = toRGB("black"),
                           mirror = "ticks"
              ),
              
              yaxis = list(range = c(0,6500),
                           title ='Número de homicidios',
                           dtick = 500,
                           tickmode = "linear",
                           titlefont = fontTitle,
                           tickfont = fontTics,
                           showline = TRUE,
                           gridcolor = toRGB("gray80"),
                           gridwidth = 2,
                           linecolor = toRGB("black"),
                           mirror = "ticks"
              ),
              margin = margin,
              showlegend = FALSE
  )
 
 

 
  print(p)
 
}

 


Comments

Popular posts from this blog