5 mapdeck

mapdeck is an R-package that allows you to create interactive maps using mapbox GL and deck.gl. Mapbox is a location data platform that can be used to create various applications. Deck.gl is a framework for visualizing large datasets. To use mapdeck, a Mapbox token is required. To obtain a Mapbox token, you must create a free Mapbox account at https://www.mapbox.com. After you have received your token, you can either set it globally with set_token() or you can set it manually for each plot with the token argument.

# for loading our data
library(sf)
# for datasets
library(nycflights13)
# for plotting
library(mapdeck)
library(RColorBrewer)
# for data wrangling
library(dplyr)

5.1 Data used

In this chapter we will use three datasets. The first two are both taken from OpenStreetMap and contain the road network of Hamburg and locations of bakeries in Europe. We will also use a dataset from the package nycflights13, which contains all flights from New York airports in 2013.

roads_hamburg <- read_sf("hamburg.shp")
bakeries <- read_sf("bakeries.kml")
# count the number of flights from each origin to each destination
flights_grouped <- flights %>%
  count(dest, origin)
colnames(airports)[1] <- "dest"
# join the flight data with the coordinates of the destination airports
flights_grouped <- flights_grouped %>%
  right_join(airports[, c(1, 3:4)])
colnames(flights_grouped)[4:5] <- c("lat_dest", "lon_dest")
colnames(airports)[1] <- "origin"
# join the flight data with the coordinates of the origin airports
flights_grouped <- flights_grouped %>%
  right_join(airports[, c(1, 3:4)])
colnames(flights_grouped)[6:7] <- c("lat_origin", "lon_origin")
# remove NAs
flights_grouped <- flights_grouped[!is.na(flights_grouped$dest), ]

5.2 Using mapdeck to create maps

If you create a map with mapdeck, you can define a basemap style using mapdeck_style(). If you do not define a style, a default mapbox style is used. To create a map, start with mapdeck() and then add layers using the pipe operator %>%. For instance, we can visualize our flight data by adding an arc layer that represents the flight routes as raised arcs.

ms <- mapdeck_style("satellite")
mapdeck(data = flights_grouped, style = ms, pitch = 30, token = token) %>%
  add_arc(
    # coordinates of origin airports
    origin = c("lon_origin", "lat_origin"),
    # coordinates of destination airports
    destination = c("lon_dest", "lat_dest"),
    # color our strokes depending on the number of flights
    stroke_from = "n",
    stroke_to = "n",
    palette = "viridis",
    legend = TRUE
    ) %>%
  # set the view
  mapdeck_view(
    location = c(-110, 48),
    # set the zoom level
    zoom = 2,
    # set the pitch angle
    pitch = 45,
  )