I have tried searching for an answer to this question and came across this :
Manually adding legend values in leaflet
But this isn't quite what I would like as the leaflet map displays the breaks I want however when I try adding them to the legend using the pal = I get an error
I have used the ClassInt package in R to find the jenks natural breaks in my data as follows:
[0,3] (3,8] (8,16] (16,32] (32,70]
759 505 290 138 29
and then use findColours to and the RcolourBrewer package:
cols_code <- findColours(cols_classes, brewer.pal(5,"YlGnBu"))
When I use this in my leaflet map it works fine and displays the colours thematically by polygon as I want:
leaflet() %>%
addProviderTiles("CartoDB.Positron") %>%
addPolygons(data = foo,
fillColor = cols_code,
fillOpacity = 0.9,
color = "white",
weight = 1)
But when I try to add a legend using this object I get an error:
addLegend(pal = cols_code,
values = foo$bar,
title = "title",
labFormat = labelFormat(suffix = " things"),
opacity = 0.9)
Error in if (type == "numeric") { : argument is of length zero
I have tried using the leaflet colorBin and colorNumeric instead but they do not seem to recognize my breaks and instead overwrite into their own intervals in the legend and in the thematic.
Any suggestions welcome, I want to avoid converting them into a factor if possible as I can see that both findColours and colorBin functions have palettes attached to them but it only seems to look it up for the leaflet colorBins/numeric.
Without a reproducible example it is not easy to know what exactly you want. But try:
pal2 <- leaflet::colorBin(palette = col.regions,
bins = length(at),
domain = at,
na.color = na.color)
where col.regions
is a function to generate colors (e.g. some colorRampPalette
or viridis
), at
are your breaks and na.color
is some color for NA
values.
Then you can do:
leaflet::addLegend(map = m,
pal = pal2,
opacity = 1,
values = at,
title = "someTitle")
We use this in mapview so that we can do:
mapview(breweries91, zcol = "founded",
at = seq(1400, 2300, 300), legend = TRUE)
You coud obviously use mapview which will handle this for you.