reverse order in R leaflet continuous legend

2019-05-02 00:07发布

问题:

I am trying to reverse the value display of my leaflet legend in R. This post covers categorical data, but I am working with continuous data. Here's a toy example:

map <- leaflet() %>% addProviderTiles('Esri.WorldTopoMap')
x <- 1:100
pal <- colorNumeric(c("#d7191c","#fdae61","#ffffbf","#abd9e9", "#2c7bb6"), x)
map %>% addLegend('topright', pal=pal, values=x)

I'd like the legend to read 100 at the top and 1 on the bottom with the colors reversed. I can certainly reverse the colors in colorNumeric(), but reversing the order of the labels is harder. I have tried reversing the order of the values in x, and I even fiddled with the labelFormat() parameter for addLegend() to reference a lookup table of reversed values... nothing seems to work. Is there an easy way to do this?

回答1:

I just found that the built-in labelFormat function has a transform parameter that takes a function. So I passed the sort function in there. To use the same example,

map %>% addLegend('topright',
              pal = pal, 
              values = x, 
              labFormat = labelFormat(transform = function(x) sort(x, decreasing = TRUE)))


回答2:

Update

Use the answer by Jake. This one should no longer be the 'accepted' one.


I have a feeling there's a simpler way. However, taking my solution from this other question you can create your own label format and use that

However, you may want to play with the cuts as it leaves the space above 100

library(leaflet)

map <- leaflet() %>% addProviderTiles('Esri.WorldTopoMap')

x <- 1:100
## I've reversed the order of the colours too
pal <- colorNumeric(rev(c("#d7191c","#fdae61","#ffffbf","#abd9e9", "#2c7bb6")), x)

## custom label format function
myLabelFormat = function(..., reverse_order = FALSE){ 
    if(reverse_order){ 
        function(type = "numeric", cuts){ 
            cuts <- sort(cuts, decreasing = T)
        } 
    }else{
        labelFormat(...)
    }
}

map %>% addLegend('topright',
                  pal = pal, 
                  values = x, 
                  labFormat = myLabelFormat(reverse_order = T))



标签: r leaflet legend