15

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
  • 10,794
  • 12
  • 54
  • 74

5 Answers5

16

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

Harley
  • 1,305
  • 1
  • 13
  • 28
9

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
InLaw
  • 2,537
  • 2
  • 21
  • 33
8

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)
sparrow
  • 10,794
  • 12
  • 54
  • 74
6

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())
Penny Pang
  • 535
  • 2
  • 8
  • 23
  • 2
    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 Jun 27 '17 at 22:11
3

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.

Dan Kinn
  • 151
  • 2
  • 5