2016-05-16 138 views
1

鑑於以下數據幀和產生的透視表:Matplotlib線圖與熊貓透視表

import pandas as pd 
import numpy as np 
%matplotlib inline 
df = pd.DataFrame(
     {'YYYYMM':[201603,201503,201403,201303,201603,201503,201403,201303], 
     'Count':[5,6,2,7,4,7,8,9], 
     'Group':['A','A','A','A','B','B','B','B']}) 
df['YYYYMM']=df['YYYYMM'].astype(str).str[:-2].astype(np.int64) 
t=df.pivot_table(df,index=['YYYYMM'],columns=['Group'],aggfunc=np.sum) 


    Count 
Group A B 
YYYYMM  
2013 7 9 
2014 2 8 
2015 6 7 
2016 5 4 

我要繪製它來創建與所述y軸刻度標記標籤反映年的線圖(YYYYMM)如數據透視表中所示。

這是我到目前爲止有:

fig, ax = plt.subplots(1,1) 
t.plot(ax=ax) 

軸標籤是2013年,2014年,2015年,和2016年,分別是什麼,而不是在那裏。

enter image description here

提前感謝!

回答

1

我想你可以刪除.astype(np.int64)但你得到的值類型指數string

df['YYYYMM']=df['YYYYMM'].astype(str).str[:-2] 

print t.index 
Index([u'2013', u'2014', u'2015', u'2016'], dtype='object', name=u'YYYYMM') 

但是如果你需要int指標,使用方法:

from matplotlib.ticker import FuncFormatter 

fig, ax = plt.subplots(1,1) 
ax.xaxis.set_major_formatter(FuncFormatter(lambda x, _: int(x))) 
t.plot(ax=ax)