rvisualizationgeospatiallayerr-leaflet

Map vector group in specific order


I have a shapefile with polylines of routes in different years. Here is an example data shapefile with routes in the year 2000 and year 2013. I would like the map to show the older routes at the top and more recent routes at the bottom. I've had a look at the addMapPane function but not sure how to apply it for a vector in the same file. Here is my code so far:

sample_palette <- leaflet::colorFactor(palette = rainbow(2), 
                                domain = data_sample$Year)


sample_plot <- leaflet(data_sample) %>% 
  addProviderTiles("CartoDB.Positron") %>% 
  addPolylines(color = ~sample_palette(Year), 
               opacity = 1) %>% 
  leaflet::addLegend(values = ~Year, 
                     opacity = 1, 
                     pal = sample_palette, 
                     title = "Routes")

sample_plot

Solution

  • Please find one possible solution to get the older routes on top of recent routes: just need to change the order of rows in data_sample

    library(sf)
    library(leaflet)
    
    data_sample <- st_read("ADD YOUR PATH HERE")
    
    # Order 'data_sample' rows in decreasing order of 'Year' 
    data_sample <- data_sample %>% 
      arrange(., desc(Year))
    
    # Choose colors
    sample_palette <- leaflet::colorFactor(palette = rainbow(2), 
                                           domain = data_sample$Year)
    
    # Build the map
    sample_plot <- leaflet(data_sample) %>% 
      addProviderTiles("CartoDB.Positron") %>% 
      addPolylines(color = ~sample_palette(Year), 
                   opacity = 1) %>% 
      leaflet::addLegend(values = ~Year, 
                         opacity = 1, 
                         pal = sample_palette, 
                         title = "Routes")
    
    sample_plot
    

    enter image description here