Este cuaderno visualiza la abstención en elecciones generales 2000-2019

Cargar librerĆ­as

if (!"tidyverse" %in% installed.packages()) {install.packages("tidyverse")}
if (!"lubridate" %in% installed.packages()) {install.packages("lubridate")}
if (!"readxl" %in% installed.packages()) {install.packages("readxl")}
if (!"mapSpain" %in% installed.packages()) {install.packages("mapSpain")}
if (!"sf" %in% installed.packages()) {install.packages("sf")}
if (!"ggthemes" %in% installed.packages()) {install.packages("ggthemes")}
if (!"gganimate" %in% installed.packages()) {install.packages("gganimate")} 
if (!"purrr" %in% installed.packages()) {install.packages("purrr")} 
if (!"animation" %in% installed.packages()) {install.packages("animation")} 
if (!"magick" %in% installed.packages()) {install.packages("magick")} 
library(tidyverse)
library(lubridate)
library(readxl)
library(mapSpain)
library(sf)
library(ggthemes)    # Temas
library(purrr)
library(animation)
library(magick)
locale(date_names = "es", date_format = "%AD", time_format = "%AT",
  decimal_mark = ",", grouping_mark = ".", tz = "Europe/Berlin",
  encoding = "UTF-8", asciify = FALSE)
## <locale>
## Numbers:  123.456,78
## Formats:  %AD / %AT
## Timezone: Europe/Berlin
## Encoding: UTF-8
## <date_names>
## Days:   domingo (dom.), lunes (lun.), martes (mar.), miƩrcoles (miƩ.), jueves
##         (jue.), viernes (vie.), sƔbado (sƔb.)
## Months: enero (ene.), febrero (feb.), marzo (mar.), abril (abr.), mayo (may.),
##         junio (jun.), julio (jul.), agosto (ago.), septiembre (sept.),
##         octubre (oct.), noviembre (nov.), diciembre (dic.)
## AM/PM:  a. m./p. m.
Sys.setlocale(category = "LC_ALL", locale = "spanish")
## [1] "LC_COLLATE=Spanish_Spain.1252;LC_CTYPE=Spanish_Spain.1252;LC_MONETARY=Spanish_Spain.1252;LC_NUMERIC=C;LC_TIME=Spanish_Spain.1252"

Leer datos

fecha_elecciones <- c ("20-11-2019","28-04-2019","26-06-2016","20-12-2015","20-11-2011","09-03-2008","14-03-2004","12-03-2000")
ultima_eleccion <- "2019-11-20"
file_participacion = "participacion_elecciones_generales.xlsx"
primera_eleccion <- TRUE
list_abstencion_global <- list()
for (fecha_eleccion in fecha_elecciones) {
  participacion <- read_excel (file_participacion, sheet = fecha_eleccion) 
  abstencion_global <- 100 - round(sum(participacion$`Total votantes`) * 100 / sum(participacion$`Total censo electoral`),2)
  list_abstencion_global <- append(list_abstencion_global, abstencion_global)
  participacion_df <- participacion %>%
    mutate (fecha = as.Date(fecha_eleccion,"%d-%m-%Y")) %>%
    mutate (porcentaje_participacion = (`Total votantes` * 100) / `Total censo electoral`) %>%
    mutate (abstencion = 100 - porcentaje_participacion) %>%
    mutate (year = as.numeric(year(fecha))) %>%
    mutate(color_text = ifelse(abstencion > abstencion_global, "alta","baja")) 
  if (primera_eleccion){
    participacion_by_year_df <- participacion_df
    primera_eleccion <- FALSE
  }else{participacion_by_year_df <- rbind(participacion_by_year_df, participacion_df)}
}
min_abstencion <- min (participacion_by_year_df$abstencion)
max_abstencion <- max (participacion_by_year_df$abstencion)

Abstención por provincia

mapSpain_prov <- esp_get_prov() %>%
  mutate(cpro = as.numeric (cpro)) 
map_provincias_abstencion <-left_join (mapSpain_prov,participacion_by_year_df, by = c("cpro"="Código de Provincia" ))
Can <- esp_get_can_box()
num_frames <- length(unique (map_provincias_abstencion$fecha)) 
i<- 0
for (fecha_eleccion in fecha_elecciones) {
  i <- i + 1 
  p <- ggplot(data = map_provincias_abstencion  %>% filter (fecha == as.Date(fecha_eleccion,"%d-%m-%Y"))) + 
    geom_sf(
      aes(fill = abstencion),
      color = "grey80"
    ) + 
    geom_sf(data = Can, color = "grey70") +
    geom_sf_label (
      aes(
        label = round(abstencion,1),
        fill = abstencion,
        color = color_text
      ),
      show.legend = FALSE,
      stat = "sf_coordinates",
      size = 2,
      label.padding = unit(0.12, "lines"),
      label.size = 0,
    ) +
    scale_fill_gradient (
      low = "#D6D2D2",high = "#7A7878",
      aesthetics = "fill" ,
      guide = guide_legend(),
      breaks = c(seq(20,60, by = 10))
    ) +
    scale_colour_manual('', values = c('alta'='#FFFFFF', 'baja'='grey40')) +
    labs(
      title = paste0 ("Abstención elecciones generales ", format(as.Date(fecha_eleccion,"%d-%m-%Y"),"%Y-%B")),
      subtitle = paste0("Abstención global ", list_abstencion_global[i],"%"),
       x = "",
       y = "",
       fill = "% Abstención",
       caption = "by @congosto\nFuentes: https://infoelectoral.interior.gob.es/"
     ) +
    #guides(fill = guide_colourbar(nbin = 5),color = "none" +
    guides(color = "none") +
    theme_void() +
    theme (
      legend.position = c(0.1, 0.6),
      title = element_text(color  = "grey50", size = 10),
      plot.subtitle = element_text(color  = "grey50", size = 8),
      legend.text =  element_text(color  = "grey50", size = 6),
      legend.key.height = unit(0.6, "cm")
     )
  if (fecha_eleccion == fecha_elecciones[1]){p + theme(panel.background = element_rect(fill = 'grey20'))}
  ggsave(paste0("generales_abstencion_",as.Date(fecha_eleccion,("%d-%m-%Y")),".png"), height=3.6, width=4.3)
}

animation <- list.files(
  path = "./",
  pattern = "*.png", full.names = T) %>% 
  map(image_read) %>%          # lee las imƔgenes del directorio
  image_join() %>%             #une las imƔgenes
  image_animate(fps = 1)        # genera la animación
for (i in 1:length(animation)){
  if (i == 1){animation_lenta <- c(rep(animation[i],1))
  }else{animation_lenta <- c(animation_lenta, rep(animation[i],1))}
}
gif_with_pause<-c(animation_lenta, rep(animation[length(animation)],5))
image_write(gif_with_pause, "mapa_abstencion_generales.gif") # la guarda en un fichero .gif

Mapa Animado

Evolución de la abstención por provincia

max_date <- max(participacion_by_year_df$fecha)
df <- participacion_by_year_df %>%
      filter (fecha  == max_date) %>%
      arrange(abstencion)
orden_provincias <- unique(df$`Nombre de Provincia`)
participacion_by_year_df$`Nombre de Provincia` <- factor(participacion_by_year_df$`Nombre de Provincia`,orden_provincias)

ggplot(
  data = participacion_by_year_df,
  aes(
    x = as.character(fecha,"%Y\n%b"),
    y = `Nombre de Provincia`,
    fill = abstencion
  )) +
  geom_tile(color = "white") +
  geom_text(
    aes(
      label = sprintf("%0.1f", round(abstencion, digits = 1)),
      color = color_text
    ),
    size =4,
    hjust=.5,
    vjust=.5 
   ) +
   scale_fill_gradient (
      low = "#D6D2D2",high = "#7A7878",
      aesthetics = "fill" ,
      guide = guide_legend(reverse = TRUE),
      breaks = c(seq(20,60, by = 10))
    ) +
  scale_x_discrete(
    expand =  c(0,0),
    position = "top"
  ) +
  scale_y_discrete(expand =  c(0,0)) +
  scale_colour_manual('', values = c('alta'='#FFFFFF', 'baja'='grey40')) +
  guides(color = "none") +
  labs(
     title = "Abstención elecciones generales ",
     x = "",
     y = "",
     fill = "% Abstención"
  ) +
  theme_light() +
  theme(
    legend.position="right",
    axis.title.y=element_blank(),
    panel.border = element_blank(),
    panel.background = element_blank(),
    legend.key.height = unit(7, "cm")
  )