require(knitr)
## Loading required package: knitr
r = getOption("repos")
r["CRAN"] = "http://cran.us.r-project.org" # set up mirror
options(repos = r)
knitr::opts_chunk$set(echo = TRUE)
# set the default root.dir in this r-setup chunk for the whole notebook
opts_knit$set(root.dir = "/Users/raulmiranda/Desktop/DATA 110 Fall 2020/Databases/GIS")
Based on https://www.computerworld.com/article/3038270/data-analytics/create-maps-in-r-in-10-fairly-easy-steps.html by Sharon Machlis sharon_machlis@idg.com and Prof. Rachel Saidi’s tutorial
# names of files and FIPS codes for New Hampshire and South Carolina
nhdatafilecsv <- "NHD2016.csv"
usshapefile <- "cb_2014_us_county_5m/cb_2014_us_county_5m.shp"
nhfipscode <- "33"
scdatafile <- "SCGOP2016.csv"
scfipscode <- "45"
Install packages and libraries
install.packages('shiny')
##
## The downloaded binary packages are in
## /var/folders/f2/clwdhl813kv3ls5yc62jk9v40000gn/T//RtmpfJyjL9/downloaded_packages
install.packages('urltools')
##
## The downloaded binary packages are in
## /var/folders/f2/clwdhl813kv3ls5yc62jk9v40000gn/T//RtmpfJyjL9/downloaded_packages
install.packages('tmap')
##
## The downloaded binary packages are in
## /var/folders/f2/clwdhl813kv3ls5yc62jk9v40000gn/T//RtmpfJyjL9/downloaded_packages
install.packages('tmaptools')
##
## The downloaded binary packages are in
## /var/folders/f2/clwdhl813kv3ls5yc62jk9v40000gn/T//RtmpfJyjL9/downloaded_packages
install.packages('leaflet')
##
## The downloaded binary packages are in
## /var/folders/f2/clwdhl813kv3ls5yc62jk9v40000gn/T//RtmpfJyjL9/downloaded_packages
install.packages('scales')
##
## The downloaded binary packages are in
## /var/folders/f2/clwdhl813kv3ls5yc62jk9v40000gn/T//RtmpfJyjL9/downloaded_packages
install.packages('leaflet.extras')
##
## The downloaded binary packages are in
## /var/folders/f2/clwdhl813kv3ls5yc62jk9v40000gn/T//RtmpfJyjL9/downloaded_packages
install.packages('rio')
##
## The downloaded binary packages are in
## /var/folders/f2/clwdhl813kv3ls5yc62jk9v40000gn/T//RtmpfJyjL9/downloaded_packages
install.packages('htmlwidgets')
##
## The downloaded binary packages are in
## /var/folders/f2/clwdhl813kv3ls5yc62jk9v40000gn/T//RtmpfJyjL9/downloaded_packages
install.packages('sf')
##
## The downloaded binary packages are in
## /var/folders/f2/clwdhl813kv3ls5yc62jk9v40000gn/T//RtmpfJyjL9/downloaded_packages
install.packages('tidyverse')
##
## The downloaded binary packages are in
## /var/folders/f2/clwdhl813kv3ls5yc62jk9v40000gn/T//RtmpfJyjL9/downloaded_packages
install.packages("raster")
##
## The downloaded binary packages are in
## /var/folders/f2/clwdhl813kv3ls5yc62jk9v40000gn/T//RtmpfJyjL9/downloaded_packages
install.packages("rgdal")
##
## The downloaded binary packages are in
## /var/folders/f2/clwdhl813kv3ls5yc62jk9v40000gn/T//RtmpfJyjL9/downloaded_packages
install.packages('viridis')
##
## The downloaded binary packages are in
## /var/folders/f2/clwdhl813kv3ls5yc62jk9v40000gn/T//RtmpfJyjL9/downloaded_packages
library(raster)
library(rgdal)
library(tidyverse)
library(tmap)
library(tmaptools)
library(leaflet)
library(sf)
library(leaflet.extras)
library(dplyr)
library(rio)
library(sp)
library(scales)
library(htmlwidgets)
library(viridis)
nhdata <- import(nhdatafilecsv)
nhdata <- nhdata[,c("County", "Clinton", "Sanders")]
nhdata$SandersMarginVotes <- nhdata$Sanders - nhdata$Clinton
nhdata$SandersPct <- (nhdata$Sanders) / (nhdata$Sanders + nhdata$Clinton)
nhdata$ClintonPct <- (nhdata$Clinton) / (nhdata$Sanders + nhdata$Clinton)
nhdata$SandersMarginPctgPoints <- nhdata$SandersPct - nhdata$ClintonPct
usgeo <- shapefile("cb_2014_us_county_5m/cb_2014_us_county_5m.shp")
qtm(usgeo)
view(usgeo)
Subset the NH data and map it
nhgeo <- usgeo[usgeo$STATEFP==nhfipscode,]
qtm(nhgeo)
Manipulate data; convert county names to character
str(nhgeo)
## Formal class 'SpatialPolygonsDataFrame' [package "sp"] with 5 slots
## ..@ data :'data.frame': 10 obs. of 9 variables:
## .. ..$ STATEFP : chr [1:10] "33" "33" "33" "33" ...
## .. ..$ COUNTYFP: chr [1:10] "009" "011" "007" "001" ...
## .. ..$ COUNTYNS: chr [1:10] "00873178" "00873179" "00873177" "00873174" ...
## .. ..$ AFFGEOID: chr [1:10] "0500000US33009" "0500000US33011" "0500000US33007" "0500000US33001" ...
## .. ..$ GEOID : chr [1:10] "33009" "33011" "33007" "33001" ...
## .. ..$ NAME : chr [1:10] "Grafton" "Hillsborough" "Coos" "Belknap" ...
## .. ..$ LSAD : chr [1:10] "06" "06" "06" "06" ...
## .. ..$ ALAND : chr [1:10] "4425927252" "2269220216" "4648216798" "1036582289" ...
## .. ..$ AWATER : chr [1:10] "105375486" "41604851" "90773891" "177039345" ...
## ..@ polygons :List of 10
## .. ..$ :Formal class 'Polygons' [package "sp"] with 5 slots
## .. .. .. ..@ Polygons :List of 1
## .. .. .. .. ..$ :Formal class 'Polygon' [package "sp"] with 5 slots
## .. .. .. .. .. .. ..@ labpt : num [1:2] -71.8 43.9
## .. .. .. .. .. .. ..@ area : num 0.508
## .. .. .. .. .. .. ..@ hole : logi FALSE
## .. .. .. .. .. .. ..@ ringDir: int 1
## .. .. .. .. .. .. ..@ coords : num [1:327, 1:2] -72.3 -72.3 -72.3 -72.3 -72.3 ...
## .. .. .. ..@ plotOrder: int 1
## .. .. .. ..@ labpt : num [1:2] -71.8 43.9
## .. .. .. ..@ ID : chr "685"
## .. .. .. ..@ area : num 0.508
## .. ..$ :Formal class 'Polygons' [package "sp"] with 5 slots
## .. .. .. ..@ Polygons :List of 1
## .. .. .. .. ..$ :Formal class 'Polygon' [package "sp"] with 5 slots
## .. .. .. .. .. .. ..@ labpt : num [1:2] -71.7 42.9
## .. .. .. .. .. .. ..@ area : num 0.255
## .. .. .. .. .. .. ..@ hole : logi FALSE
## .. .. .. .. .. .. ..@ ringDir: int 1
## .. .. .. .. .. .. ..@ coords : num [1:45, 1:2] -72.1 -72 -72 -72 -72 ...
## .. .. .. ..@ plotOrder: int 1
## .. .. .. ..@ labpt : num [1:2] -71.7 42.9
## .. .. .. ..@ ID : chr "866"
## .. .. .. ..@ area : num 0.255
## .. ..$ :Formal class 'Polygons' [package "sp"] with 5 slots
## .. .. .. ..@ Polygons :List of 1
## .. .. .. .. ..$ :Formal class 'Polygon' [package "sp"] with 5 slots
## .. .. .. .. .. .. ..@ labpt : num [1:2] -71.3 44.7
## .. .. .. .. .. .. ..@ area : num 0.539
## .. .. .. .. .. .. ..@ hole : logi FALSE
## .. .. .. .. .. .. ..@ ringDir: int 1
## .. .. .. .. .. .. ..@ coords : num [1:511, 1:2] -71.8 -71.8 -71.8 -71.7 -71.7 ...
## .. .. .. ..@ plotOrder: int 1
## .. .. .. ..@ labpt : num [1:2] -71.3 44.7
## .. .. .. ..@ ID : chr "922"
## .. .. .. ..@ area : num 0.539
## .. ..$ :Formal class 'Polygons' [package "sp"] with 5 slots
## .. .. .. ..@ Polygons :List of 1
## .. .. .. .. ..$ :Formal class 'Polygon' [package "sp"] with 5 slots
## .. .. .. .. .. .. ..@ labpt : num [1:2] -71.4 43.5
## .. .. .. .. .. .. ..@ area : num 0.136
## .. .. .. .. .. .. ..@ hole : logi FALSE
## .. .. .. .. .. .. ..@ ringDir: int 1
## .. .. .. .. .. .. ..@ coords : num [1:33, 1:2] -71.7 -71.7 -71.7 -71.7 -71.7 ...
## .. .. .. ..@ plotOrder: int 1
## .. .. .. ..@ labpt : num [1:2] -71.4 43.5
## .. .. .. ..@ ID : chr "1100"
## .. .. .. ..@ area : num 0.136
## .. ..$ :Formal class 'Polygons' [package "sp"] with 5 slots
## .. .. .. ..@ Polygons :List of 1
## .. .. .. .. ..$ :Formal class 'Polygon' [package "sp"] with 5 slots
## .. .. .. .. .. .. ..@ labpt : num [1:2] -71.1 43
## .. .. .. .. .. .. ..@ area : num 0.208
## .. .. .. .. .. .. ..@ hole : logi FALSE
## .. .. .. .. .. .. ..@ ringDir: int 1
## .. .. .. .. .. .. ..@ coords : num [1:123, 1:2] -71.5 -71.4 -71.4 -71.4 -71.4 ...
## .. .. .. ..@ plotOrder: int 1
## .. .. .. ..@ labpt : num [1:2] -71.1 43
## .. .. .. ..@ ID : chr "1278"
## .. .. .. ..@ area : num 0.208
## .. ..$ :Formal class 'Polygons' [package "sp"] with 5 slots
## .. .. .. ..@ Polygons :List of 1
## .. .. .. .. ..$ :Formal class 'Polygon' [package "sp"] with 5 slots
## .. .. .. .. .. .. ..@ labpt : num [1:2] -72.3 42.9
## .. .. .. .. .. .. ..@ area : num 0.208
## .. .. .. .. .. .. ..@ hole : logi FALSE
## .. .. .. .. .. .. ..@ ringDir: int 1
## .. .. .. .. .. .. ..@ coords : num [1:161, 1:2] -72.6 -72.6 -72.6 -72.6 -72.6 ...
## .. .. .. ..@ plotOrder: int 1
## .. .. .. ..@ labpt : num [1:2] -72.3 42.9
## .. .. .. ..@ ID : chr "1877"
## .. .. .. ..@ area : num 0.208
## .. ..$ :Formal class 'Polygons' [package "sp"] with 5 slots
## .. .. .. ..@ Polygons :List of 1
## .. .. .. .. ..$ :Formal class 'Polygon' [package "sp"] with 5 slots
## .. .. .. .. .. .. ..@ labpt : num [1:2] -71 43.3
## .. .. .. .. .. .. ..@ area : num 0.11
## .. .. .. .. .. .. ..@ hole : logi FALSE
## .. .. .. .. .. .. ..@ ringDir: int 1
## .. .. .. .. .. .. ..@ coords : num [1:177, 1:2] -71.2 -71.2 -71.2 -71.2 -71.1 ...
## .. .. .. ..@ plotOrder: int 1
## .. .. .. ..@ labpt : num [1:2] -71 43.3
## .. .. .. ..@ ID : chr "2676"
## .. .. .. ..@ area : num 0.11
## .. ..$ :Formal class 'Polygons' [package "sp"] with 5 slots
## .. .. .. ..@ Polygons :List of 1
## .. .. .. .. ..$ :Formal class 'Polygon' [package "sp"] with 5 slots
## .. .. .. .. .. .. ..@ labpt : num [1:2] -71.7 43.3
## .. .. .. .. .. .. ..@ area : num 0.274
## .. .. .. .. .. .. ..@ hole : logi FALSE
## .. .. .. .. .. .. ..@ ringDir: int 1
## .. .. .. .. .. .. ..@ coords : num [1:49, 1:2] -72.1 -72.1 -72 -72.1 -72.1 ...
## .. .. .. ..@ plotOrder: int 1
## .. .. .. ..@ labpt : num [1:2] -71.7 43.3
## .. .. .. ..@ ID : chr "2773"
## .. .. .. ..@ area : num 0.274
## .. ..$ :Formal class 'Polygons' [package "sp"] with 5 slots
## .. .. .. ..@ Polygons :List of 1
## .. .. .. .. ..$ :Formal class 'Polygon' [package "sp"] with 5 slots
## .. .. .. .. .. .. ..@ labpt : num [1:2] -71.2 43.9
## .. .. .. .. .. .. ..@ area : num 0.288
## .. .. .. .. .. .. ..@ hole : logi FALSE
## .. .. .. .. .. .. ..@ ringDir: int 1
## .. .. .. .. .. .. ..@ coords : num [1:73, 1:2] -71.6 -71.4 -71.4 -71.3 -71.4 ...
## .. .. .. ..@ plotOrder: int 1
## .. .. .. ..@ labpt : num [1:2] -71.2 43.9
## .. .. .. ..@ ID : chr "3077"
## .. .. .. ..@ area : num 0.288
## .. ..$ :Formal class 'Polygons' [package "sp"] with 5 slots
## .. .. .. ..@ Polygons :List of 1
## .. .. .. .. ..$ :Formal class 'Polygon' [package "sp"] with 5 slots
## .. .. .. .. .. .. ..@ labpt : num [1:2] -72.2 43.4
## .. .. .. .. .. .. ..@ area : num 0.159
## .. .. .. .. .. .. ..@ hole : logi FALSE
## .. .. .. .. .. .. ..@ ringDir: int 1
## .. .. .. .. .. .. ..@ coords : num [1:118, 1:2] -72.5 -72.4 -72.4 -72.4 -72.4 ...
## .. .. .. ..@ plotOrder: int 1
## .. .. .. ..@ labpt : num [1:2] -72.2 43.4
## .. .. .. ..@ ID : chr "3167"
## .. .. .. ..@ area : num 0.159
## ..@ plotOrder : int [1:10] 3 1 9 8 2 6 5 10 4 7
## ..@ bbox : num [1:2, 1:2] -72.6 42.7 -70.7 45.3
## .. ..- attr(*, "dimnames")=List of 2
## .. .. ..$ : chr [1:2] "x" "y"
## .. .. ..$ : chr [1:2] "min" "max"
## ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slot
## .. .. ..@ projargs: chr "+proj=longlat +datum=NAD83 +no_defs"
str(nhdata$County)
## chr [1:10] "Belknap" "Carroll" "Cheshire" "Coos" "Grafton" "Hillsborough" ...
nhgeo$NAME <- as.character(nhgeo$NAME)
Order geo and votes datasets by county; check if identical; if so, merge both datasets
nhgeo <- nhgeo[order(nhgeo$NAME),]
nhdata <- nhdata[order(nhdata$County),]
if (identical(nhgeo$NAME,nhdata$County)) {
nhmap <- merge(nhgeo, nhdata, by.x = "NAME", by.y = "County") # Merge geo and vote datasets
} else {stop}
qtm(nhmap, "SandersMarginVotes")
qtm(nhmap, "SandersMarginPctgPoints")
tm_shape(nhmap) +
tm_fill("SandersMarginVotes", title="Sanders Margin, Total Votes", palette = "PRGn") +
tm_borders(alpha=.5) +
tm_text("NAME", size=0.8) +
tm_layout(legend.width = .6)
Regraph static map in classic style and save it to “nhdemprimary.jpg”
nhstaticmap <- tm_shape(nhmap) +
tm_fill("SandersMarginVotes", title="Sanders Margin, Total Votes", palette = "viridis") +
tm_borders(alpha=.5) +
tm_text("NAME", size=0.8) +
tm_style("classic") +
tm_layout(legend.width = .6)
nhstaticmap
tmap_save(nhstaticmap, filename="nhdemprimary.jpg")
clintonPalette <- colorNumeric(palette = "Blues", domain=nhmap$ClintonPct) # color palette for Clinton
nhpopup <- paste0("County: ", nhmap$NAME,
" - Sanders ", percent(nhmap$SandersPct), " - Clinton ", percent(nhmap$ClintonPct)) # popup content
nhmap_projected <- sp::spTransform(nhmap, "+proj=longlat +datum=WGS84") # add the appropriate projection, WGS84
leaflet(nhmap_projected) %>%
addProviderTiles("CartoDB.Positron") %>%
addPolygons(stroke=FALSE,
smoothFactor = 0.2,
fillOpacity = .8,
popup=nhpopup,
color= ~clintonPalette(nhmap$ClintonPct))
scdata <- import(scdatafile)
scgeo <- usgeo[usgeo@data$STATEFP=="45",]
qtm(scgeo)
Modify the SC dataset: add columns (9-15) with percent votes for candidates in columns 2-7; then identify the winner in each county
for(i in 2:7){
j = i + 7
scdata[[j]] <- scdata[[i]] / scdata$Total
colnames(scdata)[j] <- paste0(colnames(scdata)[i], "Pct")
}
winner <- colnames(scdata[2:7])
for(i in 1:nrow(scdata)){
scdata$winner[i] <- names(which.max(scdata[i,2:7]))}
Import spreadsheet with % adult population with at least 4-yr college degree; check scgeo name and sced county columns are identical and merge by name=county.
sced <- import("SCdegree.xlsx")
str(scgeo$NAME)
## chr [1:46] "Edgefield" "Lee" "Horry" "Allendale" "Marion" "Dorchester" ...
str(scdata$County)
## chr [1:46] "Abbeville" "Aiken" "Allendale" "Anderson" "Bamberg" "Barnwell" ...
# Change the county names to plain characters in scgeo:
scgeo$NAME <- as.character(scgeo$NAME)
# Order each data set by county name
scgeo <- scgeo[order(scgeo$NAME),]
scdata <- scdata[order(scdata$County),]
# check name and county columns are identical
if (identical(scgeo$NAME,scdata$County )) {
scmap <- merge(scgeo, scdata, by.x = "NAME", by.y = "County")
} else {stop}
Create color palettes:
differentiate the winners by color and their win difference (max-min) by scale of color
minpct <- min(c(scdata$`Donald J TrumpPct`, scdata$`Marco RubioPct`, scdata$`Ted CruzPct`)) # min votes
maxpct <- max(c(scdata$`Donald J TrumpPct`, scdata$`Marco RubioPct`, scdata$`Ted CruzPct`)) # max votes
# Create leaflet palettes for each layer of the map:
trumpPalette <- colorNumeric(palette = "Purples", domain=c(minpct, maxpct)) # w/color scale
rubioPalette <- colorNumeric(palette = "Reds", domain = c(minpct, maxpct)) # w/color scale
cruzPalette <- colorNumeric(palette = "Oranges", domain = c(minpct, maxpct)) # w/color scale
winnerPalette <- colorFactor(palette=c("#984ea3", "#e41a1c"), domain = scmap$winner)
edPalette <- colorNumeric(palette = "Blues", domain=scmap$PctCollegeDegree)
Create a pop-up and add the geographic projection
scpopup <- paste0("<b>County: ", scmap$NAME, "<br />Winner: ", scmap$winner, "</b><br /><br />Trump: ", percent(scmap$`Donald J TrumpPct`), "<br />Rubio: ", percent(scmap$`Marco RubioPct`), "<br />Cruz: ", percent(scmap$`Ted CruzPct`), "<br /><br />Pct w college ed: ", sced$PctCollegeDegree, "% vs state-wide avg of 25%")
scmap <- sp::spTransform(scmap, "+proj=longlat +datum=WGS84") # add the projection
leaflet(scmap) %>%
addProviderTiles("CartoDB.Positron") %>%
addPolygons(stroke=TRUE,
weight=1,
smoothFactor = 0.2,
fillOpacity = .75,
popup=scpopup,
color= ~winnerPalette(scmap$winner),
group="Winners" ) %>%
addLegend(position="bottomleft", colors=c("#984ea3", "#e41a1c"), labels=c("Trump", "Rubio"))
scGOPmap <- leaflet(scmap) %>%
addProviderTiles("CartoDB.Positron") %>%
addPolygons(stroke=TRUE,
weight=1,
smoothFactor = 0.2,
fillOpacity = .75,
popup=scpopup,
color= ~winnerPalette(scmap$winner),
group="Winners" ) %>%
addPolygons(stroke=TRUE,
weight=1,
smoothFactor = 0.2,
fillOpacity = .75,
popup=scpopup,
color= ~trumpPalette(scmap$`Donald J TrumpPct`),
group="Trump") %>%
addPolygons(stroke=TRUE,
weight=1,
smoothFactor = 0.2,
fillOpacity = .75,
popup=scpopup,
color= ~rubioPalette(scmap$`Marco RubioPct`),
group="Rubio") %>%
addPolygons(stroke=TRUE,
weight=1,
smoothFactor = 0.2,
fillOpacity = .75,
popup=scpopup,
color= ~cruzPalette(scmap$`Ted CruzPct`),
group="Cruz") %>%
addPolygons(stroke=TRUE,
weight=1,
smoothFactor = 0.2,
fillOpacity = .75,
popup=scpopup,
color= ~edPalette(sced$PctCollegeDegree), #this data is in the sced table, not scmaps
group="College degs") %>%
addLayersControl(
baseGroups=c("Winners", "Trump", "Rubio", "Cruz", "College degs"),
position = "bottomleft",
options = layersControlOptions(collapsed = FALSE))
scGOPmap
htmlwidgets::saveWidget(widget=scGOPmap, file="Hwk10_scGOPprimary.html")