Last active
May 2, 2024 23:23
-
-
Save angusdev/19d0574c43be948cd0133fc2044b2460 to your computer and use it in GitHub Desktop.
jobchart.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
import matplotlib.pyplot as plt | |
from matplotlib.dates import DateFormatter | |
import mplcursors | |
# Sample data | |
data = { | |
'Date': ['1-Apr-2024', '1-Apr-2024', '1-Apr-2024', '4-Apr-2024', '5-Apr-2024', '6-Apr-2024'], | |
'Job': ['FOO', 'FOO', 'FOO', 'FOO', 'FOO', 'FOO'], | |
'Start': ['1-Apr-2024 13:12:24', '1-Apr-2024 15:23:44', '1-Apr-2024 23:12:52', | |
'4-Apr-2024 13:22:30', '5-Apr-2024 14:38:01', '7-Apr-2024 12:00:00'], | |
'End': ['1-Apr-2024 14:24:17', '1-Apr-2024 16:25:27', '2-Apr-2024 00:04:19', | |
'4-Apr-2024 14:54:18', '5-Apr-2024 15:47:37', None] | |
} | |
# Convert to DataFrame | |
df = pd.DataFrame(data) | |
df['Start'] = pd.to_datetime(df['Start'], format='%d-%b-%Y %H:%M:%S') | |
df['End'] = pd.to_datetime(df['End'], format='%d-%b-%Y %H:%M:%S') | |
df['Date'] = pd.to_datetime(df['Date'], format='%d-%b-%Y') | |
df['AdjustedEnd'] = df.apply(lambda row: row['End'] if pd.notnull(row['End']) else row['Start'] + pd.Timedelta(minutes=30), axis=1) | |
min_date = df['Date'].min() | |
date_diff = df['Date'] - min_date | |
df['Start'] = df['Start'] - date_diff | |
df['AdjustedEnd'] = df['AdjustedEnd'] - date_diff | |
min_start_time = df['Start'].min() - pd.Timedelta(minutes=30) | |
max_end_time = max(df['Start'].max(), df['AdjustedEnd'].max()) + pd.Timedelta(minutes=30) | |
# Assign a numerical value to each date | |
date_values = {date: i for i, date in enumerate(df['Date'].unique())} | |
# Plotting | |
fig, ax = plt.subplots(figsize=(10, 8)) | |
for date, group in df.groupby('Date'): | |
for job, start_time, end_time, duration in zip(group['Job'], group['Start'], group['End'], group['AdjustedEnd'] - group['Start']): | |
color = 'red' if pd.isnull(end_time) else 'blue' | |
formatted_date = date.strftime('%d-%b') | |
ax.barh(f'{formatted_date} {job}', duration.total_seconds() / 86400, left=start_time, height=0.5, color=color) | |
# Set y-ticks to display date labels | |
ax.set_yticks(list(date_values.values())) | |
ax.set_yticklabels([date.strftime('%d-%b') for date in date_values.keys()]) | |
ax.set_xlabel('Duration (hours)') | |
ax.set_ylabel('Date - Job') | |
ax.set_title('Running Duration of Each Job Based on Start and End Time') | |
ax.xaxis.set_major_formatter(DateFormatter('%H:%M')) | |
ax.set_xlim(min_start_time, max_end_time) | |
ax.grid(axis='y') | |
# Use mplcursors to display tooltips | |
mplcursors.cursor(hover=True) | |
plt.tight_layout() | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment