Примеры:
Цифровая легенда

Я также хотел бы добавить категориальная легенда, такая как эта:
Категорическая легенда

Пока у меня есть только этот код, я застрял, пытаясь достичь того, что делает addLegend из R.
Функция
Код: Выделить всё
def add_categorical_legend(folium_map, title, colors, labels):
if len(colors) != len(labels):
raise ValueError("colors and labels must have the same length.")
color_by_label = dict(zip(labels, colors))
legend_categories = ""
for label, color in color_by_label.items():
legend_categories += f"[*]{label}"
legend_html = f"""
{title}
[list]
{legend_categories}
[/list]
"""
script = f"""
var oneTimeExecution = (function() {{
var executed = false;
return function() {{
if (!executed) {{
var checkExist = setInterval(function() {{
if ((document.getElementsByClassName('leaflet-top leaflet-right').length) || (!executed)) {{
document.getElementsByClassName('leaflet-top leaflet-right')[0].style.display = "flex"
document.getElementsByClassName('leaflet-top leaflet-right')[0].style.flexDirection = "column"
document.getElementsByClassName('leaflet-top leaflet-right')[0].innerHTML += `{legend_html}`;
clearInterval(checkExist);
executed = true;
}}
}}, 100);
}}
}};
}})();
oneTimeExecution()
"""
css = """
.maplegend {
z-index:9999;
float:right;
background-color: rgba(255, 255, 255, 1);
border-radius: 5px;
border: 2px solid #bbb;
padding: 10px;
font-size:12px;
positon: relative;
}
.maplegend .legend-title {
text-align: left;
margin-bottom: 5px;
font-weight: bold;
font-size: 90%;
}
.maplegend .legend-scale ul {
margin: 0;
margin-bottom: 5px;
padding: 0;
float: left;
list-style: none;
}
.maplegend .legend-scale ul li {
font-size: 80%;
list-style: none;
margin-left: 0;
line-height: 18px;
margin-bottom: 2px;
}
.maplegend ul.legend-labels li span {
display: block;
float: left;
height: 16px;
width: 30px;
margin-right: 5px;
margin-left: 0;
border: 0px solid #ccc;
}
.maplegend .legend-source {
font-size: 80%;
color: #777;
clear: both;
}
.maplegend a {
color: #777;
}
"""
folium_map.get_root().header.add_child(folium.Element(script + css))
return folium_map
Код: Выделить всё
import folium
m = folium.Map()
m = add_categorical_legend(m, 'My title',
colors = ['#000','#03cafc'],
labels = ['Heat', 'Cold'])
m = add_categorical_legend(m, 'My title 2',
colors = ['#F23','#777'],
labels = ['Heat 2', 'Cold 2'])
m.save("map.html")
m

Проблемы
- Однако легенда, которую я создал, конфликтует с элементами управления слоями folium, и они перестают работать, что для меня является очень большой проблемой, потому что легенды предназначены для описания того, что я я использую в LayerControls. Я не знаю, в чем причина.
- Кроме того, это работает только для категориальных данных.
- Я бы хотел, чтобы легенды можно было добавлять вверх | бот и право | левые позиции, как это делает addLegend из R. Указание абсолютного положения невозможно.
ПРИМЕЧАНИЕ. Я не хочу использовать карту цветов Бранка, потому что мне бы хотелось иметь легенду, подобную той, что показана вам на изображениях.
Подробнее здесь: https://stackoverflow.com/questions/650 ... folium-map