代码之家  ›  专栏  ›  技术社区  ›  Nikko

Matplotlib绘图24小时,间隔1小时

  •  -1
  • Nikko  · 技术社区  · 6 年前

    嗨,我现在有这个情节。现在这个图显示了每滴答声间隔3小时。我想要所有的时间从0:00到23:59或者回到0:00,即00:00,01:00,02:00。。。23:00、23:59或00:00。

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.dates as md
    import pandas as pd
    
    df = pd.DataFrame({'toronto_time': ['2018-09-08 00:00:50',
                                        '2018-09-08 01:01:55',
                                        '2018-09-08 05:02:18',
                                        '2018-09-08 07:05:24',
                                        '2018-09-08 16:05:34',
                                        '2018-09-08 23:06:33'], 
                        'description': ['STATS', 'STATS', 'DEV_OL', 'STATS', 'STATS', 'CMD_ERROR']})
    df['toronto_time'] = pd.to_datetime(df['toronto_time'], format='%Y-%m-%d %H:%M:%S')
    
    fig, ax = plt.subplots(figsize=(8,6))
    plt.plot('toronto_time', 'description', data=df)
    ax.set_xlim(df['toronto_time'].min()-pd.Timedelta(1,'h'),
                df['toronto_time'].max()+pd.Timedelta(1,'h'))
    ax.xaxis.set_major_formatter(md.DateFormatter('%H:%M:%S'))
    plt.show()
    

    enter image description here

    1 回复  |  直到 6 年前
        1
  •  5
  •   tda    6 年前

    ax.xaxis.set_major_locator(md.HourLocator(interval = 1))
    

    完整示例如下:

    import matplotlib.pyplot as plt
    import matplotlib.dates as md
    import pandas as pd
    
    df = pd.DataFrame({'toronto_time': ['2018-09-08 00:00:50',
                                        '2018-09-08 01:01:55',
                                        '2018-09-08 05:02:18',
                                        '2018-09-08 07:05:24',
                                        '2018-09-08 16:05:34',
                                        '2018-09-08 23:06:33'],
                        'description': ['STATS', 'STATS', 'DEV_OL', 'STATS', 'STATS', 
                                        'CMD_ERROR']})
    df['toronto_time'] = pd.to_datetime(df['toronto_time'], format='%Y-%m-%d %H:%M:%S')
    
    fig, ax = plt.subplots(figsize=(8,6))
    
    plt.plot('toronto_time', 'description', data=df)
    ax.set_xlim(df['toronto_time'].min()-pd.Timedelta(1,'h'),
                df['toronto_time'].max()+pd.Timedelta(1,'h'))
    
    ax.xaxis.set_major_locator(md.HourLocator(interval = 1))
    ax.xaxis.set_major_formatter(md.DateFormatter('%H:%M:%S'))
    
    fig.autofmt_xdate()
    
    plt.show()  
    

    我还添加了 fig.autofmt_xdate() plt.show() 有助于格式化每小时频率,以防止x轴上的时间戳重叠。

    这将产生:

    enter image description here