【问题标题】:Matplotlib Line Graph with Pandas Pivot Table带有 Pandas 数据透视表的 Matplotlib 折线图
【发布时间】:2016-05-16 15:16:57
【问题描述】:

给定以下数据框和生成的数据透视表:

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,而不是那里的。

提前致谢!

【问题讨论】:

    标签: python-3.x pandas matplotlib pivot-table


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      • 2022-07-21
      相关资源
      最近更新 更多