Init notebook

if(!"tidyverse" %in% installed.packages()) {install.packages("tidyverse")}
if(!"RColorBrewer" %in% installed.packages()) {install.packages("RColorBrewer")}
if(!"ggsankey" %in% installed.packages()) {devtools::install_github("davidsjoberg/ggsankey")}
library("tidyverse")
library("RColorBrewer")
library("ggsankey")
mi_locale <- locale(date_names = "es", date_format = "%AD", time_format = "%AT",
  decimal_mark = ",", grouping_mark = ".", tz = "Europe/Berlin",
  encoding = "UTF-8", asciify = FALSE)
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 fichero

voto <- read_delim(
  "https://raw.githubusercontent.com/congosto/congosto.github.io/refs/heads/master/barometro_21R_2024-12.csv",
  delim = ";",
  locale = mi_locale,
  show_col_types = FALSE
)

Transferencia de votos entre partidos

color_partidos <- c("PSOE" = "#FF0000","PP" = "#09DBDE","VOX"= "#11CA08", "UPN" = "#ea515a",
                    Podemos = "#6329CF",  "ERC" = "#F2C005", "EAJ-PNV" = "#298B13", 
                    "EH-BILDU" = "#ACE155", "Junts" = "#1cc7b0", "Sumar" =  "#ff33c1",
                    "BNG" = "#85d1ed", "CCa" = "#06e7f5", "PACMA" = "#33a41e", "SALF" = "#c59112")
list_partidos <- c("PSOE","PP","VOX","Sumar","Podemos", "SALF", "ERC", "PACMA", "Junts",
                  "EAJ-PNV", "EH-BILDU", "BNG", "CCa", "UPN", "Otro partido")

# Alargar estructura de datos
voto_long <- voto %>%
  dplyr::select (-`En blanco`, -`Voto nulo`,-`Abstención`, -`No tenía edad`, -`No tenía derecho a voto`, -`N.R.`, -`N.C.`) %>%
  dplyr::filter(Voto %in% list_partidos) %>%
  tidyr::pivot_longer(cols = -c(Voto, Total), names_to = "Recuerdo_voto", values_to = "Total_recuerdo")
#  Dar forma para sankey
sankey_voto <- voto_long %>%
  make_long(source = Recuerdo_voto, target = Voto, value = Total_recuerdo) 

# Crear el diagrama de Sankey
ggplot(sankey_voto, aes(x = x, next_x = next_x, node = node, next_node = next_node, value = value, fill = factor(node))) +
  geom_sankey(
    flow.alpha = 0.5,
    node.color = "gray30",
    node.width = 20,
    space = 18) + 
  geom_sankey_label(
    aes(
      label = node, 
      fill = "white",
      hjust = dplyr::case_when(
        x == "source" ~ 1,
        x == "target" ~ 0,
        .default = .5
      )
    ),
    size = 4.5,
    color = "white",
    space = 18
  ) +
  scale_x_discrete(
    position = "top",
    labels = c("source" = "Recuerdo de voto 23J", "target" = "Intención de voto dic-2024")
  ) +
  scale_fill_manual(values = color_partidos) +
  labs(
    title = "Transferencia de votos entre los partidos",
    x = "",   
    caption = "@congosto\nFuente: CIS"
  ) +
  theme_sankey(base_size = 18) +
  theme(
    legend.position='none',
    plot.title=element_text(color = "#5a5856"),
    plot.caption = element_text(color = "#5a5856", hjust = 0)
  )

Tranferencia de voto

color_partidos <- c("PSOE" = "#FF0000","PP" = "#09DBDE","VOX"= "#11CA08", "UPN" = "#ea515a",
                    Podemos = "#6329CF",  "ERC" = "#F2C005", "EAJ-PNV" = "#298B13", 
                    "EH-BILDU" = "#ACE155", "Junts" = "#1cc7b0", "Sumar" =  "#ff33c1",
                    "BNG" = "#85d1ed", "CCa" = "#06e7f5", "PACMA" = "#33a41e", "SALF" = "#c59112")

# Alargar estructura de datos
voto_long <- voto %>%
  dplyr::select (Voto,Total,`En blanco`, `Voto nulo`,`Abstención`) %>%
  tidyr::pivot_longer(cols = -c(Voto, Total), names_to = "Recuerdo_voto", values_to = "Total_recuerdo")

#  Dar forma para sankey
sankey_voto <- voto_long %>%
  make_long(source = Recuerdo_voto, target = Voto, value = Total_recuerdo) 

# Crear el diagrama de Sankey
ggplot(sankey_voto, aes(x = x, next_x = next_x, node = node, next_node = next_node, value = value, fill = factor(node))) +
  geom_sankey(
    flow.alpha = 0.5,
    node.color = "gray30",
    node.width = 20,
    space = 18) + 
  geom_sankey_label(
    aes(
      label = node, 
      fill = "white",
      hjust = dplyr::case_when(
        x == "source" ~ 1,
        x == "target" ~ 0,
        .default = .5
     )
    ),
    size = 4.5,
    color = "white",
    space = 18
  ) +
  scale_x_discrete(
    position = "top",
    labels = c("source" = "Recuerdo de voto 23J", "target" = "Intención de voto dic-2024")
  ) +
  scale_fill_manual(values = color_partidos) +
  labs(
    title = "Transferencia de votos fuera de los partidos",
    x = "",   
    caption = "@congosto\nFuente: CIS"
  ) +
  theme_sankey(base_size = 18) +
  theme(
    legend.position='none',
    plot.title=element_text(color = "#5a5856"),
    plot.caption = element_text(color = "#5a5856", hjust = 0)
  )

Los que votan por primera vez

color_partidos <- c("PSOE" = "#FF0000","PP" = "#09DBDE","VOX"= "#11CA08", "UPN" = "#ea515a",
                    Podemos = "#6329CF",  "ERC" = "#F2C005", "EAJ-PNV" = "#298B13", 
                    "EH-BILDU" = "#ACE155", "Junts" = "#1cc7b0", "Sumar" =  "#ff33c1",
                    "BNG" = "#85d1ed", "CCa" = "#06e7f5", "PACMA" = "#33a41e", "SALF" = "#c59112")

# Alargar estructura de datos
voto_long <- voto %>%
  dplyr::select (Voto,Total,`No tenía edad`, `No tenía derecho a voto`) %>%
  tidyr::pivot_longer(cols = -c(Voto, Total), names_to = "Recuerdo_voto", values_to = "Total_recuerdo")

#  dar forma para sankey
sankey_voto <- voto_long %>%
  make_long(source = Recuerdo_voto, target = Voto, value = Total_recuerdo) 

# Crear el diagrama de Sankey
ggplot(sankey_voto, aes(x = x, next_x = next_x, node = node, next_node = next_node, value = value, fill = factor(node))) +
  geom_sankey(
    flow.alpha = 0.5,
    node.color = "gray30",
    node.width = 20,
    space = 18) + 
  geom_sankey_label(
    aes(
      label = node, 
      fill = "white",
      hjust = dplyr::case_when(
        x == "source" ~ 1,
        x == "target" ~ 0,
        .default = .5
      )
    ),
    size = 4.5,
    color = "white",
    space = 18
  ) +
  scale_x_discrete(
    position = "top",
    labels = c("source" = "Recuerdo de voto 23J", "target" = "Intención de voto dic-2024")
  ) +
  scale_fill_manual(values = color_partidos) +
  labs(
    title = "Los que votan por primera vez",
    x = "",   
    caption = "@congosto\nFuente: CIS"
  ) +
  theme_sankey(base_size = 18) +
  theme(
    legend.position='none',
    plot.title=element_text(color = "#5a5856"),
    plot.caption = element_text(color = "#5a5856", hjust = 0)
  )

Mapa de calor

list_partidos <- c("PSOE","PP","VOX","Sumar","Podemos", "SALF", "ERC", "PACMA", "Junts",
                  "EAJ-PNV", "EH-BILDU", "BNG", "CCa", "UPN")
list_opciones <- c(list_partidos, "Otro partido","En blanco","Voto nulo", "Abstención", "No Sabe todavía","N.C.")

# Alargar estructura de datos
transfer_votos <- voto %>%
  select(-`No tenía edad`, -`No tenía derecho a voto` , -`N.R.` , -`N.C.`) %>%
  tidyr::pivot_longer(
    cols = -c(Voto, Total),
    names_to = "Recuerdo_voto",
    values_to = "Total_recuerdo"
  ) %>%
  mutate(Total_recuerdo = ifelse(is.na(Total_recuerdo),0,Total_recuerdo))

# Ordenar los nombres de las opciones de votación
transfer_votos$Voto <- factor(transfer_votos$Voto, rev(list_opciones))
transfer_votos$Recuerdo_voto <- factor(transfer_votos$Recuerdo_voto, list_opciones)

# Crear el diagrama de treemap
ggplot(data = transfer_votos, aes(x = Recuerdo_voto, y = Voto,fill = Total_recuerdo)) +
  geom_tile()+
  geom_text(
    aes(
      label = ifelse(Total_recuerdo >0, paste0(Total_recuerdo,"%"),"")
     ),
    color="white",
    size =4,
    hjust=0.5,
    vjust=.5 
  ) +
  scale_fill_gradient(low = "steelblue", high = "red4")+
  scale_x_discrete(
    position = "top",
    labels = c(
      "EAJ-PNV" ="EAJ\nPNV", "EH-BILDU" = "EH\nBILDU",
      "Otro partido" = "Otro", "En blanco" = "Blanco",
      "Voto nulo" = "Nulo", "Abstención" = "Abst."),
    expand =  c(0,1)
  ) +
  labs(
    title = "Intención de voto dic-2024 vs. recuerdo de voto 23J",
     fill = "",
     x = "Recuerdo de voto 23J",
     y = "Intención de voto dic-2024",
     caption = "@congosto\nFuente: CIS") +
  theme_light(base_size = 18) +
  theme (
    legend.position="none",
    plot.title=element_text(color = "#5a5856"),
    axis.title=element_text(color = "#5a5856"),
    panel.border = element_blank(),
    panel.background = element_blank(),
    plot.caption = element_text(color = "#5a5856", hjust = 0)
  )