Python中如何为Folium地图添加Circle尺寸图例并优化标注可见性
Folium 欧洲人口规模地图开发问题
我在开发欧洲区域可视化地图,核心需求是用Circle标记标注城市点位,将标记尺寸和经过缩放的城市人口值一一对应,直观展示不同城市的人口规模差异。目前开发过程中遇到两个难以解决的核心问题:
- Circle尺寸映射的图例无法实现:一直尝试为地图添加和Circle尺寸匹配的图例,但始终没找到可行的实现方案。Folium的Circle图层本身没有内置图例配置接口,没法清晰向用户展示“圆形大小对应多少人口”的映射规则。
- 邻近城市的标注文字互相遮挡:目前我通过自定义DivIcon实现城市名称标注,基础功能可以正常运行,但当两个城市点位距离较近时,标注文字会互相重叠完全看不清。我希望能将这类邻近城市的标注文本偏移到对应点位的外侧,用细引线连接标注文字和对应的圆形点位,保证所有场景下的标注都清晰可见。
补充说明:当前示例只放了部分英国城市的测试数据,实际应用场景是覆盖全欧洲的大范围地图,点位数量多、相邻分布的情况非常普遍,标注遮挡的问题会在实际使用中特别突出。而且目前网上能找到的Folium相关配套资料比较零散,暂时没有找到同类场景的成熟参考实现,想问问各位开发者有没有相关的实现思路可以参考。
现有示例代码
import pandas as pd import numpy as np import folium import json import geopandas as gpd # 适配Notebook环境的可视化配置 %matplotlib inline # 测试用英国城市数据:城市名称、常住人口、纬度、经度 data = [['Birmingham', 1141374, 52.4796992, -1.9026911], ['Bradford', 537173, 53.7944229, -1.7519186], ['Bristol', 463405, 51.4538022, -2.5972985], ['Edinburgh', 518500, 55.9533456, -3.1883749], ['Glasgow', 626410, 55.8609825, -4.2488787], ['Leeds', 789194, 53.7974185, -1.5437941], ['Liverpool', 494814, 53.407154, -2.991665]] cities = pd.DataFrame(data, columns = ['City', 'Population', 'Latitude', 'Longitude']) # 加载欧洲区域行政边界的GeoJSON数据 europe = None import folium.plugins from folium.features import * # 自定义DivIcon类,实现纯文本无图标标注 class DivIcon(MacroElement): def __init__(self, html='', size=(30,30), anchor=(0,0), style=''): super(DivIcon, self).__init__() self._name = 'DivIcon' self.size = size self.anchor = anchor self.html = html self.style = style self._template = Template(u""" {% macro header(this, kwargs) %} <style> .{{this.get_name()}} { {{this.style}} } </style> {% endmacro %} {% macro script(this, kwargs) %} var {{this.get_name()}} = L.divIcon({ className: '{{this.get_name()}}', iconSize: [{{ this.size[0] }},{{ this.size[1] }}], iconAnchor: [{{ this.anchor[0] }},{{ this.anchor[1] }}], html : "{{this.html}}", }); {{this._parent.get_name()}}.setIcon({{this.get_name()}}); {% endmacro %} """) # 初始化底图 map = folium.Map(location=[53.7974185, -1.5437941], zoom_start=4, tiles=None) # 欧洲边界图层样式 style_boundary = {'color': 'black', 'weight': -1, 'opacity': 0.2} # 添加欧洲边界图层 folium.GeoJson( europe, name='Europe', overlay=False, control= False, style_function = lambda x: style_boundary).add_to(map) # 遍历所有城市,逐点添加圆形标记与文本标注 for idx, city in cities.iterrows(): # 圆形标记:半径与城市人口值成比例缩放 folium.Circle(location=(city['Latitude'], city['Longitude']), popup=city['City'], radius=city['Population']/10000, fillColor= 'red', color= 'red', fill= True, fillOpacity= 0, opacity= 1, weight= 2 ).add_to(map) # 城市名称文本标注 folium.Marker(location=(city['Latitude'], city['Longitude']), icon=DivIcon( size=(75,25), anchor=(50,-3), html=city.City, style='font-size:13px; color:black; text-align: center')).add_to(map) # 渲染输出地图 map
内容的提问来源于stack exchange,提问作者ctrl_z
相关产品推荐
相关产品推荐

