溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何在Matplotlib中繪制時(shí)間序列數(shù)據(jù)

發(fā)布時(shí)間:2021-12-02 17:34:18 來(lái)源:億速云 閱讀:566 作者:小新 欄目:大數(shù)據(jù)

這篇文章主要介紹了如何在Matplotlib中繪制時(shí)間序列數(shù)據(jù),具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

背景介紹

將學(xué)習(xí)如何在Matplotlib中繪制時(shí)間序列數(shù)據(jù)。時(shí)間序列數(shù)據(jù)由包含日期的數(shù)據(jù)組成。例如繪制在過(guò)去幾周內(nèi)比特幣價(jià)格走勢(shì)。我們將學(xué)習(xí)如何以不同方式格式化日期,以便它們更好地與我們的圖形一起使用。讓我們開(kāi)始吧...

如何在Matplotlib中繪制時(shí)間序列數(shù)據(jù)


入門實(shí)例

首先來(lái)看一個(gè)基本的時(shí)間序列圖,以及格式化x軸的日期顯示方式:

from datetime import datetime,timedeltafrom matplotlib import pyplot as pltfrom matplotlib import dates as mpl_dates#設(shè)置圖表樣式plt.style.use('seaborn')#讀取數(shù)據(jù)dates_x = [  datetime(2019,7,24),  datetime(2019,7,25),  datetime(2019,7,26),  datetime(2019,7,27),  datetime(2019,7,28),  datetime(2019,7,29),  datetime(2019,7,30)]#縱軸數(shù)據(jù)y列表y = [0,1,3,5,7,8,9]#繪制時(shí)間序列圖表plt.plot_date(dates_x,y,lineStyle='solid')#格式化x軸日期顯示plt.gcf().autofmt_xdate()#指定顯示的格式date_format = mpl_dates.DateFormatter('%m/%d/%Y')plt.gca().xaxis.set_major_formatter(date_format)plt.tight_layout()plt.show()
 

運(yùn)行結(jié)果:

如何在Matplotlib中繪制時(shí)間序列數(shù)據(jù)

 

綜合實(shí)例

我們從一個(gè)數(shù)據(jù)文件中data.csv讀取過(guò)去一段時(shí)間關(guān)于比特幣的價(jià)格收盤價(jià)的數(shù)據(jù)走勢(shì),內(nèi)容大致如下:

如何在Matplotlib中繪制時(shí)間序列數(shù)據(jù)

實(shí)現(xiàn):import pandas as pdfrom datetime import datetime,timedeltafrom matplotlib import pyplot as pltfrom matplotlib import dates as mpl_datesfrom matplotlib import font_managerfrom pandas.plotting import \register_matplotlib_convertersregister_matplotlib_converters()#設(shè)置圖表樣式plt.style.use('seaborn')#讀取數(shù)據(jù)data = pd.read_csv('data.csv')#csv文件中數(shù)據(jù)中date為str類型#這里做處理方便展示圖表時(shí)#能夠按照日期排序顯示data['Date'] = pd.to_datetime(data['Date'])data.sort_values('Date', inplace=True)price_date = data['Date']price_close = data['Close']#調(diào)用plot_date()#顯示時(shí)間序列數(shù)據(jù)圖表plt.plot_date(price_date, price_close,       linestyle='solid')#格式化x軸日期顯示plt.gcf().autofmt_xdate()zh_font = font_manager.\FontProperties(fname='C:\\Windows\\Fonts\\msyh.ttf')plt.title('比特幣價(jià)格',fontproperties=zh_font)plt.xlabel('日期',fontproperties=zh_font)plt.ylabel('收盤價(jià)',fontproperties=zh_font)plt.tight_layout()plt.show()
 

運(yùn)行結(jié)果:

如何在Matplotlib中繪制時(shí)間序列數(shù)據(jù)

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“如何在Matplotlib中繪制時(shí)間序列數(shù)據(jù)”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI