Plotly Express choropleth按指定分箱设置离散色阶的实现方法
Plotly Express choropleth 自定义分箱离散色阶实现方法
原代码不生效的原因:传入color参数的PGR字段为连续数值类型,Plotly默认调用连续色阶映射,而color_discrete_sequence仅对类别类型的color字段生效。
你可以选择以下两种方案实现需求:
方案1:提前对PGR字段分箱(推荐,原生离散色阶)
先使用pandas的cut方法按你指定的区间将PGR转为有序类别字段,再传入绘图接口:
import pandas as pd import plotly.express as px # 定义分箱边界 bins = [-50, 0, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500] # 定义分箱显示标签,和区间一一对应 bin_labels = ["[-50,0)", "[0,50)", "[50,100)", "[100,150)", "[150,200)", "[200,250)", "[250,300)", "[300,350)", "[350,400)", "[400,450)", "[450,500)"] # 生成有序分箱列,right=False表示区间左闭右开,符合你的需求 popCodes["PGR_bin"] = pd.cut(popCodes["PGR"], bins=bins, labels=bin_labels, include_lowest=True, right=False, ordered=True) # 绘图 fig = px.choropleth(popCodes, locations="Code", color="PGR_bin", hover_name="Country", color_discrete_sequence=px.colors.sequential.Plasma, category_orders={"PGR_bin": bin_labels} # 强制图例按分箱顺序排列 ) fig.show()
该方案的优势是图例直接展示每个区间色块,hover信息可直接显示所属区间,符合离散色阶的使用逻辑。
方案2:自定义连续色阶断点(无需新增列)
如果不想修改原始数据框,可通过自定义连续色阶的分段,模拟离散分箱效果:
import plotly.express as px bins = [-50, 0, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500] colors = px.colors.sequential.Plasma # 构造自定义分段色阶 custom_colorscale = [] for idx in range(len(bins)-1): # 计算区间在整个值域的归一化位置 norm_start = (bins[idx] - bins[0]) / (bins[-1] - bins[0]) norm_end = (bins[idx+1] - bins[0]) / (bins[-1] - bins[0]) # 同一个颜色覆盖整个区间 custom_colorscale.append([norm_start, colors[idx]]) custom_colorscale.append([norm_end, colors[idx]]) # 绘图 fig = px.choropleth(popCodes, locations="Code", color="PGR", range_color=(-50, 500), hover_name="Country", color_continuous_scale=custom_colorscale ) # 调整色条刻度,匹配分箱边界 fig.update_layout(coloraxis_colorbar=dict( tickvals=bins, ticktext=[str(b) for b in bins] )) fig.show()
该方案的优势是无需修改原始数据,hover时仍显示原始PGR数值。
内容的提问来源于stack exchange,提问作者Mercredi
相关产品推荐
相关产品推荐

