Part 1: Map presidential elections results with the maps package

1. Download the elections file from harvard database:

Use this “database”.

2. Load the data, and clean it up:

# need these packages while we work
library(dplyr)
library(maps)
library(leaflet)
library(sf)
library(rgdal)
library(raster)

# read csv data
my_data <- read.csv("1976-2020-president.csv")
str(my_data)
## 'data.frame':    4287 obs. of  15 variables:
##  $ year            : int  1976 1976 1976 1976 1976 1976 1976 1976 1976 1976 ...
##  $ state           : chr  "ALABAMA" "ALABAMA" "ALABAMA" "ALABAMA" ...
##  $ state_po        : chr  "AL" "AL" "AL" "AL" ...
##  $ state_fips      : int  1 1 1 1 1 1 1 2 2 2 ...
##  $ state_cen       : int  63 63 63 63 63 63 63 94 94 94 ...
##  $ state_ic        : int  41 41 41 41 41 41 41 81 81 81 ...
##  $ office          : chr  "US PRESIDENT" "US PRESIDENT" "US PRESIDENT" "US PRESIDENT" ...
##  $ candidate       : chr  "CARTER, JIMMY" "FORD, GERALD" "MADDOX, LESTER" "BUBAR, BENJAMIN \"\"BEN\"\"" ...
##  $ party_detailed  : chr  "DEMOCRAT" "REPUBLICAN" "AMERICAN INDEPENDENT PARTY" "PROHIBITION" ...
##  $ writein         : logi  FALSE FALSE FALSE FALSE FALSE FALSE ...
##  $ candidatevotes  : int  659170 504070 9198 6669 1954 1481 308 71555 44058 6785 ...
##  $ totalvotes      : int  1182850 1182850 1182850 1182850 1182850 1182850 1182850 123574 123574 123574 ...
##  $ version         : int  20210113 20210113 20210113 20210113 20210113 20210113 20210113 20210113 20210113 20210113 ...
##  $ notes           : logi  NA NA NA NA NA NA ...
##  $ party_simplified: chr  "DEMOCRAT" "REPUBLICAN" "OTHER" "OTHER" ...
# Define the color variable in the dataset
my_data$color <- ifelse(my_data$party_detailed == "DEMOCRAT", "blue",
                        ifelse(my_data$party_detailed == "REPUBLICAN", "red", "white"))

# Select winning observations: First row of each state is chosen for each year because it has the highest votes
win <- my_data %>% group_by(state, year) %>% top_n(1, candidatevotes)  # grouped and maximum value extracted
win <- win[, c("year", "state", "state_fips", "party_detailed", "candidate", "color")]  #subsetting the data

3. Try to make a map just for one year:

state <- win[win$year == 2020,]
state <- state[match(paste(state.fips$fips),paste(state$state_fips)),] #making sure the order of the data

# make a map
map("state", col = state$color, fill = TRUE)
legend("bottomleft", legend = c("DEMOCRAT", "REPUBLICAN"), fill = c("blue", "red"), cex = 0.8)
title("Presidential election results by state in 2020")

4. Now loop that code and map it over time:

# loop over time
years = seq(1976, 2020, 4)
par(mfrow=c(4,3), mar=c(0,0,0,0))
for (i in years) {
  temp <- win[win$year == i, c("state", "state_fips", "party_detailed", "color")]
  temp <- temp[match(paste(state.fips$fips), paste(temp$state_fips)),]
  map("state", col = temp$color, fill = TRUE)
  mtext(i, side = 3, line = 1, cex = 0.8)
}

Part 2: Interactive Maps with Leaflet

1. Get familiar with the leaflet package

# try different option and the setView command
myMap <- leaflet() %>%
  addProviderTiles(providers$OpenStreetMap) %>%
  setView(lat=33.947474, lng=-83.373671, zoom = 12)
myMap

2. Add your own shapefiles

# Load the shape file 
sp <- shapefile("C:/Users/Mei/Desktop/PhD/courses/Spring 2021/econometrics/Assignments/HW7Maps/data/200908_RRC_Outline_Block_AL2.shp")
# Projection is necessary for R to place the coordinates correctly
campShapeFile <- spTransform(sp, CRS("+proj=longlat +datum=WGS84 +no_defs"))
head(campShapeFile)
##   Block_Let Camp_SSID Block_Name   Block_SSID SMSD_Cname       Camp_Alias
## 0         I   CXB-232     C04X_I CXB-232_I163   Camp 04X Camp 4 Extension
## 1         B   CXB-232     C04X_B CXB-232_B165   Camp 04X Camp 4 Extension
## 2         F   CXB-232     C04X_F CXB-232_F161   Camp 04X Camp 4 Extension
## 3         C   CXB-232     C04X_C CXB-232_C166   Camp 04X Camp 4 Extension
## 4         E   CXB-232     C04X_E CXB-232_E160   Camp 04X Camp 4 Extension
## 5         H   CXB-232     C04X_H CXB-232_H162   Camp 04X Camp 4 Extension
##           NPM_Cname Area_Acres         CampName         Area_SqM
## 0 Camp 04 Extension  17.597196 Camp 4 Extension 71213.3263972732
## 1 Camp 04 Extension  19.816614 Camp 4 Extension 80194.9934341609
## 2 Camp 04 Extension   8.901736 Camp 4 Extension 36024.0480281611
## 3 Camp 04 Extension  40.230092 Camp 4 Extension  162805.40781136
## 4 Camp 04 Extension  17.447146 Camp 4 Extension 70606.0954539348
## 5 Camp 04 Extension   8.247218 Camp 4 Extension 33375.3063270588
# zooming to Bangladesh
Bangladesh <- 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),  # add highlight and label
            label = campShapeFile$Block_No)
Bangladesh

3. Add tiles from the web

# overlay raster image of current rainfall in US
USA <- map("state", fill = TRUE, plot=FALSE)
  leaflet() %>%
  addPolygons(data=USA, fill=TRUE, stroke=T, weight=1) %>%
  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"
  )

4. For more excellent leaflet features

Visit “this page”