如何轉換非標準日期格式以在 Python 中繪圖?

Patricia Arquette
發布: 2024-10-17 13:48:30
原創
362 人瀏覽過

How to Convert Non-Standard Date Formats for Plotting in Python?

Converting Dates to Plottable Format

Plotting data against dates can be challenging when dates are stored in non-standard formats. In the given case, the date format is "01/02/1991". To simplify the plotting process, we can convert these dates into a format acceptable by the plot function of matplotlib.

To begin, convert the strings into instances of Python datetime.date:

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

The next step is to plot the data. Instead of using plot_date(), which encountered the error, we can use the simpler plot() instead:

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

By following these steps, you can now plot your information effectively against dates in the desired format.

以上是如何轉換非標準日期格式以在 Python 中繪圖?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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