Search code examples
pythonmatplotlib

How to plot times on the x-axis with matplotlib?


Following the example given HERE I want to create a plot that shows just the time on the x-axis, not the date. So I modified the example code to the following:

from datetime import datetime as dt
from matplotlib import pyplot as plt, dates as mdates

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

dates = ["01/02/2020 10:00", "01/02/2020 10:05", "01/02/2020 10:10"]
x_values = [dt.strptime(d, "%m/%d/%Y %H:%M").date() for d in dates]
y_values = [1, 2, 3]
ax = plt.gca()

formatter = mdates.DateFormatter("%H:%M")
ax.xaxis.set_major_formatter(formatter)
locator = mdates.HourLocator()
ax.xaxis.set_major_locator(locator)
plt.plot(x_values, y_values)

plt.show()

but instead of showing a range in time from 10:00 to 10:10 I get the following:

enter image description here

What is wrong?


Solution

  • I think two issues were that the time information was being discarded when you had .date() chained to .strptime(...), and secondly HourLocator was being used instead of MinuteLocator.

    from datetime import datetime as dt
    from matplotlib import pyplot as plt, dates as mdates
    
    plt.rcParams["figure.figsize"] = [7.50, 3.50]
    plt.rcParams["figure.autolayout"] = True
    
    dates = ["01/02/2020 10:00", "01/02/2020 10:05", "01/02/2020 10:10"]
    x_values = [dt.strptime(d, "%m/%d/%Y %H:%M") for d in dates]
    y_values = [1, 2, 3]
    ax = plt.gca()
    
    formatter = mdates.DateFormatter("%H:%M")
    ax.xaxis.set_major_formatter(formatter)
    
    #Comment out to show fewer minute ticks
    locator = mdates.MinuteLocator()
    ax.xaxis.set_major_locator(locator)
    
    plt.plot(x_values, y_values, 'o-');
    

    enter image description here