Plotting time in Python with Matplotlib Plotting time in Python with Matplotlib python python

Plotting time in Python with Matplotlib


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:

dates = matplotlib.dates.date2num(list_of_datetimes)matplotlib.pyplot.plot_date(dates, values)


You can also plot the timestamp, value pairs using pyplot.plot (after parsing them from their string representation). (Tested with matplotlib versions 1.2.0 and 1.3.1.)

Example:

import datetimeimport randomimport matplotlib.pyplot as plt# make up some datax = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(12)]y = [i+random.gauss(0,1) for i,_ in enumerate(x)]# plotplt.plot(x,y)# beautify the x-labelsplt.gcf().autofmt_xdate()plt.show()

Resulting image:

Line Plot


Here's the same as a scatter plot:

import datetimeimport randomimport matplotlib.pyplot as plt# make up some datax = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(12)]y = [i+random.gauss(0,1) for i,_ in enumerate(x)]# plotplt.scatter(x,y)# beautify the x-labelsplt.gcf().autofmt_xdate()plt.show()

Produces an image similar to this:

Scatter Plot


7 years later and this code has helped me.However, my times still were not showing up correctly.

enter image description here

Using Matplotlib 2.0.0 and I had to add the following bit of code from Editing the date formatting of x-axis tick labels in matplotlib by Paul H.

import matplotlib.dates as mdatesmyFmt = mdates.DateFormatter('%d')ax.xaxis.set_major_formatter(myFmt)

I changed the format to (%H:%M) and the time displayed correctly.enter image description here

All thanks to the community.