---
title: "Introduction to parlitools"
author: "Evan Odell"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Introduction to parlitools}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

# Introduction to `parlitools`

`parlitools` is a collection of datasets, maps and data retrieval functions for analysing UK politics.

## Vignettes

In addition to this introductory vignette, there are vignettes on [using `parlitools` with `cartogram`](http://docs.evanodell.com/parlitools/articles/using-cartograms.html), the [British Election Study dataset](http://docs.evanodell.com/parlitools/articles/bes-2015.html) and [mapping local authorities](http://docs.evanodell.com/parlitools/articles/mapping-local-authorities.html).


### Included Data

`party_colours` - A tibble with the ID, name and hex code for the official colour of a variety of political parties, taken from Wikipedia. Includes all political parties with MPs and a number without MPs. (Sources: https://en.wikipedia.org/wiki/Wikipedia:Index_of_United_Kingdom_political_parties_meta_attributes, [`mnis::ref_parties()`](https://cran.r-project.org/package=mnis))

`bes_2015` - A tibble with the British Election Study 2015 Constituency Results Version 2.2. For information on all the variables in this dataset, see the [bes-2015 vignette](http://docs.evanodell.com/parlitools/articles/bes-2015.html) (Source: http://www.britishelectionstudy.com/data-object/2015-bes-constituency-results-with-census-and-candidate-data/)

`council_data` - A tibble with data on the size of each local council (in terms of councillors), and the party or parties controlling the council.  (Sources: http://opencouncildata.co.uk/councils.php?model=, http://geoportal.statistics.gov.uk/datasets/464be6191a434a91a5fa2f52c7433333_0)

`leave_votes_west` - The percentage of votes cast for leave in the 2016 EU referendum. Some constituencies have actual results and others only have estimates by Chris Hanretty; in cases where the actual cote count is known, both the estimates and the actual results are reported. (Sources: https://secondreading.uk/brexit/brexit-votes-by-constituency/ http://www.bbc.co.uk/news/uk-northern-ireland-36616830)

### Data Retrieval Functions

`current_mps` - Uses functions from `hansard` and `mnis` to create a tibble with data on all current MPs, their party affiliation and their constituency.

`mps_on_date`  - Uses functions from `hansard` and `mnis` to create a tibble with data on all MPs from a given date, their party affiliation and their constituency.

### Included Maps

`west_hex_map` - A hexagonal cartogram, stored as a simple feature and data frame, of Westminster parliamentary constituencies. `west_hex_map` can be used to create maps like this:

`local_hex_map` - Hexagonal cartogram, A hexagonal cartogram, stored as a simple feature and data frame, of all Local Authorities in England, Wales and Scotland. 

## Other Data Sources

There are a variety of potentially relevant data sources and datasets on UK politics, far too many for me to include them all in this package, and many of which are far too large. This list is by no means complete:

* [Electoral Commission](http://www.electoralcommission.org.uk/our-work/our-research/electoral-data) - Electoral results dating back to 2005.

* [British Election Study](http://www.britishelectionstudy.com/data/) - A large selection of open data, including panel surveys, linked data and aggregated Twitter data, covering elections and referenda.

* [`hansard`](https://cran.r-project.org/package=hansard) & [`mnis`](https://cran.r-project.org/package=mnis) data retrieval packages for parliamentary APIs.

* [Open Council Data](http://opencouncildata.co.uk/) has data on the names, parties, and wards of all UK councillors, updated more or less weekly.


# Using `parlitools`

## Creating a hexagonal map of constituencies

Create a hexagonal map of all constituency MPs, at the time Parliament was dissolved for the 2017 General Election.

The code below creates a hexagonal map of UK constituency MPs, as of 20 June 2017. 

### Creating a leaflet map:

```{r fig.width=6, fig.height=7, message=FALSE, warning=FALSE}
library(leaflet)
library(sf)
library(htmlwidgets)
library(dplyr)
library(parlitools)

west_hex_map <- parlitools::west_hex_map

party_col <- parlitools::party_colour

mps <- mps_on_date("2017-06-20")

mps_colours <- left_join(mps, party_col, by = "party_id") #Join to current MP data

west_hex_map <- left_join(west_hex_map, mps_colours, by = "gss_code") #Join colours to hexagon map

# Creating map labels
labels <- paste0(
  "<strong>", west_hex_map$constituency_name, "</strong>", "</br>",
  "Party: ", west_hex_map$party_name, "</br>",
  "MP: ", west_hex_map$display_as, "</br>",
  "Most Recent Result: ", west_hex_map$result_of_election, "</br>",
  "Current Majority: ", west_hex_map$majority, " votes"
) %>% lapply(htmltools::HTML)

# Creating the map itself
leaflet(options=leafletOptions(
  dragging = FALSE, zoomControl = FALSE, tap = FALSE,
  minZoom = 6, maxZoom = 6, maxBounds = list(list(2.5,-7.75),list(58.25,50.0)),
  attributionControl = FALSE),
  west_hex_map) %>%
  addPolygons(
    color = "grey",
    weight=0.75,
    opacity = 0.5,
    fillOpacity = 1,
    fillColor = ~party_colour,
    label=labels)  %>% 
  htmlwidgets::onRender(
    "function(x, y) {
        var myMap = this;
        myMap._container.style['background'] = '#fff';
    }")
```


## Mapping Parliamentary Petitions

The [UK Parliamentary Petition site](https://petition.parliament.uk/) has facilities for mapping which parliamentary constituencies signatories of petitions live in. However, it only produces geographic maps, not hexagrams.

I have the petition 'Prevent Donald Trump from making a State Visit to the United Kingdom', both of which attracted  1,863,565 signatures. 

### Anti-Trump petition signatories

```{r fig.width=6, fig.height=7, message=FALSE}
library(leaflet)
library(sf)
library(htmlwidgets)
library(dplyr)
library(hansard)
library(parlitools)

west_hex_map <- parlitools::west_hex_map #Base map

trump_no <- hansard::epetition(ID = 648278, by_constituency=TRUE) #Download anti-inviting Trump signatures

west_trump_no <- dplyr::left_join(west_hex_map, trump_no, by = "gss_code") #Joining to base map

pal = colorNumeric("Blues", trump_no$number_of_signatures)

label_no <- paste0(
  "<strong>", west_trump_no$constituency_name, "</strong>", "</br>",
  "Signatures: ", west_trump_no$number_of_signatures
) %>% lapply(htmltools::HTML)

leaflet(options=leafletOptions(
  dragging = FALSE, zoomControl = FALSE, tap = FALSE,
  minZoom = 6, maxZoom = 6, maxBounds = list(list(2.5,-7.75),list(58.25,50.0)),
  attributionControl = FALSE),
  west_trump_no) %>%
  addPolygons(
    color = "grey",
    weight=0.75,
    opacity = 0.5,
    fillOpacity = 1,
    fillColor = ~pal(number_of_signatures),
    label = label_no) %>%
  addLegend("topright", pal = pal, values = ~number_of_signatures,
    title = "Number of Signatures",
    opacity = 1)  %>% 
  htmlwidgets::onRender(
    "function(x, y) {
        var myMap = this;
        myMap._container.style['background'] = '#fff';
    }")%>% 
  mapOptions(zoomToLimits = "first")
```



### Graphing Demographics and Voting Trends

`parlitools` contains extensive demographic data in the `census_11` dataset. The map below shows the relationship between votes cast for the Labour party and the percentage of the local population holding university degrees.

```{r fig.width=6, fig.height=7, message=FALSE, warning=FALSE}
library(dplyr)
library(ggplot2)

census_11 <- parlitools::census_11

bes_2017 <- parlitools::bes_2017

elect_results <- left_join(census_11, bes_2017)

degree_plot <- ggplot(elect_results, aes(y=lab_17, x=degree)) + geom_point(alpha=0.75) + 
  geom_smooth(size=1.75, colour = "#DC241F") + ylab("Share of Votes Cast for Labour") + xlab("Percentage of Population with a University Degree")

degree_plot

```



