首页  >  文章  >  后端开发  >  在 X 轴上绘制日期时如何解决“年份超出范围”错误?

在 X 轴上绘制日期时如何解决“年份超出范围”错误?

Linda Hamilton
Linda Hamilton原创
2024-10-17 13:45:29508浏览

How to Resolve the

在 X 轴上绘制日期:解决“年份超出范围”错误

遇到错误“ValueError:year is使用plot_date() 在 x 轴上绘制日期时超出范围”,请考虑使用更简单的plot() 函数。操作方法如下:

将字符串转换为日期时间对象:

<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>

使用日期时间格式绘图:

<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>

结果:

这种更简单的方法将正确地在 x 轴上绘制日期,如下图所示:

[x 轴上带有日期的绘图图像-轴]

以上是在 X 轴上绘制日期时如何解决“年份超出范围”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn