Use Python to draw Gantt charts elegantly

Introduction

A Gantt chart is a bar chart used to depict project progress. The chart lists tasks to be performed on the vertical axis and time intervals on the horizontal axis. The width of the horizontal bars in the graph shows the duration of each activity. In Python, we can use the Plotly library to create and display Gantt charts.

Basic Gantt chart

First, let's create a basic Gantt chart showing the start and end times of several tasks.

# coding=gbk
"""
作者:川川
@时间  : 202210/05 16:05
"""
import plotly.express as px
import pandas as pd

df = pd.DataFrame([
    dict(Task="Job A", Start='2022-01-01', Finish='2022-02-28'),
    dict(Task="Job B", Start='2022-03-05', Finish='2022-04-15'),
    dict(Task="Job C", Start='2022-02-20', Finish='2022-05-30')
])
# 这几个参数固定
fig = px.timeline(df, x_start="Start", x_end="Finish", y="Task")
fig.update_yaxes(autorange="reversed")
fig.show()

The running results are as follows:
Insert image description here
In this example, we define three tasks, each task has a start and end date. We use plotly.express’s timeline function to create the chart and update_yaxes to reverse the order of the y-axis.

Add color to Gantt chart

We can distinguish different resource or task states by adding a color parameter.

# coding=gbk
"""
作者:川川
@时间  : 202210/05 16:05
"""
import plotly.express as px
import pandas as pd

df = pd.DataFrame([
    dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28', Resource="Alex"),
    dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15', Resource="Alex"),
    dict(Task="Job C", Start='2009-02-20', Finish='2009-05-30', Resource="Max")
])

fig = px.timeline(df, x_start="Start", x_end="Finish", y="Task", color="Resource")
fig.update_yaxes(autorange="reversed")
fig.show()

as follows:
Insert image description here

In this example, we added a "Resource" column to represent the resource of the task and used it as the color parameter.

Color using percent completeness

We can also use the task's completion percentage to color the Gantt chart.

import plotly.express as px
import pandas as pd

df = pd.DataFrame([
    dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28', Completion_pct=50),
    dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15', Completion_pct=25),
    dict(Task="Job C", Start='2009-02-20', Finish='2009-05-30', Completion_pct=75)
])

fig = px.timeline(df, x_start="Start", x_end="Finish", y="Task", color="Completion_pct")
fig.update_yaxes(autorange="reversed")
fig.show()

Run as follows:
Insert image description here

Display by resource

It is also possible to have multiple bars on the same horizontal line, for example by resource:
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_46211269/article/details/133564031