如何在Folium Choropleth地图中使用自定义颜色渐变条
解决Folium Choropleth自定义颜色渐变条的问题
Folium的Choropleth组件fill_color参数仅接受内置配色名称(如'viridis')或特殊值'custom',无法直接传入branca的StepColormap对象,这就是你遇到报错的原因。以下两种方案可以实现需求:
方案一:使用Choropleth原生自定义配色(无需branca)
如果需要基于预设分段的配色,直接将颜色列表传给colors参数,同时设置fill_color='custom',注意bins的长度必须比颜色列表长度多1(bins是区间分界点,颜色对应每个区间)。
示例代码(固定bins):
# 定义变量 max_value = df[status].max() # 4个颜色对应bins的4个区间(bins长度为5) hex_codes = ['#0b0405', '#28192e', '#3b2e5d', '#40498e'] bins = [0,10,100,1000,10000] # 创建Choropleth图层 folium.Choropleth( geo_data=df, data=df, bins=bins, columns=('polyname', status), key_on="feature.properties.polyname", fill_color='custom', # 指定使用自定义配色 colors=hex_codes, # 传入自定义颜色列表 legend_name=status ).add_to(m)
示例代码(自动生成bins适配10个颜色):
如果想保留你定义的10个颜色,可以按数值等分生成对应bins:
import numpy as np hex_codes = ['#0b0405', '#28192e', '#3b2e5d', '#40498e', '#366a9f', '#348ba6', '#38aaac', '#55caad', '#a1dfb9', '#def5e5'] # 生成11个分界点,对应10个颜色区间 bins = np.linspace(0, df[status].max(), len(hex_codes)+1).tolist() folium.Choropleth( geo_data=df, data=df, bins=bins, columns=('polyname', status), key_on="feature.properties.polyname", fill_color='custom', colors=hex_codes, legend_name=status ).add_to(m)
方案二:使用GeoJson+branca Colormap(更灵活)
如果要保留branca StepColormap的自动数值映射功能,可放弃Choropleth组件,直接用GeoJson图层配合自定义样式函数:
from branca.colormap import StepColormap # 定义变量和自定义颜色映射 max_value = df[status].max() hex_codes = ['#0b0405', '#28192e', '#3b2e5d', '#40498e', '#366a9f', '#348ba6', '#38aaac', '#55caad', '#a1dfb9', '#def5e5'] custom_colour_map = StepColormap(colors=hex_codes, vmin=0, vmax=max_value, tick_labels=[0, max_value*.25, max_value*.5, max_value*.75, max_value]) # 定义样式函数:根据特征数值获取对应颜色 def style_function(feature): value = feature['properties'][status] return { 'fillColor': custom_colour_map(value), 'color': 'black', 'weight': 1, 'fillOpacity': 0.7 } # 添加GeoJson图层 folium.GeoJson( df, style_function=style_function, tooltip=folium.GeoJsonTooltip(fields=['polyname', status]) # 可选:添加悬浮提示 ).add_to(m) # 将自定义颜色渐变条添加到地图 custom_colour_map.add_to(m)
两种方案对比:
- 方案一适合简单分段配色,利用Choropleth内置功能实现,代码简洁;
- 方案二更灵活,支持branca所有配色类型,还能自由控制图层样式细节。
内容的提问来源于stack exchange,提问作者Alex_J
相关产品推荐
相关产品推荐

