- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) > 編程語(yǔ)言 >
- Python中怎么實(shí)現時(shí)間序列可視化
Python中怎么實(shí)現時(shí)間序列可視化,相信很多沒(méi)有經(jīng)驗的人對此束手無(wú)策,為此本文總結了問(wèn)題出現的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。
1.單個(gè)時(shí)間序列
首先,我們從tushare.pro獲取指數日線(xiàn)行情數據,并查看數據類(lèi)型。
import tushare as ts import pandas as pd pd.set_option('expand_frame_repr', False) # 顯示所有列 ts.set_token('your token') pro = ts.pro_api() df = pro.index_daily(ts_code='399300.SZ')[['trade_date', 'close']] df.sort_values('trade_date', inplace=True) df.reset_index(inplace=True, drop=True) print(df.head()) trade_date close 0 20050104 982.794 1 20050105 992.564 2 20050106 983.174 3 20050107 983.958 4 20050110 993.879 print(df.dtypes) trade_date object close float64 dtype: object
交易時(shí)間列'trade_date' 不是時(shí)間類(lèi)型,而且也不是索引,需要先進(jìn)行轉化。
df['trade_date'] = pd.to_datetime(df['trade_date']) df.set_index('trade_date', inplace=True) print(df.head()) close trade_date 2005-01-04 982.794 2005-01-05 992.564 2005-01-06 983.174 2005-01-07 983.958 2005-01-10 993.879
接下來(lái),就可以開(kāi)始畫(huà)圖了,我們需要導入matplotlib.pyplot【2】,然后通過(guò)設置set_xlabel()和set_xlabel()為x軸和y軸添加標簽。
import matplotlib.pyplot as plt ax = df.plot(color='') ax.set_xlabel('trade_date') ax.set_ylabel('399300.SZ close') plt.show()
matplotlib庫中有很多內置圖表樣式可以選擇,通過(guò)打印plt.style.available查看具體都有哪些選項,應用的時(shí)候直接調用plt.style.use('fivethirtyeight')即可。
print(plt.style.available) ['bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark-palette', 'seaborn-dark', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'seaborn', 'Solarize_Light2', 'tableau-colorblind10', '_classic_test'] plt.style.use('fivethirtyeight') ax1 = df.plot() ax1.set_title('FiveThirtyEight Style') plt.show()
2.設置更多細節
上面畫(huà)出的是一個(gè)很簡(jiǎn)單的折線(xiàn)圖,其實(shí)可以在plot()里面通過(guò)設置不同參數的值,為圖添加更多細節,使其更美觀(guān)、清晰。
figsize(width, height)設置圖的大小,linewidth設置線(xiàn)的寬度,fontsize設置字體大小。然后,調用set_title()方法設置標題。
ax = df.plot(color='blue', figsize=(8, 3), linewidth=2, fontsize=6) ax.set_title('399300.SZ close from 2005-01-04 to 2019-07-04', fontsize=8) plt.show()
如果想要看某一個(gè)子時(shí)間段內的折線(xiàn)變化情況,可以直接截取該時(shí)間段再作圖即可,如df['2018-01-01': '2019-01-01']
dfdf_subset_1 = df['2018-01-01':'2019-01-01'] ax = df_subset_1.plot(color='blue', fontsize=10) plt.show()
如果想要突出圖中的某一日期或者觀(guān)察值,可以調用.axvline()和.axhline()方法添加垂直和水平參考線(xiàn)。
ax = df.plot(color='blue', fontsize=6) ax.axvline('2019-01-01', color='red', linestyle='--') ax.axhline(3000, color='green', linestyle='--') plt.show()
也可以調用axvspan()的方法為一段時(shí)間添加陰影標注,其中alpha參數設置的是陰影的透明度,0代表完全透明,1代表全色。
ax = df.plot(color='blue', fontsize=6) ax.axvspan('2018-01-01', '2019-01-01', color='red', alpha=0.3) ax.axhspan(2000, 3000, color='green', alpha=0.7) plt.show()
3.移動(dòng)平均時(shí)間序列
有時(shí)候,我們想要觀(guān)察某個(gè)窗口期的移動(dòng)平均值的變化趨勢,可以通過(guò)調用窗口函數rolling來(lái)實(shí)現。下面實(shí)例中顯示的是,以250天為窗口期的移動(dòng)平均線(xiàn)close,以及與移動(dòng)標準差的關(guān)系構建的上下兩個(gè)通道線(xiàn)upper和lower。
ma = df.rolling(window=250).mean() mstd = df.rolling(window=250).std() ma['upper'] = ma['close'] + (mstd['close'] * 2) ma['lower'] = ma['close'] - (mstd['close'] * 2) ax = ma.plot(linewidth=0.8, fontsize=6) ax.set_xlabel('trade_date', fontsize=8) ax.set_ylabel('399300.SZ close from 2005-01-04 to 2019-07-04', fontsize=8) ax.set_title('Rolling mean and variance of 399300.SZ cloe from 2005-01-04 to 2019-07-04', fontsize=10) plt.show()
4.多個(gè)時(shí)間序列
如果想要可視化多個(gè)時(shí)間序列數據,同樣可以直接調用plot()方法。示例中我們從tushare.pro上面選取三只股票的日線(xiàn)行情數據進(jìn)行分析。
# 獲取數據 code_list = ['000001.SZ', '000002.SZ', '600000.SH'] data_list = [] for code in code_list: print(code) df = pro.daily(ts_code=code, start_date='20180101', end_date='20190101')[['trade_date', 'close']] df.sort_values('trade_date', inplace=True) df.rename(columns={'close': code}, inplace=True) df.set_index('trade_date', inplace=True) data_list.append(df) df = pd.concat(data_list, axis=1) print(df.head()) 000001.SZ 000002.SZ 600000.SH 000001.SZ 000002.SZ 600000.SH trade_date 20180102 13.70 32.56 12.72 20180103 13.33 32.33 12.66 20180104 13.25 33.12 12.66 20180105 13.30 34.76 12.69 20180108 12.96 35.99 12.68 # 畫(huà)圖 ax = df.plot(linewidth=2, fontsize=12) ax.set_xlabel('trade_date') ax.legend(fontsize=15) plt.show()
調用.plot.area()方法可以生成時(shí)間序列數據的面積圖,顯示累計的總數。
ax = df.plot.area(fontsize=12) ax.set_xlabel('trade_date') ax.legend(fontsize=15) plt.show()
如果想要在不同子圖中單獨顯示每一個(gè)時(shí)間序列,可以通過(guò)設置參數subplots=True來(lái)實(shí)現。layout指定要使用的行列數,sharex和sharey用于設置是否共享行和列,colormap='viridis' 為每條線(xiàn)設置不同的顏色。
df.plot(subplots=True, layout=(2, 2), sharex=False, sharey=False, colormap='viridis', fontsize=7, legend=False, linewidth=0.3) plt.show()
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。
Copyright ? 2009-2022 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 特網(wǎng)科技 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 百度云 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站