Leaflet in R Markdown

Training for DEP Assessment and Monitoring Staff From a Safe Social Distance


  • So we’ve gone over code to pull data from SIS and clean/analyze the resulting dataset.
  • Now we’ll look at the R Markdown side to see how to present interactive maps that we created in ‘script_mapping.R’
  • When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document.
  • Note that the echo = T, eval = T options (set at top) cause all code to be displayed AND evaluated (unless otherwise specified in each code chunk)


Here is a map of total nitrogen concentrations at all samples I’ve collected since starting in January

TNdomain <- map_df %>% filter(param_lab == 'Tot. Nitrogen (mg/L)') %>% pull(mean_conc)
## filter (grouped): removed 68 rows (81%), 16 rows remaining
## define color palette
palTN <- colorNumeric(palette = "Blues", domain = TNdomain)

# create basic map
leaflet() %>%
  addProviderTiles(providers$Esri.NatGeoWorldMap, group = "Basemap") %>% # basemap
  
  addCircleMarkers(
    data = filter(map_df, param_lab == 'Tot. Nitrogen (mg/L)'),
    lng = ~ long, lat = ~ lat,
    col = ~ palTN(mean_conc), opacity = 1, 
    label = ~ MONITORING_POINT_ALIAS_ID,
    popup = ~ as.character(round(mean_conc, 1))) %>% 
  
  addLegend(pal = palTN, values = TNdomain, opacity = 0.8,
            title = 'Tot. Nitrogen (mg/L)')
## filter (grouped): removed 68 rows (81%), 16 rows remaining


This map is meh… don’t like the empty circles and the popup boxes aren’t informative


  • So let’s dress it up a bit by:
    • Improving appearance of the circle markers (filled), and
    • Expand content/format of pop ups
leaflet() %>%
  addProviderTiles(providers$Esri.NatGeoWorldMap, group = "Basemap") %>% # basemap
  
  addCircleMarkers(
    data = filter(map_df, param_lab == 'Tot. Nitrogen (mg/L)'),
    lng = ~ long, lat = ~ lat,
    fill = TRUE, fillColor = ~ palTN(mean_conc), fillOpacity = 0.8, # fill appearance
    radius = 10, # control size of points
    stroke = TRUE, 
    
    col = '#252525',  # dark outline for circles so they don't blend into bg
    weight = 2, # width of dark outline
    label = ~ MONITORING_POINT_ALIAS_ID,
    
    # enhance pop-ups:
    popup = ~ paste("<div class='leaflet-popup-scrolled' style='max-width:200px;max-height:250px'", 
                    '<br>',
                    '<b>', 'Tot. Nitrogen: ', '</b>', paste0(as.character(round(mean_conc, 1)), ' mg/l'), "<br>",
                    '<b>', 'n:  ', '</b>', n, "<br>",
                    '<br>',
                    '<b>', 'Alias:  ', '</b>', MONITORING_POINT_ALIAS_ID, "<br>",
                    '<b>', 'Site:  ', '</b>', MONITORING_POINT_NAME, "<br>",
                    '<b>', 'Location:  ', '</b>', SAMPLE_LOCATION, "<br>",
                    '<br>',
                    '<b>', 'SIS NHD ID:  ', '</b>', NHD_ID, "<br>",
                    '<b>', 'COM ID:  ', '</b>', FLOWLINE_COM_ID, "<br>",
                    '<b>', 'Latitude:  ', '</b>', lat, "<br>", 
                    '<b>', 'Longitude:  ', '</b>', long, "<br>")) %>% 
  
  addLegend(pal = palTN, values = TNdomain, opacity = 0.8,
            title = 'Tot. Nitrogen (mg/L)')
## filter (grouped): removed 68 rows (81%), 16 rows remaining


This map is definitely an improvement, but what about our other data?


Let’s add some other data as selectable layers (with reactive legends) and add an aerial base layer and a scale bar. Since the code required to do this is lengthy, refer to the script (‘script_mapping.R’) for specifics.


Since I saved the map as an object called final_map in the script, all I need to do is call that in this code chunk. Alternatively I could include all the code and override the options set at top with echo = F to tell R not to display the code.



Now that’s a map


We can switch between a basemap and aerial photo, turn layers on and off, while viewing their respective legends, and click on each point for additional information. This is a user-friendly way to communicate spatial data and allows users to interact as they wish.


Another strength is that Rmd files are saved as html files in your directory after pressing Knit, which can be saved/sent anywhere and opened in any web browser (but Chrome seems to work best).


An additional benefit is that Rmd html files can be easily published as a web page (on <www.rpubs.com>) directly from Rstudio.
* First, you must create an account on rpubs.com * The Rmd/html file size must be < 10MB! * Be aware that all rpubs.com is publicly accessible! + If your Rmd contains sensitive info just keep it as an html file and do not publish!




The Rmd shown here is just the tip of the iceberg.

  • You can include tables, images, figures genereted in R, and many other things in Rmd.
  • Similarly, the tutorial of leaflet is very basic
    • You can import GIS shapefiles into R and display them via leaflet (e.g. polygons and/or segment layers)
    • You can also create spatial objects from simple xy coordinate objects (e.g. spreadsheets) and export them to read into GIS



Biostatistics Ryan Gosling approves