Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting dates on the x-axis with Python's matplotlib

I am trying to plot information against dates. I have a list of dates in the format "01/02/1991".

I converted them by doing the following:

x = parser.parse(date).strftime('%Y%m%d')) 

which gives 19910102

Then I tried to use num2date

import matplotlib.dates as dates new_x = dates.num2date(x) 

Plotting:

plt.plot_date(new_x, other_data, fmt="bo", tz=None, xdate=True) 

But I get an error. It says "ValueError: year is out of range". Any solutions?

like image 308
irl_irl Avatar asked Mar 09 '12 01:03

irl_irl


People also ask

How do I add x-axis labels in matplotlib?

Use the xlabel() method in matplotlib to add a label to the plot's x-axis.


1 Answers

You can do this more simply using plot() instead of plot_date().

First, convert your strings to instances of Python datetime.date:

import datetime as dt  dates = ['01/02/1991','01/03/1991','01/04/1991'] x = [dt.datetime.strptime(d,'%m/%d/%Y').date() for d in dates] y = range(len(x)) # many thanks to Kyss Tao for setting me straight here 

Then plot:

import matplotlib.pyplot as plt import matplotlib.dates as mdates  plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y')) plt.gca().xaxis.set_major_locator(mdates.DayLocator()) plt.plot(x,y) plt.gcf().autofmt_xdate() 

Result:

enter image description here

like image 193
mechanical_meat Avatar answered Oct 03 '22 07:10

mechanical_meat