'How to get gantt plot using matplotlib for task with Get start time is last night and end time is next morning

I am building a timetable for IOT devices. I refer to similar questions on stackoverflow, and I have built a chart that is close to the finished product, but I encounter that the chart cannot be displayed properly at different times, especially when one day spans different dates For example, 1/1 goes to bed at 21 o'clock in the evening and the next day 1/2 gets up at 08 in the morning The chart will be wrong, I've tried everything but can't solve this problem

enter image description here

enter image description here

enter code here

    import pandas as pd
    import matplotlib.pyplot as plt
    import math
    import matplotlib.dates as md

    DF= pd.DataFrame()
    for x in report.from_to_compliance_list:
        if len(x.time) != 0:
            for a in x.time:
                new_box = pd.Series({'start':a.from_time, 'finish': a.to_time, 'date': x.date})
                DF = DF.append(new_box, ignore_index=True)
    DF['Start_device_time'] = pd.to_datetime(DF['start'], format='%H:%M')
    DF['Finish_device_time'] = pd.to_datetime(DF['finish'], format='%H:%M')

    fig, ax = plt.subplots(figsize=(10, 3))
    dates = pd.unique(DF['date'])
    colors = plt.cm.tab10.colors 
    colors *= math.ceil(len(dates) / (len(colors)))  

    for date, color in zip(dates, colors):
        for row in DF[DF['date'] == date].itertuples():
            left = timestr_to_num(row.start)
            right = timestr_to_num(row.finish)
            ax.barh(date, left=left, width=right - left, height=0.8, color=color)
    
    ax.set_xlim(
        DF['Start_device_time'].min()-pd.Timedelta(1,'h'),
        DF['Finish_device_time'].max()+pd.Timedelta(1,'h')
    )
    ax.xaxis.set_major_formatter(md.DateFormatter('%H:%M'))
    ax.xaxis.set_major_locator(md.HourLocator(interval = 1))
    fig.set_figheight(14)
    fig.set_figwidth(20)
    fig.savefig('reportImages/usage_record.png')


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source