plot time of day vs date in matplotlib

前端 未结 2 1390
一整个雨季
一整个雨季 2020-12-19 08:48

I want to plot, in a specific few ways, dates on the x axis and time of day on the y axis, and then have either line plots or interval (floating bar) plots.

This S

2条回答
  •  盖世英雄少女心
    2020-12-19 09:29

    I think you're slightly confused as to exactly how matplotlib handles times and dates behind the scenes.

    All datetimes in matplotlib are represented as simple floats. 1 day corresponds to a difference of 1.0, and the dates are in days since 1900 (if I remember correctly, anyway).

    So, in order to plot just the time of a given date, you need to use a % 1.

    I'm going to use points, but you can easily use bars. Look into using the bottom keyword argument if you do use plt.bar, so that the bottom of the bars will start at the start time of your intervals (and remember that the second argument is the height of the bar, not its top y-value).

    For example:

    import matplotlib.pyplot as plt
    import matplotlib as mpl
    import numpy as np
    import datetime as dt
    
    # Make a series of events 1 day apart
    x = mpl.dates.drange(dt.datetime(2009,10,1), 
                         dt.datetime(2010,1,15), 
                         dt.timedelta(days=1))
    # Vary the datetimes so that they occur at random times
    # Remember, 1.0 is equivalent to 1 day in this case...
    x += np.random.random(x.size)
    
    # We can extract the time by using a modulo 1, and adding an arbitrary base date
    times = x % 1 + int(x[0]) # (The int is so the y-axis starts at midnight...)
    
    # I'm just plotting points here, but you could just as easily use a bar.
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot_date(x, times, 'ro')
    ax.yaxis_date()
    fig.autofmt_xdate()
    
    plt.show()
    

    Time vs. Date

    Hopefully that helps a bit!

提交回复
热议问题