1 Introduction

This document shows how data can be added to a map using the R leaflet package. In this example we obtain from an online news article data describing the voting intentions of Australian politicians with regard to same sex marriage law and map that onto a map of New South Wales.

2 Data

2.1 NSW electorates

The map of NSW electorates is obtained as a shapefile from the Australian ELectoral Commission.

nsw <- readOGR("../../data//nsw-esri-06042016", "NSW_electoral_boundaries_25-02-2016")
## OGR data source with driver: ESRI Shapefile 
## Source: "/Users/neilsaunders/Dropbox/projects/github_projects/politics/AusVoteSSM/data/nsw-esri-06042016", layer: "NSW_electoral_boundaries_25-02-2016"
## with 47 features
## It has 9 fields
## Integer64 fields read as strings:  E_div_numb Numccds Actual Projected Total_Popu Australian

2.2 Voting intention

Voting intentions of MPs are obtained from a HTML table in this ABC News article.

abc <- read_html("http://www.abc.net.au/news/2017-11-14/same-sex-marriage-if-the-survey-says-yes-how-will-your-mp-vote/9104112")

ssm_votes_mp <- abc %>% 
  html_nodes("table") %>% 
  .[[1]] %>% 
  html_table()

3 Joining data to the map

The process of joining data is as follows:

  • match electoral division names in the shapefile to those in the data frame from the news article
  • use the matches to add voting intention to the SpatialPolygonsDataFrame
  • simplify the voting intentions by collapsing the “it’s complicated” and “Yes” variations
m1 <- match(nsw$Elect_div, ssm_votes_mp$Electorate)

nsw$Vote <- ssm_votes_mp$`How they would vote`[m1]
nsw$Vote <- gsub("complicated .+$", "complicated", nsw$Vote)
nsw$Vote <- gsub("Yes .+$", "Yes", nsw$Vote)

4 Map generation

The voting data can then be added to the map using leaflet. Note that two electorates (New England and Bennelong) are missing as they do not currently have a representative.

Mouse-over each electorate indicates the name of the politician and their detailed voting intention.

factpal <- colorFactor("Spectral", nsw$Vote)

leaflet(nsw) %>% 
  addPolygons(fillColor = ~factpal(Vote), 
              label = paste(ssm_votes_mp$MP[m1], ssm_votes_mp$`How they would vote`[m1], sep = " : "), 
              fillOpacity = 1, 
              weight = 2) %>% 
  addLegend(position = "bottomright", 
            pal = factpal, 
            values = ~Vote, 
            opacity = 1)