简体   繁体   English

如何隐藏 python folium choropleth 传说

[英]how to hide python folium choropleth legend

I have created a folium map with two choropleths layers:我创建了一个包含两个 choropleths 层的 folium 地图:

https://ghana.deta.dev/ https://ghana.deta.dev/

As you can see in the picture, only one layer is right now selected (green).正如您在图片中看到的,现在只有一层被选中(绿色)。 Yet, the legend is shown for both (blue and green).然而,图例显示了两者(蓝色和绿色)。

Is there a way to sync it with the layer control?有没有办法将它与图层控件同步?

Instead of my code, I am linking the folium Choropleth tutorial to make it more usable for everyone:我链接了 folium Choropleth 教程,而不是我的代码,以使其对每个人都更有用:

在此处输入图像描述

source: https://python-visualization.github.io/folium/quickstart.html#Choropleth-maps As you can see, regardless of the layer control, the legend is always on.来源: https ://python-visualization.github.io/folium/quickstart.html#Choropleth-maps 如您所见,无论图层控件如何,图例始终打开。

r-beginners provided the clue to this solution in their comment. r-beginners在他们的评论中提供了这个解决方案的线索。 A few additional re-works were necessary so I consider it worth adding the code for future reference.一些额外的重新工作是必要的,所以我认为值得添加代码以供将来参考。

Explaining the solution briefly, the branca color map is first removed to then be re-added to the map binded to the choropleth layer itself thanks to a custom macro element.简要解释解决方案,首先删除 branca 颜色图,然后重新添加到绑定到 choropleth 层本身的地图中,这要归功于自定义宏元素。

from branca.element import MacroElement

from jinja2 import Template

import pandas as pd


class BindColormap(MacroElement):
    """Binds a colormap to a given layer.

    Parameters
    ----------
    colormap : branca.colormap.ColorMap
        The colormap to bind.
    """
    def __init__(self, layer, colormap):
        super(BindColormap, self).__init__()
        self.layer = layer
        self.colormap = colormap
        self._template = Template(u"""
        {% macro script(this, kwargs) %}
            {{this.colormap.get_name()}}.svg[0][0].style.display = 'block';
            {{this._parent.get_name()}}.on('overlayadd', function (eventLayer) {
                if (eventLayer.layer == {{this.layer.get_name()}}) {
                    {{this.colormap.get_name()}}.svg[0][0].style.display = 'block';
                }});
            {{this._parent.get_name()}}.on('overlayremove', function (eventLayer) {
                if (eventLayer.layer == {{this.layer.get_name()}}) {
                    {{this.colormap.get_name()}}.svg[0][0].style.display = 'none';
                }});
        {% endmacro %}
        """)  # noqa

url = (
    "https://raw.githubusercontent.com/python-visualization/folium/master/examples/data"
)
state_geo = f"{url}/us-states.json"
state_unemployment = f"{url}/US_Unemployment_Oct2012.csv"
state_data = pd.read_csv(state_unemployment)

m = folium.Map(location=[48, -102], zoom_start=3)

c = folium.Choropleth(
    geo_data=state_geo,
    name="choropleth",
    data=state_data,
    columns=["State", "Unemployment"],
    key_on="feature.id",
    fill_color="YlGn",
    fill_opacity=0.7,
    line_opacity=0.2,
    legend_name="Unemployment Rate (%)",
)

for key in c._children:
    if key.startswith('color_map'):
        branca_color_map = c._children[key]
        del(c._children[key])


m.add_child(c)
m.add_child(folium.map.LayerControl())
m.add_child(branca_color_map)
m.add_child(BindColormap(c, branca_color_map))
m

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM