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?
Use the xlabel() method in matplotlib to add a label to the plot's x-axis.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With