You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Plotly添加color属性后部分数据点悬停功能失效求助

解决方案

问题根源

用color='Sign'分组后,Plotly会生成两个独立的面积图trace(对应Positive和Negative),你的代码未指定x轴参数,默认用DataFrame的index作为x轴,导致分组后trace的x轴数据与custom_data中的MeasureDate对应关系混乱,部分点无法匹配到正确的悬停数据;同时custom_data在多trace场景下的传递也容易出现关联偏差。

具体修复步骤

1. 指定x轴为MeasureDate

明确将x轴设置为日期字段,确保每个数据点的x坐标与日期一一对应,分组后的trace也能正确关联数据:

fig = px.area(df, 
              x='MeasureDate',  # 新增此行,指定x轴为日期
              y='DeviationValue', 
              title=f"Graph of {data['engine']} going back one year from {data['date']}",
              color='Sign',
              color_discrete_map={
                'Positive': 'green',
                'Negative': 'red'
              },
              labels={
                "DeviationValue": 'Deviation',
                'MeasureDate': 'Date'  # 可选:给x轴设置更清晰的标签
              }
            )

2. 简化悬停模板,无需custom_data

直接使用Plotly内置的%{x}和%{y}变量引用x轴(日期)和y轴(偏差值)数据,避免custom_data在多trace场景下的传递问题:

fig.update_traces(showlegend=False, hovertemplate='Date: %{x}<br>Deviation: %{y}')

3. 可选:检查数据完整性

确保MeasureDate和DeviationValue字段无缺失值,避免因数据空值导致的悬停提示异常:

# 检查并删除含空值的行
df = df.dropna(subset=['MeasureDate', 'DeviationValue'])

完整修复代码

df = pd.DataFrame(data['df'])
df['MeasureDate'] = pd.to_datetime(df['MeasureDate'], infer_datetime_format=True)
df['Sign'] = np.where(df['DeviationValue'] > 0, 'Positive', 'Negative')
# 检查并移除空值行
df = df.dropna(subset=['MeasureDate', 'DeviationValue'])

fig = px.area(df, 
              x='MeasureDate',
              y='DeviationValue', 
              title=f"Graph of {data['engine']} going back one year from {data['date']}",
              color='Sign',
              color_discrete_map={
                'Positive': 'green',
                'Negative': 'red'
              },
              labels={
                "DeviationValue": 'Deviation',
                'MeasureDate': 'Date'
              }
            )
fig.update_traces(showlegend=False, hovertemplate='Date: %{x}<br>Deviation: %{y}')

内容的提问来源于stack exchange,提问作者Brittanie Polasek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 23:15:27