Python绘制Choropleth地图图例显示离散值而非连续色阶问题
问题描述
现有如下美国各州事件统计数据集:
STATE Count POPESTIMATE2019 lat long IncidentPerInhabitant Code 46 New Hampshire 1 1359711 43.206898 -71.537994 0.073545 NH 45 Idaho 2 1787065 43.617775 -116.199722 0.111915 ID 48 Vermont 1 623989 44.262436 -72.580536 0.160259 VT 47 Wyoming 1 578759 41.140259 -104.820236 0.172783 WY 38 Utah 6 3205958 40.777477 -111.888237 0.187152 UT 44 Maine 3 1344212 44.307167 -69.781693 0.223179 ME . . . . . . . . . . . . . . . . . . . . . . . .
使用如下Plotly代码绘制分级统计地图:
fig1 = px.choropleth(df_merge2, locations='Code', color='IncidentPerInhabitant', color_continuous_scale='Reds', hover_name='STATE', locationmode='USA-states', labels={'IncidentPerInhabitant':'Incident Per 10000 Inhabitants '}, scope='usa') fig1.show()
运行后得到的图例为离散分段样式,每个数值单独罗列,未出现预期的连续渐变色阶:
期望实现的连续色阶图例效果如下:
问题原因
出现离散图例的核心原因是Plotly的自动类型判定逻辑:当color绑定的列被识别为分类类型,或列内唯一值数量较少时,即使传入了连续色阶参数,Plotly也会默认使用离散颜色映射,为每个独立值单独分配颜色、生成离散图例。
解决步骤
- 校验映射列的数据类型,确保数值列没有被误识别为文本类型
# 打印目标列的数据类型 print(df_merge2['IncidentPerInhabitant'].dtype) # 如果输出不是float/int数值类型,先强制转换为浮点型,转换前注意先清理列内的非数值异常值、空值 df_merge2['IncidentPerInhabitant'] = pd.to_numeric(df_merge2['IncidentPerInhabitant'], errors='coerce') - 在绘图函数中显式添加
range_color参数,手动指定连续色阶的数值范围,强制Plotly启用连续颜色映射,避免自动误判为离散模式。 - (可选)通过
update_layout调整色条的显示样式,对齐预期效果。
修正后的完整可运行代码:
import plotly.express as px import pandas as pd # 提前做数据类型转换 df_merge2['IncidentPerInhabitant'] = pd.to_numeric(df_merge2['IncidentPerInhabitant'], errors='coerce') fig1 = px.choropleth(df_merge2, locations='Code', color='IncidentPerInhabitant', color_continuous_scale='Reds', # 显式指定连续色阶的数值范围,强制启用连续色条 range_color=(df_merge2['IncidentPerInhabitant'].min(), df_merge2['IncidentPerInhabitant'].max()), hover_name='STATE', locationmode='USA-states', labels={'IncidentPerInhabitant':'Incident Per 10000 Inhabitants '}, scope='usa') # 可选:调整色条样式 fig1.update_layout( coloraxis_colorbar=dict( len=0.8, # 调整色条长度 tickmode='linear' # 设置刻度为线性均匀分布 ) ) fig1.show()
运行后即可得到连续渐变色阶的图例效果。
内容的提问来源于stack exchange,提问作者Liv Matthews
相关产品推荐
相关产品推荐

