It has been possible for some years to launch a web map from within R. A number of packages for doing this are available, including:
The best tutorial resource I have found on leaflet is this vignette by Joe Cheng and Yihui Xie. Building on their excellent description, this article explains some of the fundamentals of the package.
Because leaflet is new, it’s not yet on CRAN. Even when it does appear, installing from github may be a good idea, to ensure you have access to the latest features and bug fixes. Here’s how:
To create an interactive web map with leaflet is incredibly easy. Having installed the package try this single line of code:
Adding basic features to your webmap is easy. The
%>% ‘pipe’ operator
used extensively in dplyr
and developed for the
means we can finally escape from dozens of nested bracketted commands.
(If you use RStudio, I suggest trying the
Ctl+Shift+M to produce this wonderful operator.)
leaflet settings and functionality can thus be added sequentially, without
requiring any additional brackets!
To add a location to the map
m, for example, we can simply pipe
This way we can gradually add elements to our map, one-by-one:
In the previous example, we added some random data that we created locally, inside the function call. How do we use real, large datasets in leaflet? The package provides 3 options:
Let’s try adding a bicycle route, one that I followed with some friends to move from Sheffield to my current home of Leeds. First download some data:
Now we can load this as a
SpatialLinesDataFrame and display in leaflet:
Note in the above example that we had to use the argument
data = to
refer to our spatial object: it cannot simply be inserted without specifying
what it is. The
data argument can also be placed inside the initial
leaflet() function call.
leaflet is developed by the same team who develop shiny so the two are well integrated. Below is a very simple example, modified slightly from the package’s vignette:
leaflet is a powerful and flexible R package. If I were to offer
one critique, it would be that I could find no easy way to allow the user
to query the data objects loaded. plotly, for example, provides a
description of any visual object the user clicks on.
The datashine commuter visualisation,
for example allows users to click on any point, resulting in a burst of lines
emenating from it. This would also be possible in leaflet/shiny, but the
best implementation is not immediately clear, to me at least!
The wider context of this article is the pressing need for better transport planning decision making, to enable a transition away from fossil fuels. To this end, the ‘propensity to cycle’ project, funded by the UK’s Department for Transport, seeks to create an interactive tool to identify where new bicycle paths are most needed. There are clearly many other uses for R’s leaflet package: what will you use it for? Let me know at @robinlovelace.