1

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

I am using leaflet and R.

1
  • Hi @lenlen. Welcome to SO! Please find below one possible answer to your problem. If it meets your needs, please consider marking it as "accepted" and/or "upvoted". If not, please tell me what is wrong. Cheers
    – lovalery
    Commented Jan 9, 2022 at 15:31

1 Answer 1

1

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

  • Code
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")
  • Visualization
sample_plot

enter image description here

2
  • thank you so much - this worked! Think I spent too much time overthinking it. Really appreciate it!
    – lenlen
    Commented Jan 9, 2022 at 15:46
  • Thank you very much for your feedback @lenlen. Glad that I could help you. I wish you the best in your work. Cheers.
    – lovalery
    Commented Jan 9, 2022 at 16:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.