Working with maps

Packages used : dplyr, maps, sf, leaflet

Part 1: Map presidential elections results with the maps package

1. Download the elction file from harvard database

Use this link

2. Load the data, and clean it up
df <- read.csv("1976-2020-president.csv")
head(df)
##   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
# Define color to parties
df$color <- ifelse(df$party_detailed == "DEMOCRAT", "blue",
                   ifelse(df$party_detailed == "REPUBLICAN", "red", "lightyellow"))

df2 <- df %>%
  group_by(state, year) %>%    # grouped by state and year
  top_n(1, candidatevotes)     # select the winning obs, 1st row winning obs
3. Try to make a map just for one year
state <- df2[df2$year == 2012, c("year", "state", "state_fips", "party_detailed", "candidate", "color")]    
# subset data for 2012
state <- state[match(paste(state.fips$fips), paste(state$state_fips)), ] # match data order with map
map("state", col = state$color, fill = TRUE)  # make into the map
title("Presidential election results by state in 2012")

4. Now loop that code and map it over time
years = seq(1976, 2020, 4)
par(mfrow = c(4, 3), mar=c(0,0,0,0))
for (i in years){
 elect_result <- df2[df2$year == i, c("year", "state", "state_fips", "party_detailed", "candidate", "color")] 
 elect_result <- elect_result[match(paste(state.fips$fips), paste(elect_result$state_fips)), ]
 map("state", col = elect_result$color, fill = TRUE)
 mtext(i, slide = 3, line = 1, cex = 0.8)
}

Part 2: Interactive maps with leaflet

1. Get familiar with the leaflet package
myMap <- leaflet() %>%
  addProviderTiles(providers$OpenStreetMap) %>%   #try with different options
  setView(lat = 38.37, lng = -80.28, zoom = 10)
myMap
2. Add your own shapefiles
sp <- shapefile("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
## 0          1        1         I   CXB-232     C04X_I CXB-232_I163   Camp 04X
## 1          2        2         B   CXB-232     C04X_B CXB-232_B165   Camp 04X
## 2          3        3         F   CXB-232     C04X_F CXB-232_F161   Camp 04X
## 3          4        4         C   CXB-232     C04X_C CXB-232_C166   Camp 04X
## 4          5        5         E   CXB-232     C04X_E CXB-232_E160   Camp 04X
## 5          6        6         H   CXB-232     C04X_H CXB-232_H162   Camp 04X
##         Camp_Alias         NPM_Cname Area_Acres         CampName
## 0 Camp 4 Extension Camp 04 Extension  17.579304 Camp 4 Extension
## 1 Camp 4 Extension Camp 04 Extension  19.796469 Camp 4 Extension
## 2 Camp 4 Extension Camp 04 Extension   8.892700 Camp 4 Extension
## 3 Camp 4 Extension Camp 04 Extension  40.189147 Camp 4 Extension
## 4 Camp 4 Extension Camp 04 Extension  17.429451 Camp 4 Extension
## 5 Camp 4 Extension Camp 04 Extension   8.238809 Camp 4 Extension
##           Area_SqM  Shape_Leng  Shape_Le_1   Shape_Area
## 0 71140.9196299387 0.012361753 0.012361755 6.192077e-06
## 1 80113.4668634516 0.010098287 0.010098287 6.973411e-06
## 2 35987.4806593324 0.007094379 0.007094378 3.132450e-06
## 3 162639.706686226 0.023266098 0.023266094 1.415641e-05
## 4 70534.4857807752 0.013253804 0.013253802 6.139350e-06
## 5 33341.2781127569 0.006681391 0.006681390 2.901994e-06
# zoom onto South-Eastern Bangladesh
 bdeshMap <- leaflet() %>%
  addProviderTiles(providers$OpenStreetMap) %>%
  setView(92.14871, 21.18780, zoom = 12) %>%
  addPolygons(data = campShapeFile, fill = TRUE, stroke = T, weight = 1,  
              # add shapefile
              highlight = highlightOptions(fillOpacity = 0.7), 
              label = campShapeFile$Block_SSID) # add highlights and labels

bdeshMap
3. Add tiles from the web
# overlay raster image of current rainfall in the USA
USAmap <- map("state", fill = TRUE, plot = FALSE)
  leaflet() %>%
    addPolygons(data = USAmap, 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"
    )

For more excellent leaflet features go to this page