Leaflet Legend Items Are Not Displayed (Aligned) Correctly in Shiny
Asked Answered
K

2

3

I am rendering some leaflet maps in my shiny app and the problem is that the legend of the map is not displayed correctly and legend items are aligned very weirdly (image 2). I create the same map in R studio and in the Rstudio Viewer, legend items alignment is correct (image 1).
I have tried using CSS tags in my shiny code to customize the legend, but nothing works.

This it how the legend looks in viewer when I create the leaflet map in rstudio

This is how it looks in browser via shiny app

Here is sample code to show how I am rendering leaflet plot (and also the CSS tags examples I've tried). I dont know why the items are displayed like this. I would really appreciate your help on this.

...
tabPanel("plot", 
  tagList(
    tags$head(
      tags$style(
         ".leaflet .legend {width:200px; text-align: left;}",
         ".leaflet .legend i{float: left;}",
         ".leaflet .legend label{float:left; text-align: left;}"
       )
     )
  ),

  leafletOutput("leaflet_plot", width = 800, height = 550)
)
...

# code to create leaflet
output$leaflet_plot <- renderLeaflet({
  pal <- c("#F1F1F1", brewer.pal(5, "YlOrBr"))
  opts <- providerTileOptions(opacity = 0)
  map <- leaflet(shape_file) %>% addProviderTiles("CartoDB.PositronNoLabels", options = opts)
  map <- map %>% addPolygons(fillColor = ~colorFactor(pal, shape_file$var)(var)
  map <- map %>% addLegend("bottomleft", title = "Employment/Acre", pal = colorFactor(pal, NULL), values = ~var)
  map
})
Karate answered 21/6, 2016 at 17:37 Comment(2)
Please post a reproducible example.Owlet
Same problem, added this to my CSS as referenced below by Adam: div.info.legend.leaflet-control br { clear: both; }Nevins
F
1

Adding this CSS rule worked for me in a leaflet map inside a quarto report.

.info.legend.leaflet-control i {
  float: left;
}

If I was you I would open up your shiny app in the browser and right click on the ill-formatted legend and click 'inspect'. You can play around with the css there until you get it to work for you use case. Note the alternative css trick in this duplicate post.

Flocculent answered 28/6, 2023 at 4:8 Comment(0)
K
0

This may happen if the zoom level of the browser is more than 100%. Look at this duplicate post that has a reproducible example.

Katzir answered 15/8, 2016 at 16:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.