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
How to plot a stacked event duration using Python Pandas?
To plot a stacked event duration using Python Pandas, you create horizontal lines that represent different events over time periods. This visualization is useful for displaying timelines, project schedules, or any data with start and end times.
Steps to Create a Stacked Event Duration Plot
- Set the figure size and adjust the padding between and around the subplots
- Create a DataFrame with lists of xmin (start times) and corresponding xmax (end times)
- Use hlines() method to plot horizontal lines representing event durations
- Display the figure using show() method
Example
Here's how to create a stacked event duration plot with sample date ranges ?
import pandas as pd
from datetime import datetime as dt
import matplotlib.pyplot as plt
# Set figure parameters
plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True
# Create DataFrame with event start and end dates
df = pd.DataFrame({
'xmin': [
dt.strptime('1994-07-19', '%Y-%m-%d'),
dt.strptime('2006-03-16', '%Y-%m-%d'),
dt.strptime('1980-10-31', '%Y-%m-%d'),
dt.strptime('1981-06-11', '%Y-%m-%d'),
dt.strptime('2006-06-28', '%Y-%m-%d')
],
'xmax': [
dt.strptime('1998-06-30', '%Y-%m-%d'),
dt.strptime('2007-01-24', '%Y-%m-%d'),
dt.strptime('2007-07-31', '%Y-%m-%d'),
dt.strptime('1990-08-01', '%Y-%m-%d'),
dt.strptime('2007-01-24', '%Y-%m-%d')
]
})
# Create the stacked event duration plot
plt.hlines(df.index, df.xmin, df.xmax, linewidth=6, colors='red', alpha=0.7)
plt.xlabel('Timeline')
plt.ylabel('Event Index')
plt.title('Stacked Event Duration Plot')
plt.grid(True, alpha=0.3)
plt.show()
Enhanced Example with Multiple Colors
You can also create a more visually appealing plot with different colors for each event ?
import pandas as pd
from datetime import datetime as dt
import matplotlib.pyplot as plt
# Create DataFrame with event data including labels
df = pd.DataFrame({
'event': ['Project A', 'Project B', 'Project C', 'Project D', 'Project E'],
'start_date': [
dt.strptime('1994-07-19', '%Y-%m-%d'),
dt.strptime('2006-03-16', '%Y-%m-%d'),
dt.strptime('1980-10-31', '%Y-%m-%d'),
dt.strptime('1981-06-11', '%Y-%m-%d'),
dt.strptime('2006-06-28', '%Y-%m-%d')
],
'end_date': [
dt.strptime('1998-06-30', '%Y-%m-%d'),
dt.strptime('2007-01-24', '%Y-%m-%d'),
dt.strptime('2007-07-31', '%Y-%m-%d'),
dt.strptime('1990-08-01', '%Y-%m-%d'),
dt.strptime('2007-01-24', '%Y-%m-%d')
]
})
plt.figure(figsize=(12, 6))
# Create plot with different colors
colors = ['red', 'blue', 'green', 'orange', 'purple']
for i, (start, end) in enumerate(zip(df.start_date, df.end_date)):
plt.hlines(i, start, end, linewidth=8, colors=colors[i], alpha=0.8, label=df.event[i])
plt.yticks(range(len(df)), df.event)
plt.xlabel('Timeline')
plt.ylabel('Projects')
plt.title('Project Timeline - Stacked Event Duration')
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
Key Parameters for hlines()
| Parameter | Description | Example Value |
|---|---|---|
y |
Y-axis positions for lines | df.index |
xmin |
Start positions on X-axis | df.start_date |
xmax |
End positions on X-axis | df.end_date |
linewidth |
Thickness of lines | 6 |
colors |
Line colors |
'red' or list of colors |
alpha |
Transparency (0-1) | 0.7 |
Conclusion
Stacked event duration plots are excellent for visualizing timelines and overlapping events. Use plt.hlines() with start and end dates to create these horizontal timeline visualizations. Customize colors, line width, and transparency to make your plots more informative and visually appealing.
