[Python] Adding colormap legend to Folium map

Discussão em 'Python' iniciado por Stack, Março 30, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to make a map in Folium with multiple layers, each consisting of shaded areas (using GeoJSON) with colors given by a colormap. I'd like to add legends to my layers. I found a first solution here, but the problem with this solution were that the legend is fixed at the top right and more importantly, that it's always there. Instead, I'd like a legend that is only shown when the corresponding layer is shown.

    Here is some example code that I tried (where m is my Folium map and cm1 and cm2 are color maps):

    folium.GeoJson(data['Temp'],
    name='Temp',
    style_function=lambda x: {
    'fillColor': cm1(x['properties']['Temp']),
    'fillOpacity': 0.2,
    'color' : None
    },
    highlight_function=lambda x: {'weight':3, 'color':'black'},
    tooltip=folium.features.GeoJsonTooltip(fields=['Temp', 'Rain'],
    labels=True,
    sticky=True
    ), show=False).add_to(m)

    folium.GeoJson(data['Rain'],
    name='Rain',
    style_function=lambda x: {
    'fillColor': cm2(x['properties']['Rain']),
    'fillOpacity': 0.2,
    'color' : None
    },
    highlight_function=lambda x: {'weight':3, 'color':'black'},
    tooltip=folium.features.GeoJsonTooltip(fields=['Temp', 'Rain'],
    labels=True,
    sticky=True
    ), show=False).add_to(m)

    cm1.caption = 'Temp scale'
    cm2.caption = 'Rain scale'
    m.add_child(cm1)
    m.add_child(cm2)

    folium.LayerControl().add_to(m)


    How can I change my code so that the legends are only shown when the corresponding layers are shown? (And if possible, how can I move the legends to the bottom left?)

    Continue reading...

Compartilhe esta Página