大熊猫从每日到每月绘制x轴

时间:2018-02-12 14:39:44

标签: python matplotlib plot

我试图绘制股票价格和波动率。但是,x轴重叠。有谁知道如何从正确的频率更新"每日"每月或有任何自动适应功能?感谢

import tushare as ts
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 'sh' for shanghai A share, other single stocks are six-digit codes
Ahist = ts.get_hist_data('sh', start='2017-01-01', end='2018-02-12') 
dfA = pd.DataFrame(Ahist)
A_basic = dfA[['close','ma5', 'ma10','ma20','price_change','p_change']]
A_basic.sort_index()
fig = plt.figure(figsize = (15,12))
plt.xticks(pd.date_range(A_basic.index[0], A_basic.index[-1], freq = '30D'))
fig1 = fig.add_subplot(2,1,1, xlabel='Date', ylabel='Price')
fig2 = fig.add_subplot(2,1,2, xlabel='Date', ylabel='Volatility')
#fig.autofmt_xdate() #not working here
fig1.plot(A_basic['close'])
vol = A_basic['p_change'].rolling(5).std() * np.sqrt(5) #calc volatility
fig2.plot(vol)
plt.grid(True)
plt.show()

enter image description here

1 个答案:

答案 0 :(得分:0)

我自己想通了。

索引类型是索引,而不是日期。需要转换。添加:

A_basic.index = pd.to_datetime(A_basic.index)