How to change Legend font-size and alignment ?
Is there any way to change the font-size in leaflet legend and also change its alignment?
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 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?
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.
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:
