Plotly子图中甘特图数据异常:红色任务项消失
问题分析
使用 px.timeline 绘制甘特图时,若通过 color 参数按任务类型区分颜色,Plotly 会为每种类型生成独立的轨迹(trace)。你的代码中,trace_1.data 包含两个轨迹:一个对应蓝色任务,一个对应红色任务。但你仅将第一个轨迹(trace_1.data[0])添加到子图,导致红色任务的轨迹未被加载,因此显示消失。
解决方案
遍历 trace_1.data 中的所有轨迹,将它们逐一添加到子图中,确保所有颜色的任务都能正常显示。
修正后的完整代码
import pandas as pd import plotly.express as px from plotly.subplots import make_subplots df = pd.DataFrame({ 'Task': ['Task 1', 'Task 2', 'Task 3', 'Task 4', 'Task 5', 'Task 6'], 'Start': [pd.Timestamp('2022-01-01'), pd.Timestamp('2022-01-02'), pd.Timestamp('2022-01-03'), pd.Timestamp('2022-01-03'), pd.Timestamp('2022-01-05'), pd.Timestamp('2022-01-04')], 'Finish': [pd.Timestamp('2022-01-02'), pd.Timestamp('2022-01-04'), pd.Timestamp('2022-01-05'), pd.Timestamp('2022-01-08'), pd.Timestamp('2022-01-06'), pd.Timestamp('2022-01-07')], 'Resource': ['Resource 1', 'Resource 2', 'Resource 3', 'Resource 4', 'Resource 4', 'Resource 4'], 'Type': ['Type_Blue', 'Type_Blue', 'Type_Red', 'Type_Blue', 'Type_Blue', 'Type_Red'] }) fig = make_subplots(rows=2, shared_xaxes=True) trace_1 = px.timeline(df, x_start='Start', x_end='Finish', y='Resource', color='Type', color_discrete_map={'Type_Blue': 'blue', 'Type_Red': 'red'}, opacity=0.2) # 遍历所有轨迹并添加到子图 for trace in trace_1.data: fig.add_trace(trace, row=1, col=1) fig.update_yaxes(autorange="reversed") fig.update_layout(title='Timeline Subplots') fig.update_xaxes(type='date') fig.show()
内容的提问来源于stack exchange,提问作者Alfred Luu
相关产品推荐
相关产品推荐

