python制作甘特图的基本知识(附Demo)-2. plotly

时间:2024-07-13 13:41:34

交互式绘图库,适合制作动态甘特图

import plotly.express as px
import pandas as pd

# 创建数据
tasks = [
    {"Task": "Task A", "Start": "2024-01-01", "Finish": "2024-01-05"},
    {"Task": "Task B", "Start": "2024-01-02", "Finish": "2024-01-07"},
    {"Task": "Task C", "Start": "2024-01-08", "Finish": "2024-01-10"},
]

# 将数据转换为 DataFrame
df = pd.DataFrame(tasks)

# 使用 plotly 绘制甘特图
fig = px.timeline(df, x_start="Start", x_end="Finish", y="Task", title="Gantt Chart")
fig.update_yaxes(categoryorder="total ascending")

# 显示图形
fig.show()

截图如下:

在这里插入图片描述

带有任务分组的甘特图

import plotly.express as px
import pandas as pd

# 创建数据
tasks = [
    {"Task": "Task A1", "Start": "2024-01-01", "Finish": "2024-01-05", "Group": "Group A"},
    {"Task": "Task A2", "Start": "2024-01-06", "Finish": "2024-01-10", "Group": "Group A"},
    {"Task": "Task B1", "Start": "2024-01-02", "Finish": "2024-01-07", "Group": "Group B"},
    {"Task": "Task B2", "Start": "2024-01-08", "Finish": "2024-01-12", "Group": "Group B"},
]

# 将数据转换为 DataFrame
df = pd.DataFrame(tasks)

# 使用 plotly 绘制甘特图
fig = px.timeline(df, x_start="Start", x_end="Finish", y="Task", color="Group", title="Gantt Chart with Groups")
fig.update_yaxes(categoryorder="total ascending")

# 显示图形
fig.show()

截图如下:

在这里插入图片描述