So, you want to build interactive maps with R? It’s harder than it seems, we know. First, you need to choose a library from an extremely competitive open-source market. Welcome to the paradox of choice. Then the real problems begin. Where do you position your map? How much zoom is enough? What about the colors? These are just a couple of questions you need to find the answer to.
Today we’ll compare two libraries used to build interactive maps with R and R Shiny. These are Leaflet and Tmap – two very promising options made for different use cases. You’ll learn how to work with both, and how to embed them in R Shiny dashboards.
Interested in building interactive Google Maps? Check our comprehensive guide to get started.
Table of contents:
- Build Interactive Maps with R and Leaflet
- Build Interactive Maps with R And Tmap
- Add Interactive Tmap and Leaflet Maps to R Shiny Dashboard
Build Interactive Maps with R and Leaflet
If you’re following along, make sure to have Leaflet installed. You can install it like any other R package (install.packages(“leaflet”)). For the data source, we’ll use the List of US Airports dataset from Kaggle. Download it and extract the CSV before proceeding.
Once in RStudio, create a new R Script and paste the following code – it takes care of library imports, dataset loading, and variable setup needed for later:
Here’s how the first couple of dataset rows look like:
From here, you can proceed to build interactive maps with R and Leaflet. The first one will be rather simple – containing markers, popups, and labels for every US airport. You can use the
addMarkers() function to add a marker based on latitude and longitude info from the dataset:
Not too bad for your first Leaflet map! But there’s a lot we can improve. For example, you can use the
addProviderTiles() function to change the default visuals of your map. We found
Esri.WorldStreetMap to be just the right balance of color-punchy and minimalistic:
Not bad, but the markers are a bit boring. As it turns out, you can use the
makeIcon() function to replace the default marker with any PNG image – both local and online. Font Awesome’s GitHub repo contains this plane image in PNG format, and you only need the URL to use it.
Don’t forget to specify the
icon parameter inside the
addMarkers() function, otherwise you’ll be stuck with the default one:
That’s much better. You might want to play with the opacity further, but this is enough for what we need today. As it turns out, that’s the map we’ll embed to an R Shiny dashboard later. But first, let’s see how you can build interactive maps with R and Tmap.
Looking for a more detailed Leaflet guide? Check our complete Leaflet guide built on the earthquake dataset.
Build Interactive Maps with R and Tmap
Tmap is something else. It stands for Thematic Maps and provides a flexible way to visualize spatial data. It’s not the most intuitive package, which is problematic as most of the available guides are somewhat outdated and don’t cover what you would expect.
However, there are numerous ways to get started with Tmap. We’ve found the most user-friendly method to be by downloading a Shapefile (.shp) first. Our dataset contains US airports, so you’ll have to find a Shapefile with US geopolitical boundaries first. We found this one on GitHub. You can clone the repo if you’re following along and extract the ZIP file.
You’ll have to load three libraries and a Shapefile to get started:
Let’s first visualize the Shapefile to see what we’re working with:
That’s fundamentally different from Leaflet. We don’t see a map of the entire world, but only the area of interest instead. You’ll see later how to add the above layer to an interactive map, but let’s go over the basics first.
You’ll have to create an additional dataset in Tmap-approved format before you can add markers to the map. That dataset will have coordinate data explicitly declared. For simplicity’s sake, we’ll only subset our US airports dataset. You can then add and customize markers. We’ll start with simple black dots:
We’re getting there. The only thing left to do is to replace black dots with the plane icons. It’s somewhat easier to do this in Tmap than it was in Leaflet. Don’t forget to specify
border.lwd = NA inside
tm_symbols(), as otherwise, you’ll get a border around every marker icon:
That’s much better and more appropriate for our dataset. But do you know what the best part is? You can use the
tmap_leaflet() function to add the above Tmap layer to an interactive Leaflet map:
R Shiny will automatically make this conversion for you, as you’ll see in the next section. We now have everything needed to create an interactive R Shiny dashboard from these two maps.
Add Interactive Tmap and Leaflet Maps to R Shiny Dashboard
It’s no secret that we love dashboards at Appsilon. We think they provide the best way for users to interact with data, and to pinpoint areas of interest. The one you’ll see below allows the user to specify a list of states from which the airports are displayed.
Keep in mind:
- App UI – Use the
tmapOutput()functions to declare placeholders for our two maps.
- App Server – Use the
renderTmap()functions to display the maps. The data is prepared earlier as a reactive component to match the user-selected states.
Here’s the entire code:
The only new thing we’ve added here is a call to the
tm_view() function while rendering the Tmap map. It centers the map to a custom latitude, longitude, and zoom level. Everything else was discussed earlier in the article. Overall, we have a decent-looking map with less than 70 lines of code!
Learn how to use R to analyze large geolocation databases and build a Corona Risk heat map – CoronaRank.
You could take the dashboard to new heights by speeding it up and tweaking the visuals. Here’s a couple of resources to follow if you’re up for a challenge:
Today you’ve learned how to build interactive maps with R and R Shiny, which is no small achievement. You now know how both Leaflet and Tmap work, but we think there’s still room for improvement. Here are a couple of challenges you can do next:
- Change the coloring on the Tmap map to match what we had with Leaflet
- Add a dark theme to the Leaflet map
- Color individual states on the Tmap map based on the number of airports they have
Reference the official documentation for Leaflet and Tmap if you decide to work on these challenges. Feel free to share results with us on Twitter – @appsilon. We’d love to see what you came up with.
If you’re looking for a faster way to showcase your map online, check out our Shiny Dashboard Templates. They’re free to use and a great launching point for your project.