2016-05-16 130 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)