在 X 軸上繪製日期時如何解決「年份超出範圍」錯誤?

Linda Hamilton
發布: 2024-10-17 13:45:29
原創
507 人瀏覽過

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>
登入後複製

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>
登入後複製

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]

以上是在 X 軸上繪製日期時如何解決「年份超出範圍」錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!