Part 1: Map presidential elections results with the maps package

1. Download the elections file from harvard database

https://dataverse.harvard.edu/dataset.xhtml?persistentId=doi:10.7910/DVN/42MVDX

d <- read.csv('hw8/dataverse_files/1976-2020-president.csv')
head(d)
##   year   state state_po state_fips state_cen state_ic       office
## 1 1976 ALABAMA       AL          1        63       41 US PRESIDENT
## 2 1976 ALABAMA       AL          1        63       41 US PRESIDENT
## 3 1976 ALABAMA       AL          1        63       41 US PRESIDENT
## 4 1976 ALABAMA       AL          1        63       41 US PRESIDENT
## 5 1976 ALABAMA       AL          1        63       41 US PRESIDENT
## 6 1976 ALABAMA       AL          1        63       41 US PRESIDENT
##                 candidate             party_detailed writein candidatevotes
## 1           CARTER, JIMMY                   DEMOCRAT   FALSE         659170
## 2            FORD, GERALD                 REPUBLICAN   FALSE         504070
## 3          MADDOX, LESTER AMERICAN INDEPENDENT PARTY   FALSE           9198
## 4 BUBAR, BENJAMIN ""BEN""                PROHIBITION   FALSE           6669
## 5               HALL, GUS        COMMUNIST PARTY USE   FALSE           1954
## 6         MACBRIDE, ROGER                LIBERTARIAN   FALSE           1481
##   totalvotes  version notes party_simplified
## 1    1182850 20210113    NA         DEMOCRAT
## 2    1182850 20210113    NA       REPUBLICAN
## 3    1182850 20210113    NA            OTHER
## 4    1182850 20210113    NA            OTHER
## 5    1182850 20210113    NA            OTHER
## 6    1182850 20210113    NA      LIBERTARIAN

2. Load the data, and clean it up

library(dplyr)
# group_by then top_n, both from the dplyr package.
d1 <- d %>%
  group_by(state,year) %>%
  top_n(1,candidatevotes)
d2 <- d1 %>% select(year,state,state_fips,party_detailed,candidate)
# define the color 
d2 <- mutate(d2,color = ifelse(party_detailed %in% "DEMOCRAT", "blue",
                          ifelse(party_detailed %in% "REPUBLICAN", "red", "white" )))
d2$color <- as.character(d2$color)
#str(d2)
d2 <- d2 %>% rename(party =  party_detailed)
head(d2)
## # A tibble: 6 × 6
## # Groups:   state, year [6]
##    year state      state_fips party      candidate     color
##   <int> <chr>           <int> <chr>      <chr>         <chr>
## 1  1976 ALABAMA             1 DEMOCRAT   CARTER, JIMMY blue 
## 2  1976 ALASKA              2 REPUBLICAN FORD, GERALD  red  
## 3  1976 ARIZONA             4 REPUBLICAN FORD, GERALD  red  
## 4  1976 ARKANSAS            5 DEMOCRAT   CARTER, JIMMY blue 
## 5  1976 CALIFORNIA          6 REPUBLICAN FORD, GERALD  red  
## 6  1976 COLORADO            8 REPUBLICAN FORD, GERALD  red

3. Try to make a map just for one year

library(maps)
#subset data for just one a year
d2000 <- subset(d2,year==2000)
#select the observsations that match state.fips$fips
d2000 <- d2000[match(state.fips$fips,d2000$state_fips),]
#map
map("state",col=d2000$color,fill=TRUE)
title("Presidential Elections Results by States in 2000")
legend("bottomright", legend = c("Democrat", "Republican","other"), fill = c("blue", "red","white"))

library(ggplot2)
library(usmap)
states <- map_data("state")

p2000<- plot_usmap(regions="states",exclude = c("Alaska","Hawaii","Puerto Rico"), data = d2000, values = "color") + 
  scale_fill_manual(name = "", values =c("red"= "red","blue"= "blue","white"= "white"),
                     labels = c("Democrat", "Republican","other")  ) + 
  labs(titles = "Presidential Elections Results by States in 2000")+
  theme(legend.position = "right")
p2000

4. Now loop that code and map it over time

year <- seq(min(d2$year),max(d2$year),4)
mapf <- list()
library(gridExtra)

for (i in year) {
  #subset data for just one a year
  di <- subset(d2,year==i)
  #select the observsations that match state.fips$fips
  di <- di[match(state.fips$fips,di$state_fips),]
  #map
  map("state",col=di$color,fill=TRUE)
  title(paste("Presidential Elections Results by States in",i))
}

legend("bottomright", legend = c("Democrat", "Republican","other"), fill = c("blue", "red","white"))

#plot with ggplot
year <- seq(min(d2$year),max(d2$year),4)
mapf <- list()
library(gridExtra)
his <- list()
for (i in year) {
  di <- subset(d2,year==i)
  di <- di[match(state.fips$fips,di$state_fips),]
  p<-plot_usmap(regions="states",
                exclude = c("Alaska","Hawaii","Puerto Rico"), 
                data = di, values = "color") + 
    scale_fill_manual(name = "", values =c("red"= "red","blue"= "blue","white"= "white"),
                       labels = c("Democrat", "Republican","other")  ) + 
    labs(titles = paste(i))+
    theme(legend.position = "none")

  t <-   which(year == i)
  # add the plot to the list
  his[[t]]<- p
}

#extract legend
library(gtable)
legend1 = gtable_filter(ggplot_gtable(ggplot_build(p2000)), "guide-box")

grid.arrange(arrangeGrob(grobs = his,nrow = 4),legend1, heights=c(10,1),ncol = 2)

Part 2: Interactive Maps with Leaflet

1. Get familiar with the leaflet package

library(leaflet)
myMap <- leaflet() %>%
  addProviderTiles(providers$OpenStreetMap) %>%
  setView(lat=33.947474, lng=-83.373671, zoom = 12)
myMap
library(leaflet)
beijing <- leaflet() %>%
  addProviderTiles(providers$OpenStreetMap) %>%
  setView(lat=39.904202, lng=116.407394, zoom = 12)
beijing

2. Add your own shapefiles

library(sf)
library(raster)
library(rgdal)
sp <- shapefile('hw8/220130_RRC_Outline_Camp_AL1/T220130_RRC_Outline_Camp_AL1.shp')
# Projection is necessary for R to place the coordinates correctly 
campShapeFile <- spTransform(sp, CRS("+proj=longlat +datum=WGS84 +no_defs")) 
head(campShapeFile)
##   OBJECTID    District Upazila      Settlement        Union         Name_Alias
## 1        1 Cox's Bazar   Ukhia Collective site Palong Khali Bagghona-Putibonia
## 2        2 Cox's Bazar   Ukhia Collective site Palong Khali               <NA>
## 3        3 Cox's Bazar   Ukhia Collective site Palong Khali    Jamtoli-Baggona
## 4        4 Cox's Bazar   Ukhia Collective site  Raja Palong      Kutupalong RC
## 5        5 Cox's Bazar   Ukhia Collective site Palong Khali               <NA>
## 6        6 Cox's Bazar   Ukhia Collective site Palong Khali               <NA>
##      SSID SMSD__Cnam            NPM_Name Area_Acres PeriMe_Met     Camp_Name
## 1 CXB-224    Camp 16 Camp 16 (Potibonia)  130.57004   4136.730       Camp 16
## 2 CXB-203   Camp 02E            Camp 02E   96.58179   4803.162       Camp 2E
## 3 CXB-223    Camp 15   Camp 15 (Jamtoli)  243.25346   4722.267       Camp 15
## 4 CXB-221   Camp KRC       Kutupalong RC   95.70851   3094.872 Kutupalong RC
## 5 CXB-213    Camp 09             Camp 09  160.39225   4116.455        Camp 9
## 6 CXB-214    Camp 10             Camp 10  122.60020   3732.526       Camp 10
##           Area_SqM         Latitude        Longitude Shape_Leng   Shape_Area
## 1  528946.95881724 21.1563813298438 92.1490685817901 0.03853094 4.597769e-05
## 2 391267.799744003 21.2078084302778 92.1643360947381 0.04481152 3.402118e-05
## 3 985424.393160958 21.1606399787906 92.1428956454661 0.04423700 8.565911e-05
## 4 387729.666427279 21.2120281895357 92.1638095873048 0.02878576 3.371450e-05
## 5 649769.878002447 21.1899911992394 92.1603127317644 0.03853989 5.649182e-05
## 6 496664.566973549 21.1897434585344 92.1542587569213 0.03475873 4.318088e-05
library(leaflet)
library(rgeos)
myMap <- leaflet() %>%
  addProviderTiles(providers$OpenStreetMap) %>%
  setView(92.14871, 21.18780, zoom = 12) %>%
  addPolygons(data=campShapeFile, fill=TRUE, stroke=T, weight=1,highlight = highlightOptions(fillOpacity = 0.7),label = campShapeFile$Block_No)
myMap

3. Add tiles from the web

myMap <- leaflet() %>%
   addProviderTiles(providers$OpenStreetMap) %>%
  addWMSTiles(
  "http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi",
  layers = "nexrad-n0r-900913",
  options = WMSTileOptions(format = "image/png", transparent = TRUE),attribution = "Weather data 2012 IEM Nexrad") %>%
  setView(-95.712891, 37.090240, zoom =4)
myMap