55 min read

Static and dynamic choropleth maps and more

by

Load packages

We will begin by loading the necessary packages for these analyses

library(sp)
library(sf)
library(osmdata)
library(tmap)
library(leaflet)
library(leaflet.extras)
library(lubridate)
library(ggplot2)
library(dplyr)
library(tibble)
library(purrr)
library(tidyr)

Download and load the administrative boundary data

In order to get the administrative boundaries for use in our plots, we use the getData() function from the raster package, which connects to the Global Administrative Areas spatial database of administrative boundaries. These can also be downloaded directly via the GADM website.

In this case, we will download the admin level 2 file for Sierra Leone, which will initially be stored as a SpatialPolygonsDataFrame. However, we will convert this to a simple features collection for easier data manipulation and plotting (see the simple features website for more details).

sle_sf <- 
  raster::getData('GADM', country = 'SLE', level = 2) %>% 
  st_as_sf()

Next, we simulate some case counts for each admin region, and store this as a variable “cases”.

# set.seed(1)
sle_sf <- 
  sle_sf %>% 
  mutate(
    cases = 
      nrow(.) %>% 
      rnorm(mean = 100, sd = 70) %>% 
      round() %>% 
      abs()
  )

Generating static maps

ggplot2::ggplot()

Choropleth using continuous case data

ggplot() +
  geom_sf(data = sle_sf, aes(fill = cases)) +
  scale_fill_viridis_c() +
  theme_minimal()

Point map using GPS coordinates of case-patients

First, we generate a simple features point pattern dataset using the ebola_sim$linelist simulated data found in the outbreaks package. We use the lon and lat variables for the coordinates.

ebola_sf <- 
  outbreaks::ebola_sim$linelist %>% 
  st_as_sf(coords = c("lon", "lat"), crs = 4326) 

ggplot() +
  geom_sf(data = sle_sf %>% filter(NAME_1 %in% c('Western'))) +
  geom_sf(data = ebola_sf, size = .01, colour = 'red') +
  theme_minimal()

tmap::tmap()

At present, ggplot2 is a bit slow to draw sf maps, so we can try using the tmap package which has some great defaults and plots static maps quite quickly.

sle_tmap <- 
  tm_shape(sle_sf) +
  tm_polygons("cases", palette = "Blues", title = "# cases") +
  tm_shape(ebola_sf) +
  tm_dots(color = 'red') + 
  tm_style_gray()

sle_tmap

Generating dynamic maps

tmap::tmap_leaflet()

A very quick and dirty way to create an interactive map would be to pass the sle_tmap object we created above to the tmap::tmap_leaflet() function:

tmap_leaflet(sle_tmap)