Skip to content

Instantly share code, notes, and snippets.

@cndesantana
Last active May 14, 2020 16:09
Show Gist options
  • Select an option

  • Save cndesantana/90aeff465aa334a758a6d174744b7a29 to your computer and use it in GitHub Desktop.

Select an option

Save cndesantana/90aeff465aa334a758a6d174744b7a29 to your computer and use it in GitHub Desktop.
flexdashboard para apresentar dados eleitorais de SP em 2018
---
title: Mapas eleitorais
output: flexdashboard::flex_dashboard
runtime: shiny
---
```{r}
library(rnaturalearth)
library(wbstats)
library(leaflet)
library(DT)
library(ggplot2)
library(data.table)
library(tidyverse)
library(sf)
filename_1turno <- "data/votos_sp/gov_sp_1turno.csv"
filename_2turno <- "data/votos_sp/gov_sp_2turno.csv"
filename_mapa <- "data/zonaseleitorais_sp/zonaseleitorais2.shp"
votos1 <- fread(filename_1turno, stringsAsFactors = FALSE)
votos2 <- fread(filename_2turno, stringsAsFactors = FALSE)
#map <- ne_countries()
map <- as(st_read(filename_mapa, stringsAsFactors = FALSE, quiet=TRUE), "Spatial")
#names(map)[names(map) == "iso_a3"] <- "ISO3"
#names(map)[names(map) == "name"] <- "NAME"
#d <- wb(indicator = "EN.ATM.PM25.MC.M3",
# startdate = 2016, enddate = 2016)
```
Column {.sidebar data-width=150}
-------------------------------------
```{r}
selectInput("turno", label = "Turno",
choices = c(1,2), selected = 1)
renderUI({
if(as.numeric(input$turno)==1){
votos = votos1
}else{
votos = votos2
}
candidatos = votos %>%
distinct(NM_VOTAVEL) %>%
select(NM_VOTAVEL)
selectInput("candidato1", label = "Candidato 1",
choices = candidatos$NM_VOTAVEL)
})
renderUI({
if(as.numeric(input$turno)==1){
votos = votos1
}else{
votos = votos2
}
candidatos = votos %>%
distinct(NM_VOTAVEL) %>%
select(NM_VOTAVEL)
selectInput("candidato2", label = "Candidato 1",
choices = candidatos$NM_VOTAVEL)
})
allvotos <- reactive({
votos %>%
group_by(NR_ZONA) %>%
mutate(totalzona = sum(QT_VOTOS)) %>%
ungroup() %>%
group_by(NR_ZONA, NR_VOTAVEL, NM_VOTAVEL, totalzona) %>%
summarise(votoszona = sum(QT_VOTOS)) %>%
ungroup() %>%
group_by(NR_ZONA, NR_VOTAVEL, NM_VOTAVEL) %>%
summarise(porcvotos = round(100*votoszona/totalzona,1)) %>%
ungroup()
})
```
Column {data-width=325}
-------------------------------------
### Candidato 1
```{r}
mapFiltered <- map
allvotos <- allvotos()
names(mapFiltered)[1] <- "NR_ZONA"
mapFiltered$NR_ZONA <- as.integer(mapFiltered$NR_ZONA)
mapFiltered <- merge(mapFiltered, allvotos(), all = TRUE)
pal <- colorBin(
palette = "viridis", domain = mapFiltered()$porcvotos,
bins = seq(0, 110, by = 10)
)
#datos_votos1 <- votos1 %>% filter(NM_VOTAVEL == input$candidato1)
mapFiltered$labels <- paste0(
"<strong> Zona: </strong> ",
mapFiltered$Name, "<br/> ",
"<strong> % de votos: </strong> ",
mapFiltered()$votacao$porcvotos, "<br/> "
) %>%
lapply(htmltools::HTML)
renderLeaflet({
if (nrow(mapFiltered()) == 0) {
return(NULL)
}
leaflet(mapFiltered()) %>%
addTiles() %>%
setView(lng = 0, lat = 30, zoom = 2) %>%
addPolygons(
fillColor = ~ pal(votacao$porcvotos),
color = "white",
fillOpacity = 0.7,
label = ~labels,
highlight = highlightOptions(
color = "black",
bringToFront = TRUE
)
) %>%
leaflet::addLegend(
pal = pal, values = ~votacao$porcvotos,
opacity = 0.7, title = "% de votos"
)
})
```
@cndesantana
Copy link
Author

cndesantana commented May 14, 2020

# 
library(shiny)
library(plyr)
library(dplyr)
library(leaflet)
library(rgdal)
library(data.table)
library(tidyr)
library(sf)

data1 <- fread("gov_sp_1turno.csv")
data2 <- fread("gov_sp_2turno.csv")

data1 <- data1 %>% filter(NR_VOTAVEL %in% c(40,13,15,45))
data2 <- data2 %>% filter(NR_VOTAVEL %in% c(40,45))

data.for.map1 <- data1 %>% 
   ungroup()%>%
   dplyr::filter(CD_MUNICIPIO == 71072, CD_CARGO == 3) %>%
   dplyr::group_by(NR_ZONA) %>%
   dplyr::mutate(totalvotos = sum(QT_VOTOS),
                 Name = NR_ZONA) %>%
   ungroup()%>%
   dplyr::group_by(Name, NM_VOTAVEL, totalvotos)%>%
   dplyr::summarise(percvotos = 100*sum(QT_VOTOS)/mean(totalvotos))

data.for.map2 <- data2 %>% 
   ungroup()%>%
   dplyr::filter(CD_MUNICIPIO == 71072, CD_CARGO == 3) %>%
   dplyr::group_by(NR_ZONA) %>%
   dplyr::mutate(totalvotos = sum(QT_VOTOS),
                 Name = NR_ZONA) %>%
   ungroup()%>%
   dplyr::group_by(Name, NM_VOTAVEL, totalvotos)%>%
   dplyr::summarise(percvotos = 100*sum(QT_VOTOS)/mean(totalvotos))

data.for.map <- data.for.map1 %>% 
   ungroup()%>%
   spread(NM_VOTAVEL, percvotos)

# MAP
# GET SHAPE FILE
shape <- st_read("zonaseleitorais2.shp", quiet=TRUE)
shape$Name <- as.integer(unlist(lapply(shape$Name, as.character)))
shape <- shape %>% left_join(data.for.map, by = "Name")

ui <- shinyUI(fluidPage(leafletOutput("mymap", width = "100%", height = 500),
                        absolutePanel(top=1, right=150,
                                      selectInput("measure", "Primeiro Turno", c("Marcio França", "João Dória", "Luiz Marinho", "Paulo Skaf"), selected="Marcio França"))
))

server <- shinyServer(function(input, output) {
   
   
   points <- eventReactive(input$recalc, {
      cbind(rnorm(40) * 2 + 13, rnorm(40) + 48)
   }, ignoreNULL = FALSE)
   
   output$mymap <- renderLeaflet({
      x <- shape$`MARCIO FRANCA`
      
      if(input$measure=="Marcio França"){x <- shape$`MARCIO FRANCA`}
      if(input$measure=="João Dória"){x <- shape$`JOAO DORIA`}
      if(input$measure=="Paulo Skaf"){x <- shape$`PAULO SKAF`}
      if(input$measure=="Luiz Marinho"){x <- shape$`LUIZ MARINHO`}
      dominio <- c(0,60)
      shape$labels <- paste0(
         "<strong> Zona: </strong> ",
         shape$Name, "<br/> ",
         "<strong> % de votos: </strong> ",
         round(x,1), "<br/> "
      ) %>%
         lapply(htmltools::HTML)
      
      pal <- colorNumeric(
         palette = "Reds", domain = dominio
      )
      
      legend.title <- paste(paste0(input$measure, " ("), round(min(x, na.rm=T), 2), " - ", round(max(x, na.rm=T), 2), ")", sep="")
      
      leaflet(shape) %>%
         addPolygons(stroke = FALSE, 
                     smoothFactor = 0.2, 
                     fillOpacity = 0.9, 
                     fillColor = ~ pal(x),
                     color = "black",
                     label = ~labels,
                     highlight = highlightOptions(
                        color = "black",
                        bringToFront = TRUE
                     )
                     ) %>%
         addLegend("bottomright", pal = pal, values = dominio, title = legend.title, labFormat = labelFormat(suffix = ""), opacity = 0.3)
      
   })
})




# Run the application
shinyApp(ui = ui, server = server)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment