Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Matplotlib to draw Gantt Chart by Python

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Editor to share with you how Python uses Matplotlib to draw Gantt chart. I hope you will get something after reading this article. Let's discuss it together.

1. Introduction

The Gantt chart has a history of more than 100 years, and this visual chart is very useful for project management.

Henry Gantt created the Gantt Chart to analyze completed projects, and he originally designed this visualization tool to measure employee productivity and identify underperforming employees. After years of development, Gantt Chart has developed into a necessary tool for project planning and tracking.

This article mainly introduces how to use Matplotlib to draw Gantt chart and constantly optimize our visualization.

Cut the gossip and let's get started. :)

two。 Take a chestnut.

First of all, we import the Pandas and Numpy libraries, which can help us with data preprocessing.

Import pandas as pdimport matplotlib.pyplot as pltimport numpy as np

To give an example, a project-managed dataset is used here, and the corresponding read code is shown below:

Df = pd.read_excel ('.. / data/plan.xlsx') df

The results are as follows:

As shown in the figure above, we have a total of 14 Task, from TaskA to TaskM. Each line represents the number, the Task name, the department to which Task belongs, the Task start date, the Task end date, and how much has been completed.

3. Data preprocessing

In order to make our drawing easier, we need to add some variables.

First we need to set the entire project start date, and then we will add a column that represents the number of days from the project start date to the start of each subtask; this will help locate each subtask in the x direction.

Similarly, we add a column to the number of days from the project start date to the end of the subtask, which will help calculate the total number of days required to complete the subtask.

The code is as follows:

# project start dateproj_start = df.Start.min () # number of days from project start to task startdf ['start_num'] = (df.Start-proj_start). Dt.days# number of days from project start to end of tasksdf [' end_num'] = (df.End-proj_start). Dt.days# days between start and end of each taskdf ['days_start_to_end'] = df.end_num-df.start_num

The running results are as follows:

As shown in the figure above, we set the start date of the entire project to 2022-02-15, and we added three columns, in turn, the number of days that start_num used to represent the subtask start date to the entire project start date, end_num used to represent the subtask end date to the entire project start date, and days_start_to_end used to represent the number of days required to complete the subtask.

4. Draw a Gantt chart

With the above preparations, we can draw our Gantt chart. Here we use the bar graph in Matplotlib to draw.

The Y axis represents the task name, the width of each subitem represents the number of days between the start and end of the subtask, and the starting position of the subitem is the number of days from the beginning of the project to the start of the subtask.

The drawing code is as follows:

Fig, ax = plt.subplots (1, figsize= (16je 6)) ax.barh (df.Task, df.days_start_to_end, left=df.start_num) plt.show ()

The running results are as follows:

5. Add color

Looking at the figure above, we draw the simplest bar chart to represent project management. But it's too rough, so let's improve it step by step.

First of all, we look at the above figure, the sub-items in the bar chart are all of the same color, and the discrimination is not obvious, but each task in our data has a belonging department, and we can set different colors for different departments. The code is as follows:

# create a column with the color for each departmentdef color (row): c_dict = {'MKT':'#E64646',' FIN':'#E69646', 'ENG':'#34D05C',' PROD':'#34D0C3', 'IT':'#3475D0'} return c_dict [row [' Department']] df ['color'] = df.apply (color, axis=1)

At the same time, we observe that the x-axis in the above picture is a number, which is not intuitive, and we convert it into a date to be displayed every three days. So we optimize the x-axis date display code as follows:

From matplotlib.patches import Patchfig, ax = plt.subplots (1, figsize= (16recover6)) ax.barh (df.Task, df.days_start_to_end, left=df.start_num, color=df.color) # LEGENDS # c_dict = {'MKT':'#E64646',' FIN':'#E69646', 'ENG':'#34D05C',' PROD':'#34D0C3', 'IT':'#3475D0'} legend_elements = [Patch (facecolor=c_) [I] Label=i) for i in c_dict] plt.legend (handles=legend_elements) # TICKS # xticks = np.arange (0, df.end_num.max () + 1,3) xticks_labels = pd.date_range (proj_start, end=df.End.max ()) .strftime ("% m end=df.End.max% d") xticks_minor = np.arange (0, df.end_num.max () + 1,1) ax.set_xticks (xticks) ax.set_xticks (xticks_minor Minor=True) ax.set_xticklabels (xticks_labels [: 3]) plt.show ()

The running results are as follows:

6. Add transparency

Take a closer look at the picture above to see if it is much more beautiful than the first edition. We looked at our data and found that we still have a list of Completeness that we haven't visualized, and we know that it represents the degree of completion of each subtask. Then let's visualize the alignment.

# days between start and current progression of each taskdf ['current_num'] = (df.days_start_to_end * df.Completion)

We will create a new bar chart with subitems for the completion of each of the above subtasks. At the same time, we will write the percentage of completion at the end of the subitem.

To distinguish between completed and unfinished, we can use the parameter alpha to set the unfinished part to transparency.

The code is as follows:

From matplotlib.patches import Patchfig, ax = plt.subplots (1, figsize= (16jue 6)) # barsax.barh (df.Task, df.current_num, left=df.start_num, color=df.color) ax.barh (df.Task, df.days_start_to_end, left=df.start_num, color=df.color, alpha=0.5) # textsfor idx, row in df.iterrows (): ax.text (row.end_num+0.1, idx, f "{int (row.Completion*100)}%" Va='center', alpha=0.8) # LEGENDS # c_dict = {'MKT':'#E64646',' FIN':'#E69646', 'ENG':'#34D05C',' PROD':'#34D0C3', 'IT':'#3475D0'} legend_elements = [Patch (facecolor=c_dict [I], label=i) for i in c_dict] plt.legend (handles=legend_elements) # TICKS # xticks = np.arange (0 Df.end_num.max () + 1,3) xticks_labels = pd.date_range (proj_start, end=df.End.max ()) .strftime ("% mshock% d") xticks_minor = np.arange (0, df.end_num.max () + 1,1) ax.set_xticks (xticks) ax.set_xticks (xticks_minor, minor=True) ax.set_xticklabels (xticks_labels [: 3]) plt.show ()

The running results are as follows:

7. Re-optimization

Finally, in order to make our Gantt chart more attractive. We can draw gridlines and add our title to describe the purpose of the chart.

The code is long and is not pasting. There is a way to get the complete code later.

The final visualization results are as follows:

Of course, you can also set the background color to highlight the foreground entry. The effect is as follows:

After reading this article, I believe you have a certain understanding of "how Python uses Matplotlib to draw Gantt Chart". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report