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

基于Python Plotly的甘特图:为休假项设置独特颜色需求

实现甘特图中Leave任务的独特颜色区分

要给标注为Leave的任务设置独特颜色,核心思路是新增一个优先区分Leave的颜色分组字段,让Plotly根据这个字段分配颜色,而非直接使用原有的WnS POC。以下是修改后的完整代码:

import pandas as pd
import plotly.express as px
import plotly.io as pio

# 读取并预处理数据
df = pd.read_excel('Project Priority List.xlsx')
df.columns = df.iloc[0]
df = df[1:]
df.reset_index(drop=True, inplace=True)

Modelling = {'Oscar','Parvathy Anil','Pavan','Puru','Senthil','Vel','Vetrivel','Subramanian'}
MO = {'Anju','Naveen','Parvathy M','Shaima','Manikandan','Saranya'}

Modelling_Team = df[df['WnS POC'].isin(Modelling)]
Modelling_Team.reset_index(drop=True, inplace=True)

# 筛选Active和Leave类型的任务
filter_condition = Modelling_Team['Active Task'].str.contains('Active|Leave', case=False, na=False)
dff = Modelling_Team[filter_condition]

# 新增颜色分组字段:优先标记Leave任务
dff['Color Group'] = dff.apply(
    lambda row: 'Leave' if 'Leave' in str(row['Active Task']).lower() else row['WnS POC'],
    axis=1
)

# 自定义颜色映射(指定Leave的独特颜色,其他POC自动分配默认色)
color_map = {'Leave': '#ff4d4d'}  # 红色,可按需替换
for poc in dff['WnS POC'].unique():
    if poc not in color_map:
        color_map[poc] = px.colors.qualitative.Plotly[len(color_map) % len(px.colors.qualitative.Plotly)]

# 生成甘特图,使用新的颜色分组字段
fig = px.timeline(
    dff,
    x_start='Start Date',
    x_end='Planned Due Date',
    y='Project (Scope)',
    color='Color Group',
    color_discrete_map=color_map,
    title='Gantt Chart',
    hover_data=['Project Name', 'Priority', 'WnS POC']  # 保留负责人信息在悬浮提示中
)

# 布局配置
fig.update_xaxes(title_text='Timeline', rangeslider_visible=True, type="date")
fig.update_yaxes(autorange="reversed")
fig.show()

pio.write_html(fig, file='timeline_gantt.html')

关键修改说明:

  • 新增Color Group字段:通过判断任务类型,将Leave任务统一标记为单独分组,其他任务沿用原负责人信息,确保Leave任务能被单独识别上色。
  • 自定义颜色映射:强制指定Leave任务的独特颜色,其他负责人任务自动分配Plotly默认定性色,也可手动添加更多颜色规则。
  • 保留悬浮信息:在hover数据中补充WnS POC,不影响查看任务负责人的原始信息。

修改后所有Leave任务会显示为指定的独特颜色,其他任务仍按原负责人区分颜色,符合预期效果。

内容的提问来源于stack exchange,提问作者Naveen Nandanan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 09:28:15