folium.features.GeoJson中fillColor不生效?循环颜色始终不变求解
Folium循环设置GeoJson填充色不变的问题解决
问题原因
循环里的lambda函数采用延迟绑定变量的机制——它不会在定义时就捕获当前color的具体值,而是等到地图渲染、实际调用style_function时,才去读取color变量的最终值(也就是循环最后一次迭代的颜色),所以所有GeoJson要素的填充色都变成了同一个。
修复方案
有两种简单可行的解决方式:
方式1:给lambda添加默认参数绑定当前值
通过给lambda设置默认参数,把当前迭代的color值直接绑定进去,这样每次循环生成的lambda都会持有独立的颜色值:
location = (-32.337402, 117.871796) m = folium.Map(location=location, zoom_start=7, control_scale=True, prefer_canvas=True) # 设置颜色调色板 palette = sns.color_palette(None, len(df.name.unique())).as_hex() palette = [i for i in palette] for id, item in enumerate(df.name.unique()): color = palette[id] polygons_gjson = folium.features.GeoJson( df.loc[df.name == item, 'geometry'], # 关键修改:添加color=color默认参数 style_function=lambda x, color=color: { 'weight': 1, 'color': 'black', 'fillColor': color, 'fillOpacity': 1 }, name = f'Paddocks delivering to {str(df.site_name.values[0])} using: {item} gate', control=True ) polygons_gjson.add_to(m) m
方式2:用工厂函数生成style_function
通过定义一个专门生成样式函数的工厂,确保每次传入的颜色都被独立捕获:
location = (-32.337402, 117.871796) m = folium.Map(location=location, zoom_start=7, control_scale=True, prefer_canvas=True) # 定义样式函数工厂 def create_style(color): return lambda x: {'weight': 1, 'color': 'black', 'fillColor': color, 'fillOpacity': 1} # 设置颜色调色板 palette = sns.color_palette(None, len(df.name.unique())).as_hex() palette = [i for i in palette] for id, item in enumerate(df.name.unique()): color = palette[id] polygons_gjson = folium.features.GeoJson( df.loc[df.name == item, 'geometry'], # 调用工厂函数生成对应样式 style_function=create_style(color), name = f'Paddocks delivering to {str(df.site_name.values[0])} using: {item} gate', control=True ) polygons_gjson.add_to(m) m
内容的提问来源于stack exchange,提问作者MJ313
相关产品推荐
相关产品推荐

