0

I have exactly the same question as this one from 5 years ago. I want to invert the scale of a continuous color scale in a leaflet choropleth created from R. I'm hoping that there is a better answer available now, than then.

reverse order in R leaflet continuous legend

Here is my code: (dput()ed data available here: https://drive.google.com/file/d/1asaNqvtm0VXGH-o7GoWVd3Q6FSm1RNES/view )


pal <- colorNumeric("magma", NULL)

map.positivity.leaflet <-
    leaflet(data=D) %>%
    setView(lng=-72.8, lat=41.5, zoom=9) %>%
    addPolygons(color="lightgrey",      # stroke color
                stroke = TRUE,
                weight = 1.5,           # stroke
                fillColor = ~pal(town.positivity),
                fillOpacity = 1,
                label = ~text,
                labelOptions = labelOptions(textsize = "15px", ## could also set "font-size" in 'style' arg
                                            style = list( # add custom CSS
                                                "background-color" = "darkgreen",
                                                "color" = "white" # font color
                                            ))) %>%
    addLegend(
        "bottomright",
        pal = pal,
        values = ~town.positivity,
        title = "<b>Test Positivity (%)</b>",
        opacity = 1
    )


Here is what I get:

choropleth with inverted colorscale

I want the colorscale to run from 0 at the bottom to its maximum at the top. Is there a less kludgy way to do that than available in answers to the 5 year old question cited above?

Dave Braze
  • 441
  • 3
  • 14
  • Could you please share your data using `dput()`? – Quinten Mar 30 '22 at 17:05
  • @quinten the data is too big to include on so. Here is the dput()ed data on google drive: https://drive.google.com/file/d/1asaNqvtm0VXGH-o7GoWVd3Q6FSm1RNES/view?usp=sharing . Or, see complete code and data here: https://github.com/davebraze/ct-covid-map-examples/ . See especially the file https://github.com/davebraze/ct-covid-map-examples/blob/master/ct-covid-map.R – Dave Braze Mar 30 '22 at 17:30
  • Have you tried adding: labFormat = labelFormat(transform = function(x) sort(x, decreasing = TRUE)) to addLegend()? – Susan Switzer Mar 30 '22 at 19:03
  • Hi @SusanSwitzer, thank you for weighing in. Your suggestion does have the effect of reversing the labels, but since it does not change the actual mapping from colors to values, that means that the colorscale is not just "upside down", but it is now also incorrect. This is detailed in the 5 year old question that I cited in my own question. – Dave Braze Mar 31 '22 at 01:32

0 Answers0