Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Basic Gantt Chart Using Python Matplotlib
Project management requires careful planning, organization, and tracking of tasks and timelines. Gantt charts provide a visual representation of project schedules, task durations, and dependencies, enabling project managers to effectively plan, monitor, and communicate project progress.
In this article, we'll create basic Gantt charts using Python's powerful Matplotlib library. By leveraging Matplotlib's plotting capabilities, we can create dynamic and informative Gantt charts for project visualization and decision-making.
What is a Gantt Chart?
A Gantt chart is a horizontal bar chart that displays project tasks along a timeline. Each task is represented as a horizontal bar, where the length indicates the task duration and position shows when the task starts and ends.
Using Horizontal Bar Plots
The most straightforward approach uses Matplotlib's horizontal bar plots to create a Gantt chart. Each task appears as a horizontal bar with its start and end dates.
Example
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.dates as mdates
# Create project data
tasks = ['Planning', 'Development', 'Testing', 'Deployment']
start_dates = ['2023-06-01', '2023-06-03', '2023-06-06', '2023-06-09']
durations = [3, 4, 2, 5]
# Initialize figure and axis
fig, ax = plt.subplots(figsize=(10, 6))
# Create horizontal bars for each task
for i, task in enumerate(tasks):
start_date = pd.to_datetime(start_dates[i])
duration = pd.Timedelta(days=durations[i])
ax.barh(i, duration, left=start_date, height=0.5,
alpha=0.7, label=task)
# Customize the chart
ax.set_yticks(range(len(tasks)))
ax.set_yticklabels(tasks)
ax.set_xlabel('Timeline')
ax.set_ylabel('Project Tasks')
ax.set_title('Project Gantt Chart')
# Format dates on x-axis
ax.xaxis_date()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.xticks(rotation=45)
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
[Displays a horizontal bar chart showing four project tasks plotted along a timeline from June 1-14, 2023]
Enhanced Gantt Chart with Colors
We can improve the visualization by adding different colors for each task and displaying task durations ?
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.dates as mdates
import numpy as np
# Project data with additional details
project_data = {
'Task': ['Planning', 'Development', 'Testing', 'Deployment'],
'Start': ['2023-06-01', '2023-06-03', '2023-06-06', '2023-06-09'],
'Duration': [3, 4, 2, 5],
'Color': ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4']
}
df = pd.DataFrame(project_data)
df['Start_Date'] = pd.to_datetime(df['Start'])
df['End_Date'] = df['Start_Date'] + pd.to_timedelta(df['Duration'], unit='D')
# Create the chart
fig, ax = plt.subplots(figsize=(12, 6))
for i, row in df.iterrows():
ax.barh(i, row['Duration'], left=row['Start_Date'],
height=0.6, color=row['Color'], alpha=0.8)
# Add duration text on bars
mid_date = row['Start_Date'] + pd.Timedelta(days=row['Duration']/2)
ax.text(mid_date, i, f"{row['Duration']} days",
ha='center', va='center', fontweight='bold')
# Customize appearance
ax.set_yticks(range(len(df)))
ax.set_yticklabels(df['Task'])
ax.set_xlabel('Project Timeline')
ax.set_ylabel('Tasks')
ax.set_title('Enhanced Project Gantt Chart', fontsize=16, fontweight='bold')
# Format x-axis
ax.xaxis_date()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))
ax.xaxis.set_major_locator(mdates.DayLocator(interval=1))
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
[Displays a colorful Gantt chart with duration labels on each task bar]
Key Features of Our Gantt Chart
| Feature | Purpose | Implementation |
|---|---|---|
| Horizontal Bars | Show task duration | ax.barh() |
| Date Formatting | Display timeline clearly | mdates.DateFormatter() |
| Color Coding | Distinguish tasks |
color parameter |
| Grid Lines | Easy time reference | plt.grid() |
Conclusion
Matplotlib provides an excellent foundation for creating Gantt charts in Python. Use horizontal bar plots with date formatting for effective project timeline visualization. Enhanced features like color coding and duration labels make charts more informative for project management.
