How to Resolve the \'Year Out of Range\' Error when Plotting Dates on the X-Axis?

Linda Hamilton
Release: 2024-10-17 13:45:29
Original
507 people have browsed it

How to Resolve the

Plotting Dates on the X-Axis: Resolving the "Year Out of Range" Error

When encountering the error "ValueError: year is out of range" while plotting dates on the x-axis using plot_date(), consider using the simpler plot() function instead. Here's how:

Convert Strings to Datetime Objects:

<code class="python">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]</code>
Copy after login

Plot with Datetime Formatting:

<code class="python">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()</code>
Copy after login

Result:

This simpler approach will plot the dates on the x-axis correctly, as shown in the image below:

[Image of plot with dates on the x-axis]

The above is the detailed content of How to Resolve the \'Year Out of Range\' Error when Plotting Dates on the X-Axis?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!