Motivating Example:

In this demo we will be looking voter turn out data from IPUMS from 2016 and 2018.

vote<-read.csv("https://raw.githubusercontent.com/kitadasmalley/DATA502/main/FALL2021/Data/voterTurnOut1618.csv",
              header=TRUE, 
              stringsAsFactors = FALSE)

Step 1: State Polygons

Import the shapes using the usmaps package:

#install.packages("usmap")
library(usmap)
## Warning: package 'usmap' was built under R version 3.6.2
states <- usmap::us_map()

head(states)
##         x        y order  hole piece group fips abbr    full
## 1 1091779 -1380695     1 FALSE     1  01.1   01   AL Alabama
## 2 1091268 -1376372     2 FALSE     1  01.1   01   AL Alabama
## 3 1091140 -1362998     3 FALSE     1  01.1   01   AL Alabama
## 4 1090940 -1343517     4 FALSE     1  01.1   01   AL Alabama
## 5 1090913 -1341006     5 FALSE     1  01.1   01   AL Alabama
## 6 1090796 -1334480     6 FALSE     1  01.1   01   AL Alabama

Step 2: Joining

library(tidyverse)

mapPropVote<-states%>%
  mutate(State=full)%>%
  left_join(vote)

Step 3: Plot with ggplot

A) Default coloring

this.year=2016

mapPropVote%>%
  filter(YEAR==this.year)%>%
  ggplot(aes(x, y, group = group)) +
  geom_polygon(aes(fill = wgtPropVote),color="black")+
  theme_bw()+
  coord_fixed()

B) Color accessible

#install.packages("viridis")
library(viridis)

mapPropVote%>%
  filter(YEAR==this.year)%>%
  ggplot(aes(x, y, group = group)) +
  geom_polygon(aes(fill = wgtPropVote),color="black")+
  theme_bw()+
  coord_fixed()+
  scale_fill_viridis(option="magma", direction = -1)

C) Basic Interaction with plotly

#install.packages("plotly")
library(plotly)

p<-mapPropVote%>%
  filter(YEAR==this.year)%>%
  ggplot(aes(text=State, x, y, group = group)) +
  geom_polygon(aes(fill = wgtPropVote),color="black")+
  theme_bw()+
  coord_fixed()+
  scale_fill_viridis(option="magma", direction = -1)

ggplotly(p)