forked from Cepesp-Fgv/spatial2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.R
1157 lines (981 loc) · 53.6 KB
/
app.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# rm(list=ls())
# options(shiny.reactlog=TRUE)
library(plyr)
library(data.table)
library(shiny)
library(sp)
library(sf)
library(spdep)
library(scales)
library(leaflet)
library(rgeos)
library(raster)
library(maptools)
library(ggplot2)
library(httr)
library(ape)
library(RCurl)
library(digest)
library(shinythemes)
library(dplyr)
library(DT)
library(magrittr)
library(shinyalert)
library(shinyBS)
if(!require(cepespR)) devtools::install_github("Cepesp-Fgv/cepesp-r")
source("global.R")
ui <- navbarPage("CepespMapas",id="nav",theme = shinytheme("flatly"),
tabPanel("Mapa",div(class="outer",
tags$head(
includeCSS("styles.css")
),
tags$style(type="text/css",
".shiny-output-error { visibility: hidden; }",
".shiny-output-error:before { visibility: hidden; }",
"#controlPanel {background-color: rgba(255,255,255,0.8);}",
".leaflet-top.leaflet-right .leaflet-control {
margin-right: 10px; margin-top: 250px;
}"),
leafletOutput("map",width="100%",height="100%")),
absolutePanel(
draggable=FALSE, top = "auto", left = "auto", right = 20, bottom = 20,
width = "auto", height = "auto",
actionButton("map_zoom_in", "+"),
actionButton("map_zoom_out", "-")
),
bootstrapPage(absolutePanel(id = "note", class = "panel panel-default", fixed = TRUE,
draggable = FALSE, top = 60, left = "auto", right = 30, bottom = "auto",
width = 200, height = "auto",
HTML('<button data-toggle="collapse" data-target="#demo">Indicadores</button>'),
tags$div(id = 'demo', class="collapse in",htmlOutput("Indicators1"),
tipify(htmlOutput("Indicators2"),"O Índice G mede o desvio de apoio do candidato em todo o estado de uma distribuição uniforme de apoio em proporção perfeita à população local. G = 0 indica uma taxa uniforme de conversão da população aos votos, e G = 1 indica concentração perfeita de apoio eleitoral em apenas um município.","left"),
tipify(htmlOutput("Indicators3"),"O Morans I mede a correlação espacial de votos. Valores maiores indicam que o apoio do candidato está concentrado em um pequeno número de clusters geográficos. Identificamos vizinhos municipais com base nos 6 municípios vizinhos mais próximos.","left"),
tipify(htmlOutput("Indicators4"),"O número de clusters geográficos estatisticamente significativos de votação (fronteiras verdes no mapa) com base na medida da QL e LISA (Indicadores Locais de Autocorrelação Espacial)","left"))
))
),
tabPanel("Gráficos",
fluidRow(column(width=4,""),column(width=4,plotOutput("QL_dist")),column(width=4,plotOutput("G_cand", height="200px"),plotOutput("I_cand", height="200px"))),
bootstrapPage(absolutePanel(id = "cuts", class = "panel panel-default", fixed = TRUE,
draggable = FALSE, top = "auto", left = "auto", right = 30, bottom = 60,
width = 700, height = "auto",
h4("Winning candidates tend to have more diffuse (low G) and contiguous (high I) support"),
radioButtons("Cut",
label = "Data:",
choices = list("All","Selected Year","Selected State","Selected Party"),
selected = "All")
))
),
tabPanel("Classificar",
column(width=4,""),
column(width=8,plotOutput("quadrant",click="plot_click",hover="plot_hover"),
uiOutput("hover_info"),
htmlOutput("Classify_Note"),
htmlOutput("Classify_Note2"))
),
tabPanel("Clusters",
column(width=4,""),
column(width=4,htmlOutput("Num_clusters"),h4("Cluster Summary"),dataTableOutput("Clusters_agg"),h4("Municipalities by Cluster"),dataTableOutput("Clusters")),
column(width=4,leafletOutput("map_clusters",width="500px",height="400px"))
),
tabPanel("Extremos",
column(width=4,""),
column(width=4,h4("Top and Bottom 5 G Index in this State and Year"),dataTableOutput("Extremes")),
column(width=4,leafletOutput("map_selected_hi",width="500px",height="400px"))
),
tabPanel("Sobre",
column(width=4,""),
column(width=8,h4("Sobre CepespMapas"),htmlOutput("Note"))
),
absolutePanel(id = "controls", class = "panel panel-default", fixed = F,
draggable = F, top = 60, left = 10, right = "auto", bottom = "auto",
width = 260, height = "auto",
fluidPage(useShinyalert(),
tags$head(
tags$style(HTML('#map_down{background-color:#48C9B0}'))
),
tags$head(
tags$style(HTML('#button{background-color:#28B463}'))
),
h4("Opções:"),
selectizeInput("State",
label = NULL,
choices = c("","AC","AM","AL","AP","BA","CE","ES","GO","MA","MS","MG","MT","PA",
"PB","PE","PI","PR","RJ","RN","RO","RR","RS","SC","SE","SP","TO"),
selected = NULL,
options = list(placeholder = 'Escolha um estado:',allowEmptyOption=TRUE)),
selectizeInput("cargo",
label = NULL,
choices = list("",
"Governador" = 3,
"Senador" = 5,
"Deputado Federal" = 6,
"Deputado Estadual"= 7),
selected = NULL,
options = list(placeholder = 'Escolha um cargo:',allowEmptyOption=TRUE)),
selectizeInput("Year",
label = NULL,
choices = c("",
1998,2002,2006,2010,2014),
selected = NULL,
options = list(placeholder = 'Escolha um ano:',allowEmptyOption=TRUE)),
uiOutput("turno_UI"),
checkboxInput("eleito","Somente Candidatos Eleitos?",value = 1)),
uiOutput("party_UI"),
uiOutput("cand_UI"),
radioButtons("Indicator",
label = "Indicador:",
choices = list("Proporção de Votos do Candidato" = 1,
"Proporção de Votos no Município" = "Proporção de Votos",
"Medida QL"),
selected = "Proporção de Votos"),
actionButton("button", label = strong("Atualizar"), width = "95%"),
bsTooltip("cargo", "Todas as eleições onde o distrito eleitoral é o estado estão disponíveis",
"right", options = list(container = "body")),
bsTooltip("party_UI", "Escolha todos os partidos para pesquisar por nome do candidato na caixa abaixo",
"right", options = list(container = "body")),
radioTooltip(id = "Indicator", choice = 1, title = "O percentual de votos no candidato em todo o estado recebidos em cada município.", placement = "right", trigger = "hover", options = list(container = "body")),
radioTooltip(id = "Indicator", choice = "Proporção de Votos", title = "O percentual de votos válidos no município recebidos pelo candidato.", placement = "right", trigger = "hover", options = list(container = "body")),
radioTooltip(id = "Indicator", choice = "Medida QL", title = "A Medida QL indica quantas vezes mais votos o candidato recebeu no município em comparação com se ele tivesse recebido apoio igual em todo o estado. A QL é determinada pela razão entre duas proporções: (i) a proporção dos votos obtidos pelo candidato no município com relação à votação total do candidato no estado, e (ii) o número de eleitores do município sobre o eleitorado total do estado. QLs maiores que um indicam votação superior à esperada e potenciais bases eleitorais dos candidatos.", placement = "right", trigger = "hover", options = list(container = "body")),
conditionalPanel('input.button > 0',
downloadButton('map_down', label = "Download Mapa"), width="95%"),
HTML("</br></br>"))
)
server <- function(input, output, session) {
### Turno ###
turno <- reactive({
cargo <- as.numeric(input$cargo)
if(cargo %in% c(1,3)){
return(input$turno_value)
} else {
return(1)
}
})
output$turno_UI <- renderUI({
cargo <- as.numeric(input$cargo)
if(cargo %in% c(1,3)){
selectizeInput("turno_value",
label = NULL,
choices = list("",
"1º Turno" = 1,
"2º Turno" = 2),
selected = NULL,
options = list(placeholder = 'Escolha um turno:',allowEmptyOption=TRUE))
}
})
### Partido ###
partidos_escolhas <- reactive({
cat("Parsing partidos_escolhas\n")
cargo <- as.numeric(input$cargo)
ano <- as.numeric(input$Year)
turno_use <- turno()
eleito <- as.numeric(input$eleito)
uf <- input$State
print(cargo)
if(uf == "" | is.na(ano) | is.na(cargo)){
cat("Parsing partidos_escolhas. NULL\n")
return(NULL)
}
if(eleito == 1 & !(turno_use == 1 & cargo == 3)){
party_template <- party_template[party_template$RESULTADO == eleito,]
}
choices <- (party_template$SIGLA_PARTIDO[party_template$CODIGO_CARGO == cargo &
party_template$SIGLA_UF == uf &
party_template$ANO_ELEICAO == ano &
party_template$NUM_TURNO == turno_use])
choices <- c("Todos os Partidos", unique(sort(choices)))
cat("Parsing partidos_escolhas. CHECK!!!\n")
return(choices)
})
output$party_UI <- renderUI({
cat("Outputing party_UI.\n")
partidos <- partidos_escolhas()
if(is.null(partidos)){
cat("Outputing party_UI. NULL\n")
return(NULL)
}
UI <- selectizeInput("Party",
label = NULL,
choices = partidos,
selected = "Todos os Partidos",
options = list(placeholder = 'Escolha um partido:',allowEmptyOption=TRUE))
cat("Outputing party_UI. CHECK!!!\n")
return(UI)
})
### Candidato ###
candidatos_value <- reactive({
cat("Parsing candidates names.\n")
if(is.null(partidos_escolhas())){
cat("Parsing candidates names. NULL\n")
return(NULL)
}
cargo <- as.numeric(input$cargo)
ano <- as.numeric(input$Year)
partido <- input$Party
eleito <- as.numeric(input$eleito)
turno_use <- turno()
uf <- input$State
party_template <- party_template[party_template$CODIGO_CARGO == cargo,]
party_template <- party_template[party_template$SIGLA_UF == uf,]
party_template <- party_template[party_template$ANO_ELEICAO == ano,]
party_template <- party_template[party_template$NUM_TURNO == turno_use,]
if(partido != "Todos os Partidos"){
party_template <- party_template[party_template$SIGLA_PARTIDO == partido,]
}
if(eleito == 1 & !(turno_use == 1 & cargo == 3)){
party_template <- party_template[party_template$RESULTADO == eleito,]
}
choices <- unlist(party_template$LISTA_NUMERO)
candidatos_value <- choices[sort(names(choices))]
cat("Parsing candidates names. CHECK!!!\n")
return(candidatos_value)
})
# query_observe <- reactive({
# ano <- isolate(input$Year)
# uf <- isolate(input$State)
# cargo <- isolate(as.numeric(input$cargo))
# party <- isolate(input$Party)
#
# cat(paste0("query_observe: ", paste0(ano,uf,cargo, party),"\n"))
#
# return(paste0(ano,uf,cargo, party))
# })
output$cand_UI <- renderUI({
cat("Outputing cand_UI.\n")
candidatos <- candidatos_value()
if(is.null(candidatos)){
cat("Outputing cand_UI. NULL\n")
return(NULL)
}
print(paste0("candidato: ", candidatos[[1]]))
cat("Outputing candidates UI.\n ")
UI <- selectizeInput("candidato",
label = NULL,
choices = candidatos,
selected = NULL,
options = list(placeholder = 'Escolha um candidato:',allowEmptyOption=TRUE))
cat("Outputing cand_UI. CHECK!!!\n")
return(UI)
})
## Data Querys ##
### Query ###
state_totals <- reactive({
start <- Sys.time()
cat("Downloading State Totals. ")
### Inputs ###
ano <- input$Year
cargo <- as.numeric(input$cargo)
### Loading State Totals
state_totals <- readr::read_rds(paste0("data/state_totals/",ano,"_",cargo,".rds"))
end_start <- difftime(Sys.time(), start, units = "secs")
cat("CHECK!!! (",end_start, "seconds).\n", sep = "")
return(state_totals)
})
mun_totals <- reactive({
start <- Sys.time()
cat("Downloading Municipal Totals. \n")
### Input ###
ano <- input$Year
uf <- input$State
cargo <- as.numeric(input$cargo)
### Load municipal voting totals
mun_totals <- readr::read_rds(paste0("data/mun_totals/", ano,"_", cargo,"_" , uf, ".rds"))
end <- Sys.time()
end_start <- round(difftime(end, start, units = "secs"),2)
cat("Downloading Municipal Totals. CHECK!!! (",end_start, " seconds).\n", sep = "")
return(mun_totals)
})
### Test Query ###
# input <- tibble::tibble(cargo = 6,
# Year = 2014,
# turno = 1,
# Party = "PRB",
# State = "CE",
# candidato = "1010")
# url <- "http://api.cepesp.io/api/consulta/tse"
banco <- eventReactive(input$button, {
cat("Starting to download banco.\n")
start <- Sys.time()
withProgress(message="Por favor, espere...",
detail="Download dos dados",
value=0.3,{
uf <- input$State
partido <- stringr::str_remove_all(input$Party, " ")
cargo <- as.numeric(input$cargo)
candidato <- as.numeric(input$candidato)
if(is.null(partidos_escolhas()) | is.null(candidatos_value())){
cat("Starting to download banco. NULL\n")
return(1)
}
cat("Downloading main data (uf=", uf, "; partido=", partido, ";cargo=", cargo, ";candidato=",candidato,")\n", sep = "")
vars <- list("NUM_TURNO","UF","NUMERO_PARTIDO","ANO_ELEICAO","COD_MUN_IBGE",
"QTDE_VOTOS","NUMERO_CANDIDATO","SIGLA_PARTIDO","NOME_URNA_CANDIDATO",
"DESC_SIT_TOT_TURNO")
banco <- cepespR::get_elections(input$Year, cargo, candidate_number = candidato,
state = uf, columns_list = vars)
print(banco)
banco <- banco[banco$NUM_TURNO == turno(),]
end_beginning <- round(difftime(Sys.time(), start, units = "secs"), 2)
cat("CHECK!!! (", end_beginning, "seconds)\n", sep = "")
})
return(banco)
})
d <- reactive({
cat("Calculating 'd' value. \n")
banco_use <- banco()
if(any(class(banco_use) == c("reactive"))){
cat("Calculating 'd' value. NULL\n")
return(NULL)
}
start <- Sys.time()
withProgress(message="Por favor, espere...",detail="Download dos dados", value=0.3,{
d <- data.table::as.data.table(banco_use)
if(dim(d)[1] != 0){
#Ideally will be faster when can request specific state
setkeyv(d,c('ANO_ELEICAO','COD_MUN_IBGE','NUMERO_CANDIDATO'))
#### Aggregations
d <- merge(d,isolate(mun_totals()), by="COD_MUN_IBGE")
d <- merge(d,isolate(state_totals()), by="UF")
d[,Tot_Deputado := sum(QTDE_VOTOS), by=.(ANO_ELEICAO,UF,NUMERO_CANDIDATO)]
d[,Mun_Vote_Share := (QTDE_VOTOS/Tot_Mun)*100]
d[,Cand_Vote_Share := (QTDE_VOTOS/Tot_Deputado)*100]
incProgress(amount = 0.7)
#### G-Index Calcs
d[,G_temp := (QTDE_VOTOS/Tot_Deputado - Tot_Mun/Tot_State)^2]
d[,G_Index := sum(G_temp),by=.(ANO_ELEICAO,UF,NUMERO_CANDIDATO)] #Correct? CHECK
#### LQ Calcs
d[,LQ := (QTDE_VOTOS/Tot_Deputado)/(Tot_Mun/Tot_State),by=.(ANO_ELEICAO,UF,NUMERO_CANDIDATO)] #Correct?
#Remove NULO line from selectable candidates, though is included in calculations of total statewide and municipal votes above
d <- d[NOME_URNA_CANDIDATO!="#NULO#"]
} else {
d <- data.table("UF" = character(),
"NUMERO_PARTIDO" = integer(),
"ANO_ELEICAO" = integer(),
"COD_MUN_IBGE" = integer(),
"QTDE_VOTOS" = integer(),
"NUMERO_CANDIDATO" = integer(),
"SIGLA_PARTIDO" = character(),
"NOME_URNA_CANDIDATO" = character(),
"DESC_SIT_TOT_TURNO" = character())
}
end <- Sys.time()
end_beginning <- round(difftime(end,start, units = "secs"), 2)
cat("Calculating 'd' value. CHECK!!! (", end_beginning, "seconds)\n")
return(d)
})
})
mun_state_contig <- reactive({
uf <- input$State
## Break
if(uf == ""){
return(NULL)
}
beginning <- Sys.time()
names(mun)[which(names(mun)=="UF")] <- "UF_shape"
mun_state <- mun[mun$UF_shape == uf,]
# state_nb <- poly2nb(mun_state)
# if (any(card(state_nb)==0)){
# mun_state_contig <- mun_state[-which(card(state_nb)==0),]
# } else {
mun_state_contig <- mun_state
# }
end <- Sys.time()
cat("Time for trimming shapefile to state and first screening for neighbours:",end-beginning,".\n")
return(mun_state_contig)
})
dz3 <- reactive({
beginning <- Sys.time()
dz2 <- d()
if(is.null(dz2)){
return(NULL)
}
candidato <- isolate(input$candidato)
dz3_temp <- merge(isolate(mun_state_contig()),dz2, by.x="GEOCOD",by.y="COD_MUN_IBGE",all.x=TRUE,all.y=FALSE)
dz3_temp@data[is.na(dz3_temp@data[,"LQ"])==TRUE,"LQ"] <- 0
dz3_temp@data[is.na(dz3_temp@data[,"QTDE_VOTOS"])==TRUE,"Mun_Vote_Share"] <- 0
dz3_temp@data[is.na(dz3_temp@data[,"QTDE_VOTOS"])==TRUE,"Tot_State"] <- mean(dz3_temp@data[,"Tot_State"],na.rm=TRUE)
dz3_temp@data[is.na(dz3_temp@data[,"QTDE_VOTOS"])==TRUE,"Tot_Deputado"] <- mean(dz3_temp@data[,"Tot_Deputado"],na.rm=TRUE)
dz3_temp@data[is.na(dz3_temp@data[,"QTDE_VOTOS"])==TRUE,"NOME_URNA_CANDIDATO"] <- candidato
dz3_temp$Tot_Mun <- NULL
dz3_temp <- merge(dz3_temp,isolate(mun_totals()),by.x="GEOCOD",by.y="COD_MUN_IBGE")
dz3_temp@data[is.na(dz3_temp@data[,"QTDE_VOTOS"])==TRUE,"QTDE_VOTOS"] <- 0
end <- Sys.time()
cat("Time for merging candidate data with shapefile:",end-beginning,".\n")
dz3 <- dz3_temp
return(dz3)
})
state_nb2 <- reactive({
if(is.null(mun_state_contig())){
return(NULL)
}
state_nb2 <- knn2nb(knearneigh(coordinates(mun_state_contig()), k = 6))
#state_nb2 <- poly2nb(mun_state_contig()) #Necessary to remove 'islands' as causes problems
return(state_nb2)
})
state_nb2listw <- reactive({
beginning <- Sys.time()
if(is.null(state_nb2())){
return(NULL)
}
state_nb2listw <- nb2listw(state_nb2(),zero.policy=TRUE)
end <- Sys.time()
cat("Time for identifying neightbours list: ",end-beginning,".\n")
return(state_nb2listw)
})
dz5 <- reactive({
beginning <- Sys.time()
## Reactive events
dz4 <- dz3()
## Break
if(is.null(dz4)){
return(NULL)
}
state_nb2listw <- isolate(state_nb2listw())
#dz4 <- dz3
lisa <- as.data.frame(localmoran(dz4$LQ,state_nb2listw))
dz4$LISA_I <- lisa[,"Ii"]
dz4$LISA_p <- lisa[,"Pr(z > 0)"]
dz4$LQ_stdzd <- as.vector(scale(dz4$LQ))
dz4$LQ_stdzd_lag <- lag.listw(state_nb2listw,dz4$LQ_stdzd, NAOK=TRUE) #NAOK here helps or hinders?
dz4$category <- "Insignificant"
dz4$category[dz4$LISA_p<0.05 & dz4$LQ_stdzd>=0 & dz4$LQ_stdzd_lag>=0] <- "High-High"
dz4$category[dz4$LISA_p<0.05 & dz4$LQ_stdzd>=0 & dz4$LQ_stdzd_lag<=0] <- "High-Low"
dz4$category[dz4$LISA_p<0.05 & dz4$LQ_stdzd<=0 & dz4$LQ_stdzd_lag>=0] <- "Low-High"
dz4$category[dz4$LISA_p<0.05 & dz4$LQ_stdzd<=0 & dz4$LQ_stdzd_lag<=0] <- "Low-Low"
dz4$category <- as.factor(dz4$category)
end <- Sys.time()
print(c("Time to calculate Moran's I and LISA: ",end-beginning))
dz5 <- dz4
})
output$map <- renderLeaflet({
leaflet(options = leafletOptions(zoomControl = FALSE)) %>%
addProviderTiles(providers$CartoDB.Positron)
})
state_shp <- reactive({
uf <- input$State
if(uf == "")
uf <- "br"
state_shp <- readr::read_rds(paste0("data/shape_states/", uf,".rds"))
})
observe({
uf <- input$State
geo <- as.numeric(st_bbox(state_shp()))
### Base Map ###
leafletProxy("map") %>%
clearShapes() %>%
clearControls() %>%
addPolygons(data = state_shp(),
fillOpacity = 0,
weight = 3,
color = "black",
fillColor = NULL) %>%
flyToBounds(geo[3], geo[4], geo[1], geo[2])
})
observe({
dz5_use <- dz5()
if(is.null(dz5_use)){
return(NULL)
}
proxy <- leafletProxy("map")
proxy %>%
clearShapes() %>%
addPolygons(data = state_shp(),
color = "black",
fillColor = NULL,
fillOpacity = 0)
if (input$Indicator == "Medida QL"){
pal <- colorBin(palette = c("white","light blue","#fcbba1","#fb6a4a","#ef3b2c","#cb181d"),
domain = c(0,1000),
bins = c(0,0.01,1,5,10,50,1000),
na.color = "white")
} else if(input$Indicator == "1") {
pal <- colorNumeric(palette = c("white","red"),
domain = c(0,max(dz5_use@data[["Cand_Vote_Share"]],na.rm=TRUE)),
na.color = "white")
} else {
pal <- colorNumeric(palette = c("white","red"),
domain = c(0,max(dz5_use@data[["Mun_Vote_Share"]],na.rm=TRUE)),
na.color = "white")
}
popup_text <- paste0("<h4>", dz5_use@data[,"NOME"], "</h2>",
"</br>",
dz5_use@data[,"NOME_URNA_CANDIDATO"],
" recebeu ",
"<strong>", dz5_use@data[,"QTDE_VOTOS"], "</strong>",
" votos (",
round((dz5_use@data[,"QTDE_VOTOS"] / dz5_use@data[,"Tot_Deputado"])*100,1),
"% do total recebido pelo candidato(a) no estado). </br>",
"</br> Votos váliados no município: ",
dz5_use@data[,"Tot_Mun"],
" (",
round((dz5_use@data[,"Tot_Mun"] / dz5_use@data[,"Tot_State"])*100,1),
"% do total do Estado).",
"<br>",
"<br> Medida QL: ", round(dz5_use@data[,"LQ"],3))
popup_text_hihi <- paste0("<h4>", dz5_use@data[dz5_use@data$category=="High-High","NOME"], "</h4>",
dz5_use@data[,"NOME_URNA_CANDIDATO"],
" recebeu ",
dz5_use@data[dz5_use@data$category=="High-High","QTDE_VOTOS"],
" votos (",
round((dz5_use@data[dz5_use@data$category=="High-High","QTDE_VOTOS"]/dz5_use@data[dz5_use@data$category=="High-High","Tot_Deputado"])*100,1),
"% do total recebido pelo candidato(a) no estado)",
"</br> </br> Votos válidos no município: ",
dz5_use@data[dz5_use@data$category=="High-High","Tot_Mun"],
" (",
round((dz5_use@data[dz5_use@data$category=="High-High","Tot_Mun"]/dz5_use@data[dz5_use@data$category=="High-High","Tot_State"])*100,1),
"% do total do Estado)",
"<br>",
"<br> Medida QL: ",
round(dz5_use@data[dz5_use@data$category=="High-High","LQ"],3))
proxy %>%
clearControls() %>%
addPolygons(data = dz5_use,
fillOpacity = 0.8,
weight = 0.1,
color = "black",
fillColor = pal(dz5_use@data[[switch(input$Indicator,"Proporção de Votos"="Mun_Vote_Share",
"Medida QL" = "LQ",
"1" = "Cand_Vote_Share")]]),
popup = popup_text) %>%
addLegend(title = switch(input$Indicator,
"Medida QL" = "Medida QL",
"Proporção de Votos" = "% Votos no <br>Município",
"1" = "% Votos do(a)<br>Candidato(a)"),
pal = pal,
values = dz5_use@data[[switch(input$Indicator,"Proporção de Votos"="Mun_Vote_Share",
"Medida QL"="LQ",
"1" = "Cand_Vote_Share")]],
opacity = 0.8,
labFormat = labelFormat(suffix = "%")) %>%
addPolygons(data = dz5_use[dz5_use@data$category=="High-High",],
fillOpacity = 0,
weight = 2,
color = "green",
stroke = TRUE,
popup = popup_text_hihi)
})
### Map for Download ###
map_reactive <- eventReactive(input$button, {
dz5_use <- dz5()
if(is.null(dz5_use)){
return(NULL)
}
geo <- as.numeric(st_bbox(state_shp()))
if (input$Indicator == "Medida QL"){
pal <- colorBin(palette = c("white","light blue","#fcbba1","#fb6a4a","#ef3b2c","#cb181d"),
domain = c(0,1000),
bins = c(0,0.01,1,5,10,50,1000),
na.color = "white")
} else if(input$Indicator == "1") {
pal <- colorNumeric(palette = c("white","red"),
domain = c(0,max(dz5_use@data[["Cand_Vote_Share"]],na.rm=TRUE)),
na.color = "white")
} else {
pal <- colorNumeric(palette = c("white","red"),
domain = c(0,max(dz5_use@data[["Mun_Vote_Share"]],na.rm=TRUE)),
na.color = "white")
}
leaflet(options = leafletOptions(zoomControl = FALSE)) %>%
addProviderTiles(providers$CartoDB.Positron) %>%
addPolygons(data = state_shp(),
fillOpacity = 0,
weight = 3,
color = "black",
fillColor = NULL) %>%
flyToBounds(geo[3], geo[4], geo[1], geo[2]) %>%
addPolygons(data = dz5_use,
fillOpacity = 0.8,
weight = 0.1,
color = "black",
fillColor = pal(dz5_use@data[[switch(input$Indicator,"Proporção de Votos"="Mun_Vote_Share",
"Medida QL" = "LQ",
"1" = "Cand_Vote_Share")]])) %>%
addLegend(title = switch(input$Indicator,
"Medida QL" = "Medida QL",
"Proporção de Votos" = "% Votos no <br>Município",
"1" = "% Votos do(a)<br>Candidato(a)"),
pal = pal,
values = dz5_use@data[[switch(input$Indicator,"Proporção de Votos"="Mun_Vote_Share",
"Medida QL"="LQ",
"1" = "Cand_Vote_Share")]],
opacity = 0.8,
labFormat = labelFormat(suffix = "%")) %>%
addPolygons(data = dz5_use[dz5_use@data$category=="High-High",],
fillOpacity = 0,
weight = 2,
color = "green",
stroke = TRUE)
})
output$map_down <- downloadHandler(filename = paste0(Sys.Date(),
"_customLeafletmap",
".pdf"),
content = function(file){
mapview::mapshot(x = map_reactive(),
file = file,
cliprect = "viewport", # the clipping rectangle matches the height & width from the viewing port
selfcontained = FALSE)}) # when this was not specified, the function for produced a PDF of two pages: one of the leaflet map, the other a blank page.
### End ###
clusters <- reactive({
dz5_HH <- dz5()[dz5()$category=="High-High",]
if (dim(dz5_HH)[1]!=0){
clusters <- gUnion(dz5_HH,dz5_HH)
} else {
clusters <- NULL
}
})
clusters_sp <- reactive({
if (!(is.null(clusters()))){
clusters_sep <- slot(clusters()@polygons[[1]],"Polygons")
clusters_sep <- clusters_sep[unlist(lapply(clusters_sep, function(x) x@hole==FALSE))] #Have to make sure aren't picking up holes too!
polygons_list <- list()
for (i in 1:length(clusters_sep)){
polygons_list[[i]] <- Polygons(list(clusters_sep[[i]]),"test")
polygons_list[[i]]@ID <- paste0(i)
}
clusters_sp <- SpatialPolygons(polygons_list)
}
})
clusters_sp_cent_table <- reactive({
if (!(is.null(clusters()))){
clusters_sp_cent <- gCentroid(clusters_sp(),byid=TRUE)
clusters_sp_cent_table_temp <- as.data.frame(clusters_sp_cent@coords)
clusters_sp_cent_table_temp$Cluster_num <- rownames(clusters_sp_cent_table_temp)
clusters_sp_cent_table <- clusters_sp_cent_table_temp
}
})
clusters_list <- reactive({
if (!(is.null(clusters()))){
clusters_list_temp <- list()
num_clust <- length(clusters_sp())
for (i in 1:num_clust){
clusters_list_temp[[i]] <- raster::intersect(dz5()[dz5()$category=="High-High",],clusters_sp()[i])
clusters_list_temp[[i]]@data$Cluster_Num <- i
}
clusters_list <- clusters_list_temp
}
})
output$Num_clusters <- renderUI({
if (!(is.null(clusters()))){
Num_clusters <- paste0("<b> Number of High-High Clusters: ",length(clusters_list()),"<b>")
HTML(Num_clusters)
} else {
HTML(paste0("<b> No clusters <b>"))
}
})
cluster_table <- reactive({
if (!(is.null(clusters()))){
clusters_table_temp <- rbind.fill(lapply(clusters_list(),slot,'data'))
clusters_table_temp$pct_votes_from_mun <- clusters_table_temp$QTDE_VOTOS/clusters_table_temp$Tot_Deputado
clusters_table_temp <- clusters_table_temp[,c("Cluster_Num","NOME","QTDE_VOTOS","pct_votes_from_mun","LQ")]
clusters_table_temp$pct_votes_from_mun <- round(clusters_table_temp$pct_votes_from_mun*100,1)
clusters_table_temp$LQ <- round(clusters_table_temp$LQ,1)
cluster_table <- clusters_table_temp
}
})
output$Clusters <- renderDataTable({
if (!(is.null(clusters()))){
table_temp <- cluster_table()
colnames(table_temp) <- c("Cluster Number","Municipality","Votes","% Candidate Votes","LQ")
table_temp[,"Votes"] <- round(table_temp[,"Votes"],0)
table_temp[,"% Candidate Votes"] <- round(table_temp[,"% Candidate Votes"],1)
Clusters <- as.data.table(table_temp)
datatable(Clusters, rownames=TRUE, options=list(dom = 't'), selection='single', style = 'bootstrap', class = 'table-bordered')
}
})
output$Clusters_agg <- renderDataTable({
if (!(is.null(clusters()))){
agg <- as.data.frame(as.data.table(cluster_table())[,.(sum(QTDE_VOTOS), sum(pct_votes_from_mun)),by=Cluster_Num])
colnames(agg) <- c("Cluster Number","Total Votes Received","Total % Candidate Votes")
agg[,"Total Votes Received"] <- round(agg[,"Total Votes Received"],0)
agg[,"Total % Candidate Votes"] <- round(agg[,"Total % Candidate Votes"],1)
Clusters_agg <- as.data.table(agg)
datatable(Clusters_agg, rownames=TRUE, options=list(dom = 't'), selection='single', style = 'bootstrap', class = 'table-bordered')
}
})
output$map_clusters <- renderLeaflet({
pal <- colorBin(palette=c("white","light blue","#fcbba1","#fb6a4a","#ef3b2c","#cb181d"),domain=c(0,1000), bins=c(0,0.01,1,5,10,50,1000), na.color="white")
if (!(is.null(clusters()))){
leaflet() %>%
addProviderTiles(providers$CartoDB.Positron) %>%
clearBounds() %>%
addPolygons(data=state_shp(),fillOpacity=0,weight=3,color="black",fillColor=NULL) %>%
addPolygons(data=dz5()[dz5()@data$category=="High-High",], layerId=dz5()@data[dz5()@data$category=="High-High",],fillOpacity=0,weight=3,color="green",stroke=TRUE) %>%
addMarkers(data=clusters_sp_cent_table(),~x,~y,label = ~Cluster_num,labelOptions = labelOptions(noHide = T, textOnly = FALSE,textsize="25px"))
} else {
leaflet() %>%
addProviderTiles(providers$CartoDB.Positron) %>%
clearBounds() %>%
addPolygons(data=state_shp(),fillOpacity=0,weight=3,color="black",fillColor=NULL)
}
})
d_G <- reactive({
d_G <- d()[,unique(G_Index),by=.(UF,NUMERO_CANDIDATO,NOME_URNA_CANDIDATO,NUMERO_PARTIDO,DESC_SIT_TOT_TURNO)]
})
output$Result <- renderUI({
if(is.null(dz3())){
output_error <- "Por favor, informe os parâmetros <b>estado</b>, <b>cargo</b>, <b>ano</b>, <b>partido</b> e <b>candidato</b> antes atualizar o mapa."
return(HTML(output_error))
}
str_Result <- paste0("<b>Resultado: </b>: ",
unique(dz3()@data$DESC_SIT_TOT_TURNO[is.na(dz3()@data$DESC_SIT_TOT_TURNO)==FALSE]),
"<br><b>Votos: </b>",unique(dz3()@data$Tot_Deputado[is.na(dz3()@data$Tot_Deputado)==FALSE]),
"<br><b>Porcentagem dos votos válidos: </b>",round((unique(dz3()@data$Tot_Deputado[is.na(dz3()@data$Tot_Deputado)==FALSE])/unique(dz3()@data$Tot_State[is.na(dz3()@data$Tot_State)==FALSE]))*100,1), "%")
HTML(str_Result)
})
output$G_Index <- renderUI({
str_G_Index <- paste0("<h4>Estatísticas Geoespaciais: </h4><b>Índice G:</b> ",round(unique(dz3()@data$G_Index[is.na(dz3()@data$G_Index)==FALSE]),3))
HTML(str_G_Index)
})
moran_I <- reactive({
moran_I <- moran(dz3()$LQ,state_nb2listw(),n=length(state_nb2()),Szero(state_nb2listw()),zero.policy=TRUE,NAOK=TRUE)$I
})
output$chart_LQ <- renderPlot({
ggplot() +
geom_density(data=dz3()@data,aes(x=LQ),fill="light blue",colour=NA,alpha=0.5) +
xlab("Log of Medida QL") +
theme_classic() +
ylab("Density") +
scale_x_log10()
})
output$chart_scatter <- renderPlot({
ggplot() +
geom_point(aes(x=dz3()@data$Tot_Mun,y=dz3()@data$LQ),color="dark green") +
xlab("Log of Municipal Voting Population") +
ylab("Medida QL") +
theme_classic() +
scale_x_log10()
})
d_stats_cut <- reactive({
if (input$Cut=="All"){
d_stats_cut <- d_stats
} else if (input$Cut=="Selected Year") {
d_stats_cut <- d_stats[d_stats$ANO_ELEICAO==input$Year,]
} else if (input$Cut=="Selected State") {
d_stats_cut <- d_stats[d_stats$UF==input$State,]
} else if (input$Cut=="Selected Party") {
d_stats_cut <- d_stats[as.numeric(substr(d_stats$NUMERO_CANDIDATO,1,2))==input$Party,]
}
d_stats_cut
})
output$G_cand <- renderPlot({
##Check categories for winner here
ggplot() + geom_density(data=d_stats_cut(),aes(x=G_Index),colour=NA,fill="light blue", alpha=0.5) +
xlab("G Index") +
theme_classic() +
ylab("Density") +
geom_vline(xintercept=unique(dz3()@data$G_Index[is.na(dz3()@data$G_Index)==FALSE]),lty=2) +
theme(axis.text=element_text(size=12),axis.title=element_text(size=14,face="bold"),legend.text=element_text(size=))
})
output$I_cand <- renderPlot({
ggplot() +
geom_density(data=d_stats_cut(),aes(x=Moran_I),colour=NA,fill="light blue",alpha=0.5) +
xlab("Moran's I") +
ylab("Density") +
theme_classic() +
geom_vline(xintercept=moran_I(),lty=2) +
theme(axis.text=element_text(size=12),
axis.title=element_text(size=14,face="bold"),
legend.text=element_text(size=12))
})
output$QL_dist <- renderPlot({
ggplot() + geom_density(data=as.data.frame(d()),aes(x=LQ), color=NA, fill="#2ca25f", alpha=0.5, na.rm=T) +
geom_vline(xintercept=1,lty=2) +
xlim(0,2) +
xlab("QL") +
theme_classic() +
ylab("Density") +
theme(axis.text=element_text(size=12),axis.title=element_text(size=14,face="bold"),legend.text=element_text(size=))
})
output$Note <- renderUI({
note <- paste0("<font size='3'> As mapas eleitorais foram desenvolvidos utilizando os dados coletados e limpos pelo <a href='http://cepesp.io/'> CepespData </a>. Desenvolvido por Jonathan Phillips e Rafael de Castro Coelho Silva com apoio do equipe CEPESP. </font>")
HTML(note)
})
output$moran <- renderUI({
str_moran <- paste0("<b> Moran's I: </b>", round(moran_I(),3))
HTML(str_moran)
})
output$quadrant <- renderPlot({
ggplot() +
geom_point(data=d_stats[d_stats$CODIGO_CARGO==input$cargo & d_stats$ANO_ELEICAO==input$Year & d_stats$UF==input$State,],aes(x=G_Index,y=Moran_I,size=Tot_Deputado),color="blue",alpha=0.2) +
geom_point(data=d_stats[d_stats$CODIGO_CARGO==input$cargo & d_stats$NUMERO_CANDIDATO!=input$candidato & d_stats$ANO_ELEICAO==input$Year & d_stats$UF==input$State & as.numeric(substr(d_stats$NUMERO_CANDIDATO,1,2))==as.numeric(substr(input$candidato,1,2)),],aes(x=G_Index,y=Moran_I,size=Tot_Deputado),color="red",alpha=0.8) +
geom_point(data=d_stats[d_stats$CODIGO_CARGO==input$cargo & d_stats$NUMERO_CANDIDATO==input$candidato & d_stats$ANO_ELEICAO==input$Year & d_stats$UF==input$State,],aes(x=G_Index,y=Moran_I,size=Tot_Deputado),color="dark green",alpha=1) +
theme_classic() +
geom_vline(xintercept=median(d_stats[d_stats$CODIGO_CARGO==input$cargo & d_stats$ANO_ELEICAO==input$Year & d_stats$UF==input$State,"G_Index"][[1]],na.rm=TRUE),lty=2) +
geom_hline(yintercept=median(d_stats[d_stats$CODIGO_CARGO==input$cargo & d_stats$ANO_ELEICAO==input$Year & d_stats$UF==input$State,"Moran_I"][[1]],na.rm=TRUE),lty=2) +
theme(axis.text=element_text(size=12),axis.title=element_text(size=14,face="bold"),legend.text=element_text(size=12)) +
xlab("G Index") +
ylab("Moran's I")
})
mouse <- reactive({
if (is.null(input$plot_click)){
mouse_temp <- d_uniq[d_uniq$anoEleicao==input$Year & d_uniq$sigla_UF==input$State & d_uniq$NUMERO_CANDIDATO==input$candidato,][1,]
} else {
mouse_temp <- nearPoints(d_uniq[d_uniq$anoEleicao==input$Year & d_uniq$sigla_UF==input$State,],input$plot_click,threshold=20,maxpoints=1)
}
mouse <- mouse_temp
})
G_Quadrant <- reactive({
if(d_uniq[d_uniq$NUMERO_CANDIDATO==mouse()$NUMERO_CANDIDATO & d_uniq$anoEleicao==input$Year & d_uniq$sigla_UF==input$State & d_uniq$NUMERO_PARTIDO==as.numeric(substr(mouse()$NUMERO_CANDIDATO,1,2)),"G_Index"][[1]]>median(d_uniq[d_uniq$anoEleicao==input$Year & d_uniq$sigla_UF==input$State,"G_Index"][[1]],na.rm=TRUE)){
G_Quadrant_temp <-"above"
} else {
G_Quadrant_temp <- "below"
}
G_Quadrant <- G_Quadrant_temp
})
G_desc <- reactive({
if(d_uniq[d_uniq$NUMERO_CANDIDATO==mouse()$NUMERO_CANDIDATO & d_uniq$anoEleicao==input$Year & d_uniq$sigla_UF==input$State & d_uniq$NUMERO_PARTIDO==as.numeric(substr(mouse()$NUMERO_CANDIDATO,1,2)),"G_Index"][[1]]>median(d_uniq[d_uniq$anoEleicao==input$Year & d_uniq$sigla_UF==input$State,"G_Index"][[1]],na.rm=TRUE)){
G_desc_temp <-"concentrated"
} else {
G_desc_temp <- "diffuse"
}
G_desc <- G_desc_temp
})
Moran_Quadrant <- reactive({
if(d_uniq[d_uniq$NUMERO_CANDIDATO==mouse()$NUMERO_CANDIDATO & d_uniq$anoEleicao==input$Year & d_uniq$sigla_UF==input$State & d_uniq$NUMERO_PARTIDO==as.numeric(substr(mouse()$NUMERO_CANDIDATO,1,2)),"MoranI"][[1]]>median(d_uniq[d_uniq$anoEleicao==input$Year & d_uniq$sigla_UF==input$State,"MoranI"][[1]],na.rm=TRUE)){
Moran_Quadrant_temp <-"above"
} else {
Moran_Quadrant_temp <- "below"
}
Moran_Quadrant <- Moran_Quadrant_temp
})
Moran_desc <- reactive({
if(d_uniq[d_uniq$NUMERO_CANDIDATO==mouse()$NUMERO_CANDIDATO & d_uniq$anoEleicao==input$Year & d_uniq$sigla_UF==input$State & d_uniq$NUMERO_PARTIDO==as.numeric(substr(mouse()$NUMERO_CANDIDATO,1,2)),"MoranI"][[1]]>median(d_uniq[d_uniq$anoEleicao==input$Year & d_uniq$sigla_UF==input$State,"MoranI"][[1]],na.rm=TRUE)){
Moran_desc_temp <-"contiguous"
} else {
Moran_desc_temp <- "dispersed"
}
Moran_desc <- Moran_desc_temp
})
mouse_cand <- reactive({
mouse_cand <- d_uniq[d_uniq$NUMERO_CANDIDATO==mouse()$NUMERO_CANDIDATO & d_uniq$anoEleicao==input$Year & d_uniq$sigla_UF==input$State,"NOME_URNA_CANDIDATO"][[1]]
})
classify_note_text <- reactive({
classify_note_text <- paste0("Each point represents a <font color=\"blue\"> Candidate </font> in this election, with the size proportionate to their total number of votes received. <font color=\"red\"> Red </font> points indicate votes for the selected party. The <font color=\"green\"> Green </font> point is the selected candidate. Click on <font color=\"red\">Red </font> or <font color=\"green\"> Green </font> points to view the distribution of Medida QLs for that candidate. <br> <br>")
})
classify_note_text_2 <- reactive({
classify_note_text_2 <- paste0("The currently selected candidate (on the chart above), ", mouse_cand() ," has a G-Index <b>", G_Quadrant(),"</b> the median and a Moran's I <b>", Moran_Quadrant(), "</b> the median, indicating that the candidate's support is more <b>",G_desc(),"</b> and <b>",Moran_desc(),"</b> than average.")