Part 1: Map presidential elections results with the maps package

2. Load data and clean it up:

library(dplyr)

# Load the data into R. The relative path works in my R script but does not run in the Markdown so I used the absolute path here
elections <- read.csv("/Users/godwinnutsugah/Dropbox/AAEE-UGA/AAEC 8610/Project_Data/data/1976-2020-president.csv")  
# Select only the relevant columns
elections <- elections %>% 
  select(year, state, candidate, party_detailed, candidatevotes, state_fips) 

# Group the data by year and state, and keep only the top result for each group
elections <- elections %>% 
  group_by(year, state) %>% 
  top_n(1, wt = candidatevotes) %>% 
  ungroup()

# Rename columns for clarity
colnames(elections) <- c("year", "state", "winner_candidate", "winner_party", "winner_votes", "state_fips")

# Define a color for each party
elections$color <- ifelse(elections$winner_party == "DEMOCRAT", "blue", "red")

# Print the resulting dataset
print(elections)
## # A tibble: 612 × 7
##     year state                winner_candidate winner_pa…¹ winne…² state…³ color
##    <int> <chr>                <chr>            <chr>         <int>   <int> <chr>
##  1  1976 ALABAMA              CARTER, JIMMY    DEMOCRAT     659170       1 blue 
##  2  1976 ALASKA               FORD, GERALD     REPUBLICAN    71555       2 red  
##  3  1976 ARIZONA              FORD, GERALD     REPUBLICAN   418642       4 red  
##  4  1976 ARKANSAS             CARTER, JIMMY    DEMOCRAT     498604       5 blue 
##  5  1976 CALIFORNIA           FORD, GERALD     REPUBLICAN  3882244       6 red  
##  6  1976 COLORADO             FORD, GERALD     REPUBLICAN   584278       8 red  
##  7  1976 CONNECTICUT          FORD, GERALD     REPUBLICAN   719261       9 red  
##  8  1976 DELAWARE             CARTER, JIMMY    DEMOCRAT     122461      10 blue 
##  9  1976 DISTRICT OF COLUMBIA CARTER, JIMMY    DEMOCRAT     137818      11 blue 
## 10  1976 FLORIDA              CARTER, JIMMY    DEMOCRAT    1636000      12 blue 
## # … with 602 more rows, and abbreviated variable names ¹​winner_party,
## #   ²​winner_votes, ³​state_fips

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

library(maps)

# Subset the data for the year 2016
data_2016 <- elections[elections$year == 2016,]

# Select the observations that match state.fips$fips
data_2016$state <- state.fips$name[match(data_2016$state_fips, state.fips$fips)]

# Map the data
map("state", fill = TRUE, col = data_2016$color, resolution = 0, lty = 0)

legend("bottomright", legend = c("Republican", "Democratic"),
       fill = c("red", "blue"), bty = "n", ncol = 1, cex = 0.7, title = "Legend")
title("2016 Presidential Election Results by State ")

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

# Define layout grid for plots
par(mfrow = c(5, 3), mar=c(0,0,0,0))


# Add a title to the plot




# create a sequence of years in which elections were held
e_years <- seq(1976,2020,4)
# Loop over years and create maps
for (i in e_years) {
  
  # Subset the data for the current year
  data_year <- elections[elections$year == i,]
  
  # Select the observations that match state.fips$fips
  data_year$state <- state.fips$name[match(data_year$state_fips, state.fips$fips)]
  
  # Map the data
  map("state", fill = TRUE, col = data_year$color)
  mtext(i,side=3,line=1)
}

# Create an empty plot to hold the legend
plot.new()
# Add a legend to the plot
legend("center", legend = c("Republican", "Democratic"),
       fill = c("red", "blue"), bty = "n", ncol = 1, cex = 1)
title("Presidential Election Results by State")

#Part 2: Interactive Maps with Leaflet ## 1. Get familiar with the leaflet package

# creating the my first map
library(leaflet) # load leaflet package
myMap <- leaflet() %>%
  addProviderTiles(providers$OpenStreetMap)
myMap
# Playing around a little bit with different options under providers$
myMap2 <- leaflet() %>%
  addProviderTiles(providers$Esri) %>%
  setView(lat=50.947474, lng=-85.373671, zoom = 5)
myMap2
# last try of maps with different points for long and lat (Ghana)
leaflet() %>%
  setView(lng = -1.0232, lat = 7.9465, zoom = 7) %>%
  addTiles() 

2. Add you own shapefiles

# load the .shp file into R
library(raster)  # Here the sf package was not able to load the data but the raster package did
sp <- shapefile("/Users/godwinnutsugah/Downloads/220130_RRC_Outline_block_AL2/T220130_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)
##   OBJECTID_1 OBJECTID Block_Let Camp_SSID Block_Name   Block_SSID SMSD_Cname
## 1          1        1         I   CXB-232     C04X_I CXB-232_I163   Camp 04X
## 2          2        2         B   CXB-232     C04X_B CXB-232_B165   Camp 04X
## 3          3        3         F   CXB-232     C04X_F CXB-232_F161   Camp 04X
## 4          4        4         C   CXB-232     C04X_C CXB-232_C166   Camp 04X
## 5          5        5         E   CXB-232     C04X_E CXB-232_E160   Camp 04X
## 6          6        6         H   CXB-232     C04X_H CXB-232_H162   Camp 04X
##         Camp_Alias         NPM_Cname Area_Acres         CampName
## 1 Camp 4 Extension Camp 04 Extension  17.579304 Camp 4 Extension
## 2 Camp 4 Extension Camp 04 Extension  19.796469 Camp 4 Extension
## 3 Camp 4 Extension Camp 04 Extension   8.892700 Camp 4 Extension
## 4 Camp 4 Extension Camp 04 Extension  40.189147 Camp 4 Extension
## 5 Camp 4 Extension Camp 04 Extension  17.429451 Camp 4 Extension
## 6 Camp 4 Extension Camp 04 Extension   8.238809 Camp 4 Extension
##           Area_SqM  Shape_Leng  Shape_Le_1   Shape_Area
## 1 71140.9196299387 0.012361753 0.012361755 6.192077e-06
## 2 80113.4668634516 0.010098287 0.010098287 6.973411e-06
## 3 35987.4806593324 0.007094379 0.007094378 3.132450e-06
## 4 162639.706686226 0.023266098 0.023266094 1.415641e-05
## 5 70534.4857807752 0.013253804 0.013253802 6.139350e-06
## 6 33341.2781127569 0.006681391 0.006681390 2.901994e-06
# zooming on South_eastern Bangladesh
library(leaflet)
library(rgeos) # I needed the rgeos package so as I could use the addpolygons command
myMap4 <- leaflet() %>%
  addProviderTiles(providers$OpenStreetMap) %>%
  setView(92.14871, 21.18780, zoom = 12) %>%
  addPolygons(data=campShapeFile, fill=TRUE, stroke=T, weight=1) 
myMap4

Adding some highlight with the highlight option

library(leaflet)
library(rgeos) # I needed the rgeos package so as I could use the addpolygons command
myMap5 <- 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) ) 
myMap5

Adding some labels

library(leaflet)
library(rgeos) # I needed the rgeos package so as I could use the addpolygons command
myMap6 <- 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) 
myMap6

3. Add tiles from the web

# creating the my first map
library(leaflet) # load leaflet package
myMap3 <- leaflet() %>%
  addProviderTiles(providers$OpenStreetMap) %>%
  setView(-95.7129, 37.0902, zoom = 4) %>%
  addWMSTiles(                                               # adding tiles layer to the map
    "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"
  )
myMap3