2017-09-20 26 views
0

我有一個使用pandas和matplotlib製作的時間序列圖。我的功能看起來是這樣的:在matplotlib圖上創建軸日期的值

def graph(file): 
    pdf = PdfPages('...pdf') 
    # Temporal Change (Time Series) 
    pd.read_csv(file, usecols=['close','open']).plot() 
    plt.xlabel('Date') 
    plt.ylabel('Value') 
    plt.title('Open/Close Over Time') 
    plt.show() 

我的數據文件具有的值對應的報頭和日期標頭是索引爲0(如果那是相關的?)

眼下圖形作品,但指數該值將顯示時間而不是日期。我如何讓x軸(日期)顯示與數據對應的日期而不是索引?

編輯:數據文件看起來像這樣

date close volume open high low 
2017/09/13 173.05 9112378 173.01 173.17 172.06 
2017/09/12 172.96 11179730 173.76 174 171.75 
2017/09/11 173.51 12353760 172.4 173.89 172.2 
2017/09/08 170.95 10985350 173.09 173.49 170.8 
2017/09/07 173.21 18039640 171.94 173.3067 170.27 
2017/09/06 172.09 13886740 170.91 172.48 169.57 
2017/09/05 170.72 13214940 171.27 172.3875 169.55 
2017/09/01 172.02 11663360 172.4 172.915 171.31 
2017/08/31 171.97 17216280 170.4 172.145 170.06 

是一個.csv文件,^這是從它是開放在Excel中複製

回答

3

如果你要使用熊貓的繪圖方法,並希望日期時間,我建議確保您解析日期並將其設置爲索引。我也推薦面向對象的matplotlib接口。

from io import StringIO 
from matplotlib import pyplot 
import pandas 

datafile = StringIO("""\ 
date close volume open high low 
2017/09/13 173.05 9112378 173.01 173.17 172.06 
2017/09/12 172.96 11179730 173.76 174 171.75 
2017/09/11 173.51 12353760 172.4 173.89 172.2 
2017/09/08 170.95 10985350 173.09 173.49 170.8 
2017/09/07 173.21 18039640 171.94 173.3067 170.27 
2017/09/06 172.09 13886740 170.91 172.48 169.57 
2017/09/05 170.72 13214940 171.27 172.3875 169.55 
2017/09/01 172.02 11663360 172.4 172.915 171.31 
2017/08/31 171.97 17216280 170.4 172.145 170.06 
""") 

fig, ax = pyplot.subplots(figsize=(7, 5)) 
_ = (
    pandas.read_csv(datafile, sep='\s+', 
        usecols=['date', 'open', 'close'], 
        parse_dates=['date']) 
     .set_index('date') 
     .plot(ax=ax) 
) 
ax.set_xlabel('Date') 
ax.set_ylabel('BUY! SELL!') 
ax.set_title('Money money money money') 

enter image description here

+0

我試圖實現這一點,但仍然圖形不使用日期 –

+0

原帖被編輯到顯示數據文件 –

+1

@CassieH。用你的數據更新了我的答案 –

相關問題