leaflet icon indicating copy to clipboard operation
leaflet copied to clipboard

How to change Legend font-size and alignment ?

Open prateekjoshi565 opened this issue 8 years ago • 4 comments

Is there any way to change the font-size in leaflet legend and also change its alignment?

prateekjoshi565 avatar Jan 30 '18 10:01 prateekjoshi565

Although the question is two years old, I want to answer the question as it is the first hit by Google when searching for "leaflet legend font size".

Consider the following example code

leaf <- leaflet() %>% 
    addTiles() %>% 
    addLegend(
        position = "bottomright",
        colors = rgb(t(col2rgb(palette())) / 255),
        labels = palette(), opacity = 1,
        title = "An Obvious Legend"
    )

Then we can change the font size by using

browsable(
   tagList(
      list(
         tags$head(
            tags$style(
               ".leaflet .legend {
                 line-height: 30px;
                 font-size: 30px;
                 }",
              ".leaflet .legend i{
                width: 30px;
                height: 30px;
                 }"
            )
         ),
       leaf)))

Several things happen here. It is obvious what the font-size argument does. The line-height should be adjusted, otherwise there is not enough space for the labels of the legend. The arguments in the ".legend i{}" control affect the size and form of the colored boxes. If the sizes of the boxes (or alternatively the spacing between the boxes) are not adjusted, the space between the labels is not sufficient For me this was the easiest way to increase the font size of the legend without changing its default appearance.

jofie avatar Jan 09 '20 11:01 jofie

@jofie Hi! Thanks for providing the solution! I am using Leaflet in R. I am still confused that where should I put your codes. Is it somehow to be inserted into addLegend function? Run outside of the leaflet package? Can you provide some guidance?

xiaofanliang avatar Mar 16 '20 20:03 xiaofanliang

Looking for the same solution and found this thread.

@xiaofanliang The code is meant to be run-as (don't modify your leaflet object) so that it can be previewed using RStudio's html display capabilities (assuming you're using RStudio). If you are creating a Shiny App, then you would put that code in the header or a CSS file.

bbass444 avatar Mar 26 '20 01:03 bbass444

Also looking for a similar solution and this was the first google result. In my case I want to increase the space between the color blocks that identify the legend colors. When I increase the line-height the labels get spaced, but the blocks remain squished next to each other.

I'd like there to be whitespace between the blocks where the arrows are:

image

jzadra avatar Dec 13 '21 17:12 jzadra