Sunday, November 13, 2016

Mapping the TTC Lines with R and Leaflet


It's been quite a while since I've written a post, but as of late I've become really interested in mapping and so have been checking out different tools for doing this, one of which is Leaflet. This is an example of a case where, because of a well-written package for R, it's easy for the user to create interactive web maps directly from R, without even knowing any Javascript!

I had three requirements for myself:
  1. Write code that created an interactive web map using Leaflet
  2. Use Shapefile data about the City of Toronto
  3. Allow anyone to run it on their machine, without having to download or extract data
I decided to use shapefile data on the TTC, available from Toronto's Open Data portal. Point #3 required a little research, as the shapefile itself was buried within a zip, but it's fairly straightforward to write R code to download and unpack zip files into a temporary directory.

The code is below, followed by the result. Not a bad result for only 10 or 15 lines!
# MAPPING THE TORONTO SUBWAY LINES USING R & Leaflet
# --------------------------------------------------
#
# Myles M. Harrison
# http://www.everydayanalytics.ca

#install.packages('leaflet')
#install.packages('maptools')
library(leaflet)
library(htmlwidgets)
library(maptools)

# Data from Toronto's Open Data portal: http://www.toronto.ca/open

# Download the file and read in the
data_url <- "http://opendata.toronto.ca/gcc/TTC_subway%20lines_wgs84.zip"
cur_dir <- getwd()
temp_dir <- tempdir()
setwd(temp_dir)
download.file(data_url, "subway_wgs84.zip")
unzip("subway_wgs84.zip")
sh <- readShapeLines("subway_wgs84.shp")
unlink(dir(temp_dir))
setwd(cur_dir)

# Create a categorical coloring function
linecolor <- colorFactor(rainbow(16), sh@data$SBWAY_NAME)

# Plot using leaflet
m <- leaflet(sh) %>%
  addTiles() %>%
  addPolylines(popup = paste0(as.character(sh@data$SBWAY_NAME)), color=linecolor(sh@data$SBWAY_NAME)) %>%
  addLegend(colors=linecolor(sh@data$SBWAY_NAME), labels=sh@data$SBWAY_NAME)

m

# Save the output
saveWidget(m, file="TTC_leaflet_map.html")