Visualising data is an important part of the data science life cycle and any data scientist should know how to create good visualisations of different types of data. Recently I have been working with a lot of geospatial data which has meant that I’ve been putting some time into learning about plotting maps with R.
In my opinion one of the best R packages for doing this is ‘Leaflet’. Leaflet is actually an open-source JavaScript library for interactive maps. However, for the R user a package has been written that will allow you to integrate and control Leaflet maps through R.
Leaflet maps can be simply integrated into Shiny applications as any other visualisation, with renderLeaflet in the server function and leafletOutput in the user interface function.
To show just a couple of the things that I have liked about using Leaflet in Shiny I have created a small app (my code is available here if you want to have a play around yourself) using the City of York Council Road Safety data (link here). This data gives information of over 5000 personal injury accidents on public roads in York that are reported to the police, including the longitude and latitude coordinates.
The Shiny app shows the location of accidents on the map and a histogram of accident counts per day of the week. The app showcases how leaflet and Shiny can interact with each other in two ways. The first case shows how a Shiny input function can control what is shown on the map. The relevant server code, below, shows how the value of input$severity determines which accidents are passed to the leaflet function through the reactive accidentSeverity.
The second interaction shows how the map bounds can be used to control the output of other parts of the Shiny app. In this case the histogram automatically re-plots depending on which accidents are within the current map bounds. The relevant server code for this is shown below.
Note how the accidentsInView reactive defines an input called map_bounds which is used to filter the dataframe for the accidents that are currently being shown on the map. The input$map_bounds is a kind of special case for Leaflet map events, which usually send input to Shiny following the general pattern of input$MAPID_OBJCATEGORY_EVENTNAME, where MAPID is the map’s name (i.e. just “map” in this example), OBJCATEGORY could be a shape or marker on the map and EVENTNAME a mouse click or mouse hover.
I'm hoping to keep exploring Leaflet maps and their application in Shiny so keep an eye out for another article. In the mean time check out the Shiny Gallery, particularly the SuperZip example, which was a great help to me in learning how to use the Leaflet input events.