如何在Dash中为Plotly直方图按年龄组分组并设置连续配色?
解决方案
要实现按10岁年龄组拆分颜色的需求,核心是先把Customer_Age转换成区间分组,再用这个分组字段作为颜色依据,而不是直接用原始年龄值。具体步骤如下:
1. 数据预处理:创建年龄分组字段
用pd.cut函数把年龄按10岁为一组划分,同时把区间格式转换成更友好的文本,方便图例显示:
import pandas as pd data = pd.read_csv('data.csv') # 定义年龄区间边界,覆盖0到100岁(可根据实际数据调整) age_bins = range(0, 101, 10) # 生成可读性强的区间标签,如"0-9"、"10-19" age_labels = [f'{i}-{i+9}' for i in age_bins[:-1]] # 创建年龄分组字段,左闭右开区间(例如"10-19"包含10岁,不包含20岁) data['Age_Group'] = pd.cut(data['Customer_Age'], bins=age_bins, labels=age_labels, right=False)
2. 修改直方图代码,使用年龄分组作为颜色维度
将color参数替换为新的Age_Group字段,同时指定有序配色方案,确保颜色随年龄组呈现规律变化:
from dash import Dash, html, dcc import plotly.express as px app = Dash(__name__) app.layout = html.Div([ dcc.Graph( figure=px.histogram( data, x='Product', y='Revenue', histfunc='sum', color='Age_Group', color_discrete_sequence=px.colors.sequential.Viridis, # 指定有序渐变配色 barmode='group' # 可选:设置柱状条并列显示,默认是堆叠模式 ).update_layout( legend_title_text='年龄组', xaxis_title='产品', yaxis_title='总营收' ) ), ]) if __name__ == '__main__': app.run(debug=True)
补充说明
- 若需要堆叠显示各年龄组的营收,直接移除
barmode='group'参数即可(Plotly默认堆叠)。 - 配色序列可按需替换,比如
px.colors.sequential.Blues(冷色调渐变)、px.colors.qualitative.D3(离散对比色)等,Plotly内置多种配色方案。 - 如果数据中存在超出
0-99范围的年龄,可调整age_bins的边界值(比如扩展到110),避免出现NaN分组。
内容的提问来源于stack exchange,提问作者Bubaya
相关产品推荐
相关产品推荐

