Create a Legend on a Folium map

26,573

Solution 1

Folium now has a way to add an image easily with version 0.15.

from folium.plugins import FloatImage
image_file = 'image.PNG'

FloatImage(image_file, bottom=0, left=86).add_to(mymap)

Solution 2

You can add a legend quite easily;

#specify the min and max values of your data
colormap = branca.colormap.linear.YlOrRd_09.scale(0, 8500)
colormap = colormap.to_step(index=[0, 1000, 3000, 5000, 8500])
colormap.caption = 'Incidents of Crime in Victoria (year ending June 2018)'
colormap.add_to(world_map)

You can see my complete example here;

Folium Map with legend example

Solution 3

Try using

feature_group = FeatureGroup(name='Layer1')
feature_group2 = FeatureGroup(name='Layer2')

Then add to your map

map = folium.Map(zoom_start=6)

# coordinates to locate your marker
COORDINATE = [(333,333)] # example coordinate
COORDINATE2 = [(444,444)]

# add marker to your map
folium.Marker(location=COORDINATE).add_to(feature_group)
folium.Marker(location=COORDINATE2).add_to(feature_group2)

map.add_child(feature_group)
map.add_child(feature_group2)

# turn on layer control
map.add_child(folium.map.LayerControl())

Solution 4

You could get half the way with text/label color in the layer control, if you add html into the name parameter of a Marker or PolyLine:

import folium
print( folium.__version__)
import numpy as np

lon_ct = 50
fkt=10
num = 60
m = folium.Map((lon_ct, 6), tiles='stamentoner', zoom_start=6 )


lats = (lon_ct * np.cos(np.linspace(0, 2*np.pi, num))/fkt ) + lon_ct
lons = (lon_ct * np.sin(np.linspace(0, 2*np.pi, num))/fkt ) + 10
colors = np.sin(5 *    np.linspace(0, 2*np.pi, num))

lgd_txt = '<span style="color: {col};">{txt}</span>'

for idx, color in enumerate( ['red', 'blue']):  # color choice is limited
    print(color)
    fg = folium.FeatureGroup(name= lgd_txt.format( txt= color+' egg', col= color))
    pl = folium.features.PolyLine(
            list(zip(lats, lons - idx*fkt)),
            color=color,            
            weight=10, )
    fg.add_child(pl)
    m.add_child( fg)

folium.map.LayerControl('topleft', collapsed= False).add_to(m)
m

enter image description here

Source: html_legend

If you know a bit HTML:

item_txt = """<br> &nbsp; {item} &nbsp; <i class="fa fa-map-marker fa-2x" style="color:{col}"></i>"""
html_itms = item_txt.format( item= "mark_1" , col= "red")

legend_html = """
     <div style="
     position: fixed; 
     bottom: 50px; left: 50px; width: 200px; height: 160px; 
     border:2px solid grey; z-index:9999; 
     
     background-color:white;
     opacity: .85;
     
     font-size:14px;
     font-weight: bold;
     
     ">
     &nbsp; {title} 
     
     {itm_txt}

      </div> """.format( title = "Legend html", itm_txt= html_itms)
map.get_root().html.add_child(folium.Element( legend_html ))

Link basic

Link advanced


m.get_root().html
<branca.element.Element at 0x7f5e1ca61250>

https://pypi.org/project/branca/

  • for further manipulations

Solution 5

I was having the same issue and used this quick hack into the HTML generated by Folium to add a legend. It's not particularly graceful, but it works. Since I only needed this a few times, I manually generated the legend as an image (legend.png), but I imagine you could create a script to automatically create the legend if you were doing this often. I added the following components in the appropriate sections of the HTML file that Folium output my map to:

         <style> #background_img {
            position : absolute;
            background:url('legend.png');
            width : 16.9%;
            height: 17.7%;
            right: 20px;
            bottom: 50px;
            z-index: 99;
            background-repeat: no-repeat;
            background-size: contain; 
            }
        </style>

        <div id="background_img" class="backgroundimg" ></div>

You'll also need to change the z-index of the map style element to something less than 99, so that the legend is placed above the map.

Share:
26,573
sparrow
Author by

sparrow

I take large amounts of data and process it to gain insight and show patterns. I love my job :). My preferred tools are Python, Pandas, Plotly, Folium and Jupyter Notebooks. I'm always looking to grow my software skills. Right now I'm also learning Django. Undergrad - Electrical Engineering SDSU Grad - Hybrid EE/Comp Sci specializing in Wireless Embedded Devices UCSD.

Updated on July 10, 2022

Comments

  • sparrow
    sparrow almost 2 years

    The Folium documentation is incomplete at this time: https://folium.readthedocs.io/en/latest/

    According to the index of the incomplete docs Legends and Layers are, or will be supported. I've spent some time looking for examples on the web but have found nothing so far. If anyone has any idea how to create these things, or can point me to a document or tutorial I would be most grateful.

  • sparrow
    sparrow almost 7 years
    Thanks, that's not really a legend since it doesn't correlate the marker on the map with a particular thing, but it's still a helpful tip.
  • sparrow
    sparrow over 5 years
    Thanks @user, that is very useful, I was more so looking for a way to create a legend based on discrete values which were represented as markers by certain colors.
  • Jas
    Jas almost 5 years
    Can I remove the image from the map too?
  • Naveen Srikanth
    Naveen Srikanth over 3 years
    How to increase size of caption, Please help me
  • Ricardo Sanchez
    Ricardo Sanchez over 3 years
    This is great, but I cannot find these methods in the documentation, mind sharing a link? I would like to know if it is at all possible to remove the html child later
  • InLaw
    InLaw over 3 years
    @RicardoSanchez it a branca.element.Element
  • Artyrm Sergeev
    Artyrm Sergeev almost 2 years
    @InLaw sadly, I can only get map filled with white in the first example. Don't know what went wrong.