Manipulating the leaflet legend may seem impossible as it's rendered with an <svg>
element and several other <divs>
. However, a potential solution involves creating a new legend using tags$ul
and tags$li
.
A new function called legend
was developed to generate HTML markup for a legend using colorNumeric
and a set of values (utilizing quakes$mag
in the provided example). The resulting markup is an unordered list represented by <ul>
. List items are dynamically generated based on the specified number of bins
, typically defaulting to 7. The code snippet utilized to create a sequence of colors is adapted from the R Leaflet package: https://github.com/rstudio/leaflet/blob/master/R/legend.R#L93.
The left and right titles can be customized using the input arguments left_label
and right_label
. Background colors are defined through the style
attribute while other styles are determined via tags$style
.
For instance:
legend(
values = quakes$mag,
palette = "BrBG",
title = "Magnitude",
left_label = "0%",
right_label = "100%"
)
#
# <span class="legend-title">Magnitude</span>
# <ul class="legend">
# <li class="legend-item ..."> 0%</li>
# <li class="legend-item ..." style="background-color: #543005; ..."></li>
# ...
To display the legend in the application, you'll need to create an output element in the UI. This can be accomplished using absolutePanel
to position the legend at the bottom-right corner and defining a uiOutput
element.
absolutePanel(
bottom = 20, right = 10, width: "225px;",
uiOutput("map_legend")
)
In the server logic, replace the code within if (input$colors)
block with:
if (inputs$colors) {
output$map_legend <- renderUI({
legend(...)
})
}
An additional condition has been included to render a blank element if the option remains unticked. For more clarity, refer to the following screenshot followed by the provided example.
The only unresolved aspect is how to link the legend color scale with the circles.
If you have any queries, feel free to ask!
Screenshot
https://i.sstatic.net/0Lrvl.png
Example
(Provided full script is not displayed here due to space constraints)