Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change legend text formatting in Leaflet in R?

I've created a leaflet map and I'm trying to figure out how I can change the formatting of the legend labels. I currently have a gradient color palette to represent the data, with a set of discrete labels. Basically, the current output has the numbers aligned above the tick marks, and I would like them to be centered with the tick mark and justified left. See this image for reference.

enter image description here

pal <- colorNumeric(
  palette = "YlOrRd",
  domain = dat$distance)

m <- leaflet() %>%
  addProviderTiles(providers$Esri.WorldGrayCanvas) %>%

  addCircleMarkers(data = dat, #eastbound colored circles
                   radius = dat$total_ridership, 
                   stroke = TRUE, 
                   color = ~pal(distance), fillOpacity = 0.8)  


ui <- fluidPage(
  leafletOutput(outputId = "map") 
)

server <- function(input,output){
  output$map = renderLeaflet ({
    m %>%      
        addLegend("bottomright", pal = pal, values = dat$distance, bins = c(0,200,400,600),
            title = "Distance (ft) to <br> nearest bus stop",
            opacity = .8)
   }) 
}

shinyApp(ui=ui,server=server)

I'm still confused on how to edit some of the more specific aspects of the leaflet output, especially with the legend. I've seen this post to make a custom legend based on circle sizes, as well as this on changing the format of time labels, but I'm not sure how to apply this information in my case to edit the legend label formatting -- e.g. changing the position of the text, alignment, etc.

like image 935
nkt95 Avatar asked Oct 19 '25 11:10

nkt95


1 Answers

Taking the example from Leaflet you can follow up map with htmlwidgets::onRender() -> query the document for all text elements below info.legend 1 and then change their text-anchor attribute 2. If you use any proxy layers in combinations with Shiny, make sure to re-apply this style similar to this

library(leaflet)
countries <- sf::read_sf("https://rstudio.github.io/leaflet/json/countries.geojson")
map <- leaflet(countries) %>% addTiles()

pal <- colorNumeric(
  palette = "YlGnBu",
  domain = countries$gdp_md_est
)

map %>%
  addPolygons(stroke = FALSE, smoothFactor = 0.2, fillOpacity = 1,
              color = ~pal(gdp_md_est)
  ) %>%
  addLegend("bottomright", pal = pal, values = ~gdp_md_est,
            title = "Est. GDP (2010)",
            labFormat = labelFormat(prefix = "$"),
            opacity = 1
  )%>% htmlwidgets::onRender("
    function(el, x) {
      var labels = el.querySelectorAll('.info.legend text'); // 1
      labels.forEach(function(label) {
        label.setAttribute('text-anchor', 'start'); // 2
        label.setAttribute('dx', '5'); // set left indentation [px]
      });
    }
  ")

Note: Have a look at labelFormat for things as prefix ($) / suffix.

out

like image 145
Tim G Avatar answered Oct 21 '25 01:10

Tim G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!