'Logarithmic scale for leaflet legend and color palette

I am plotting GIS data using leaflet in R and I am setting the colour of the plotted points to a value in the data set. The data values span a wide range and it is important to distinguish colour differences at the lower end of the values but also important to differentiate the higher values. To get the effect I'm looking for, I need to be able to use a logarithmic scale to determine the colours of the points and the legend scale.

The code below gives an example of the data and the way in which I'm plotting it now but I don't know how to use a logarithmic scale for the colours and the legend.

# Some fake data
df <- sp::SpatialPointsDataFrame(
  cbind(
    (runif(100) - .5) * 10 - 90.620130,  # lng
    (runif(100) - .5) * 3.8 + 25.638077  # lat
  ),
  data.frame(testData = rexp(100, rate = 5) * 1000)
)

# Fomulate a colour palette
pal <- colorNumeric(
  palette = "YlGnBu",
  domain = df$testData
)

leaflet(df) %>% addTiles() %>%
  # Add circle markers coloured by the testData
  addCircleMarkers(fillColor = ~pal(testData), fillOpacity = 0.7, radius=6, stroke=FALSE) %>%
  # Add the legend
  addLegend("bottomright", pal = pal, values = ~testData,
    title = "Test Result",
    opacity = 1
)

Can anyone suggest how I could do this?



Solution 1:[1]

You could do this:

 pal <- colorNumeric(palette = "YlGnBu",domain = log10(df$testData))

 leaflet(df) %>%
 addTiles() %>% 
addCircleMarkers(
fillColor = ~pal(log10(testData)), 
fillOpacity = 0.7, 
radius=6, 
stroke=FALSE) %>% 
addLegend("bottomright", 
pal = pal, 
values = ~log10(testData),
 title = "Test Result",
 opacity = 1)

So, you could put log10() in 3 places above to get log scale color differentiation, however this leaves legend also in log scale which is not really friendly for most people? Did you find an answer, or anybody else?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kosk