排除 X 軸繪圖的日期時間轉換錯誤

Linda Hamilton
發布: 2024-10-17 13:47:02
原創
361 人瀏覽過

Troubleshooting Date-Time Conversion Errors for X-Axis Plotting

Plotting Dates on the X-Axis: A Troubleshooting Guide

When plotting data against dates, it is essential to convert the dates into a format that matplotlib can interpret. However, if you encounter "year is out of range" errors, it indicates an issue with the date conversion process.

Let's address the situation you described:

Problem: Converting dates in "01/02/1991" format results in an error when using plot_date().

Solution:

Instead of using plot_date(), consider using the more straightforward plot() function. To prepare your dates for plotting:

  1. Import Python's datetime library and convert your strings to datetime.date instances:
<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>
登入後複製
  1. Plot the data using plot():
<code class="python">import matplotlib.pyplot as plt
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>
登入後複製

This approach will correctly plot your data against the dates specified on the x-axis, resolving the error you encountered.

以上是排除 X 軸繪圖的日期時間轉換錯誤的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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