Plotly趋势线实现:能否绘制25-75百分位的四分位距范围?
实现25至75百分位范围趋势线的方案建议
你当前用px.scatter的expanding趋势线只能展示均值的累积变化,要实现25-75百分位的范围趋势,需要先预处理数据计算分位数,再通过添加轨迹的方式绘制范围线或填充区域。以下是具体实现步骤和代码:
1. 修正原代码的参数错误
原代码里把markersize和s放在labels字典里是错误的,这两个是控制散点大小的参数,应该直接作为px.scatter的参数传入,labels仅用于重命名轴和图例名称。
2. 分组计算百分位数据
先按时间和技术类型(或仅按时间)分组,计算每个时间点的25、75百分位:
import plotly.express as px import pandas as pd # 确保日期列是datetime类型 df['Date'] = pd.to_datetime(df['Date']) # 按日期+技术类型分组,计算25/75百分位及中位数 percentile_data = df.groupby(['Date', 'Technology'])['Number of Events'].agg( p25=lambda x: x.quantile(0.25), p75=lambda x: x.quantile(0.75), median=lambda x: x.median() ).reset_index()
3. 绘制散点+百分位范围趋势
先绘制原始散点,再遍历每个技术类型添加百分位线和填充区域:
# 初始化散点图 fig = px.scatter(df, x="Date", y="Number of Events", color="Technology", markersize=50, # 正确设置散点大小 labels={ "Date": "日期", "Number of Events": "事件数量", "Technology": "技术类型" }) # 获取plotly默认配色,保证线条和散点颜色一致 color_palette = px.colors.qualitative.Plotly rgb_palette = px.colors.qualitative.Plotly_rgb # 遍历每个技术类型,添加百分位范围 for idx, tech in enumerate(percentile_data['Technology'].unique()): tech_subset = percentile_data[percentile_data['Technology'] == tech] # 添加75百分位虚线 fig.add_scatter( x=tech_subset['Date'], y=tech_subset['p75'], mode='lines', name=f'{tech} 75百分位', line=dict(dash='dash', color=color_palette[idx]) ) # 添加25百分位虚线,并填充中间区域 fig.add_scatter( x=tech_subset['Date'], y=tech_subset['p25'], mode='lines', name=f'{tech} 25百分位', line=dict(dash='dash', color=color_palette[idx]), fill='tonexty', # 填充到上方的75百分位线 fillcolor=f'rgb({rgb_palette[idx]}, 0.2)' # 设置填充透明度 ) # 可选:添加中位数实线 fig.add_scatter( x=tech_subset['Date'], y=tech_subset['median'], mode='lines', name=f'{tech} 中位数', line=dict(color=color_palette[idx]) ) fig.show()
4. 全局百分位范围(不按技术分组)
如果不需要按技术类型区分,只看全局的25-75百分位趋势,修改分组逻辑即可:
# 按日期分组计算全局百分位 global_percentile = df.groupby('Date')['Number of Events'].agg( p25=lambda x: x.quantile(0.25), p75=lambda x: x.quantile(0.75) ).reset_index() # 绘制散点后添加全局百分位线 fig.add_scatter( x=global_percentile['Date'], y=global_percentile['p75'], mode='lines', name='全局75百分位', line=dict(dash='dash', color='gray') ) fig.add_scatter( x=global_percentile['Date'], y=global_percentile['p25'], mode='lines', name='全局25百分位', line=dict(dash='dash', color='gray'), fill='tonexty', fillcolor='rgba(128,128,128,0.1)' ) fig.show()
内容的提问来源于stack exchange,提问作者disruptive
相关产品推荐
相关产品推荐

