Drawing maps with R

Making maps in R

  • Spatial data comes with locations (perhaps with information about those locations).
  • A good way to draw spatial data is on a map.
  • The leaflet package is the easiest way to draw maps in R.
  • Install these two packages, with two familiar ones:
library(tmaptools)
library(leaflet)
library(tidyverse)
library(conflicted)
conflicts_prefer(dplyr::mutate)
conflicts_prefer(dplyr::arrange)

Hockey league map

The Ontario hockey divisions (the last example for cluster analysis) came with a very bad map. Can we do better?

  • reload the Ontario road distances
my_url <-
  "http://ritsokiguess.site/datafiles/ontario-road-distances.csv"
# my_url <- "ontario-road-distances.csv"
ontario <- read_csv(my_url)

Ontario road distances (some)

ontario

Grab the places

  • and append province (“ON”) for reasons shortly to become clear:
tibble(place = ontario$place) %>% 
  mutate(prov = "ON") %>% 
  unite(place1, c(place, prov), sep = " ") -> ontario2
ontario2

Geocode 1/2

  • find their latitudes and longitudes (“geocode”; slow).
  • Save the geocoded places.
ontario2 %>% 
  rowwise() %>% 
  mutate(ll = list(geocode_OSM(place1))) -> d
d

Geocode 2/2

Untangle the lats and longs:

d %>% 
  unnest_wider(ll) %>% 
  unnest_wider(coords) -> ontario3
ontario3

Make map

  • finally:
leaflet(data = ontario3) %>% 
  addTiles() %>% 
  addCircleMarkers(lng = ~x, lat = ~y) 

Cluster analysis revisited

ontario %>% select(-1) %>% as.dist() -> ontario.d 
ontario.hc <- hclust(ontario.d, method = "ward.D")

Seven clusters:

plot(ontario.hc)
rect.hclust(ontario.hc, 7)

Get the clusters

tibble(place = ontario$place, cluster = cutree(ontario.hc, 7)) -> clusters
clusters %>% arrange(cluster)

Combine clusters

  • combine clusters 6 and 7 with 4 (“north”)
  • combine clusters 2 and 3 (“east”)
  • make named divisions
clusters %>% 
  mutate(division = fct_collapse(factor(cluster),
                                "north" = c("4", "6", "7"),
                                "east" = c("2", "3"),
                                "west" = "5",
                                "central" = "1")) %>% 
  arrange(division) -> divisions

The divisions

divisions

Take “ON” off of ontario3

ontario3 %>% 
  mutate(place = str_replace(place1, " ON$", "")) -> ontario3
ontario3

Add the divisions, matching by place

  • and draw map
pal <- colorFactor("Set1", divisions$division)

ontario3 %>% left_join(divisions) %>% 
  select(place, x, y, division) %>% 
  leaflet() %>% 
  addTiles() %>% 
  addCircleMarkers(lng = ~x, lat = ~y, 
                   color = ~pal(division)) 

Original seven clusters

The same idea gets a map of the original seven clusters:

pal <- colorFactor("Set1", divisions$cluster)
ontario3 %>% left_join(divisions) %>% 
  select(place, x, y, cluster) %>% 
  leaflet() %>% 
  addTiles() %>% 
  addCircleMarkers(lng = ~x, lat = ~y, 
                   color = ~pal(cluster))