Brandon Walker

Data Scientist

Tutorial: Mapping in R with Leaflet

8 minutes
October 27, 2019

At the most recent datathon I was at of the few people who asked me for help, a lot of them wanted help creating maps. Additionally, I am getting bored with plotting in R, and I think other people are too. Making use of JavaScript adds interactivity to your plots keeping them interesting for the people that have to look at them.

I’ll be covering the htmlwdigets package from R over the course of the next few tutorials. This first one is about leaflet.

To show how it works and some of its features, I have a data set containing a few of the museum’s I have visited recently. I will be using the pipe operator frequently, if you need a refresher on that check out my earlier post.

Step 1: Install Packages

Run this in your console in R Studio.

# tidyverse is a meta-package with lots of useful packages and functions
install.packages("tidyverse")
# htmlwidgets is a meta-package that contains leaflet
install.packages("htmlwidgets")

Step 2: Load Packages

From here on out we will be running this code in your script file.

library(tidyverse)
library(leaflet)

Step 3: Load Data

museum <- read_csv("museum.csv")
## Parsed with column specification:
## cols(
##   museum = col_character(),
##   lat = col_double(),
##   lng = col_double(),
##   `Presidential Library` = col_character()
## )

Step 4: Add Tiles

Step 4A: First we have to pass our data into the leaflet function, using the pipe. This alone won’t make a map.
Step 4B: Pick out tiles (what the map looks) like at this link.
Step 4C: Pass the output of the leaflet function into the addProviderTiles() function, with the only argument being the tiles you selected in step 3B. I picked Stamen.TonerLite.

museum %>%
leaflet() %>%
addProviderTiles(providers$Stamen.TonerLite)

Step 5: Add Multiple Tiles

Step 5A: Select another set of tiles you want to add.
Step 5B: Give each of the groups names with the group argument, I selected Esri.WorldImagery.
Step 5C: Add layer control (this enables you to see both tiles). You’ll be able to select the tiles you want to view in the top right corner

museum %>%
leaflet() %>%
addProviderTiles(providers$Esri.WorldImagery, group = "World Imagery") %>%
addProviderTiles(providers$Stamen.TonerLite, group = "Toner Lite") %>%
addLayersControl(baseGroups = c("Toner Lite", "World Imagery"))

Step 6: Use Data to Add Markers to the Map

Step 6A: Use the addMarkers() function, if your data set has latitude and longitude (or an abbreviation of them) you don’t need to fill out the argument for lat and lng.
Step 6B: You can optionally set the label and popup to display information when you hover your mouse over the marker or click it.

museum %>%
leaflet() %>%
addProviderTiles(providers$Esri.WorldImagery, group = "World Imagery") %>%
addProviderTiles(providers$Stamen.TonerLite, group = "Toner Lite") %>%
addLayersControl(baseGroups = c("Toner Lite", "World Imagery")) %>%
addMarkers(label = museum$museum, 
           popup = ifelse(museum$`Presidential Library`=="Yes",
                          "A Presidential Library", # Value if True
                          "Not a Presidential Library")) # Value if False
## Assuming "lng" and "lat" are longitude and latitude, respectively

Step 7: Add Clusters

This is a good thing to do if you have lots and lots of data points, so that your chart doesn’t get overwhelmed. It’s also good to do if you have points that are very close together. All we need to do is update our addMarkers() function with the clusterOptions argument.

museum %>%
leaflet() %>%
addProviderTiles(providers$Esri.WorldImagery, group = "World Imagery") %>%
addProviderTiles(providers$Stamen.TonerLite, group = "Toner Lite") %>%
addLayersControl(baseGroups = c("Toner Lite", "World Imagery")) %>%
addMarkers(label = museum$museum,
           clusterOptions = markerClusterOptions(),
           popup = ifelse(museum$`Presidential Library`=="Yes",
                          "A Presidential Library", # Value if True
                          "Not a Presidential Library")) # Value if False
## Assuming "lng" and "lat" are longitude and latitude, respectively

Step 8: Set Map View

This step is by no means required, but if you want to focus your map on a specific location to start with, you can use the setView() function. I’ll focus in on Atlanta

museum %>%
leaflet() %>%
addProviderTiles(providers$Esri.WorldImagery, group = "World Imagery") %>%
addProviderTiles(providers$Stamen.TonerLite, group = "Toner Lite") %>%
addLayersControl(baseGroups = c("Toner Lite", "World Imagery")) %>%
addMarkers(label = museum$museum,
           clusterOptions = markerClusterOptions(),
           popup = ifelse(museum$`Presidential Library`=="Yes",
                          "A Presidential Library", # Value if True
                          "Not a Presidential Library")) %>% # Value if False 
setView(lat = 33.736309, lng = -84.388298, zoom = 11)
## Assuming "lng" and "lat" are longitude and latitude, respectively

Step 9: Add a Minimap

Too add a minimap to our htmlwidget, we just need to use the addMiniMap() function. Two arguments you can adjust with addMiniMap() are changing the tiles, and toggleDisplay.

museum %>%
leaflet() %>%
addProviderTiles(providers$Esri.WorldImagery, group = "World Imagery") %>%
addProviderTiles(providers$Stamen.TonerLite, group = "Toner Lite") %>%
addLayersControl(baseGroups = c("Toner Lite", "World Imagery")) %>%
addMarkers(label = museum$museum,
           clusterOptions = markerClusterOptions(),
           popup = ifelse(museum$`Presidential Library`=="Yes",
                          "A Presidential Library", # Value if True
                          "Not a Presidential Library")) %>% # Value if False 
setView(lat = 33.736309, lng = -84.388298, zoom = 11) %>%
addMiniMap(
    toggleDisplay = TRUE,
    tiles = providers$Stamen.TonerLite,
    )
## Assuming "lng" and "lat" are longitude and latitude, respectively

This does not show every single leaflet feature, but it should give you a good start to get whatever you need done. A great tutorial in my opinion is this one.