Search code examples
pythonmatplotlibtimestampx-axis

Plotting time on the independent axis


I have an array of timestamps in the format (HH:MM:SS.mmmmmm) and another array of floating point numbers, each corresponding to a value in the timestamp array.

Can I plot time on the x axis and the numbers on the y-axis using Matplotlib?

I was trying to, but somehow it was only accepting arrays of floats. How can I get it to plot the time? Do I have to modify the format in any way?


Solution

  • Update:

    This answer is outdated since matplotlib version 3.5. The plot function now handles datetime data directly. See https://matplotlib.org/3.5.1/api/_as_gen/matplotlib.pyplot.plot_date.html

    The use of plot_date is discouraged. This method exists for historic reasons and may be deprecated in the future.

    datetime-like data should directly be plotted using plot.

    If you need to plot plain numeric data as Matplotlib date format or need to set a timezone, call ax.xaxis.axis_date / ax.yaxis.axis_date before plot. See Axis.axis_date.


    Old, outdated answer:

    You must first convert your timestamps to Python datetime objects (use datetime.strptime). Then use date2num to convert the dates to matplotlib format.

    Plot the dates and values using plot_date:

    import matplotlib.pyplot as plt
    import matplotlib.dates
    
    from datetime import datetime
    
    x_values = [datetime(2021, 11, 18, 12), datetime(2021, 11, 18, 14), datetime(2021, 11, 18, 16)]
    y_values = [1.0, 3.0, 2.0]
    
    dates = matplotlib.dates.date2num(x_values)
    plt.plot_date(dates, y_values)
    

    enter image description here