Matplotlib时间序列绘图与groupby函数应用于df

时间:2017-10-05 19:33:39

标签: python pandas matplotlib group-by time-series

目前我有八个不同的扬声器这个df。 :

                      raw_score
  Speaker date                 
  Allison 2012-10-31   0.796908
          2012-11-30   1.792649
          2012-12-31   0.668619
  Warsh   2015-03-31        NaN
          2015-04-30        NaN
          2015-05-31  -0.094364
          2015-06-30   0.349691

我用这段代码创建了我当前的df:

dropped = df.drop(['Unnamed: 0', 'text'], axis=1)
dropped['date'] =  pd.to_datetime(dropped['date'], format='%m/%d/%y')
dropped.index = dropped['date']
del dropped['date']
dropped = dropped.groupby('Speaker')
dropped = dropped.resample('M').mean()

我想用' raw_score'制作时间序列图表。在x轴上的y轴和日期(当前是df的索引)上,每个扬声器的图表上有一条单独的线。

我尝试了以下内容,但没有得到我想要的内容:

dropped.plot()

New graph!

2 个答案:

答案 0 :(得分:2)

试试这个:

In [47]: df.reset_index(level=0).pivot_table(index='date', columns='Speaker', values='raw_score')
Out[47]:
Speaker      Allison     Warsh
date
2012-10-31  0.796908       NaN
2012-11-30  1.792649       NaN
2012-12-31  0.668619       NaN
2015-03-31       NaN       NaN
2015-04-30       NaN       NaN
2015-05-31       NaN -0.094364
2015-06-30       NaN  0.349691


In [48]: df.reset_index(level=0).pivot_table(index='date', columns='Speaker', values='raw_score').plot()
Out[48]: <matplotlib.axes._subplots.AxesSubplot at 0xc804710>

compare-and-swap

答案 1 :(得分:2)

ax = df.unstack(0)['raw_score'].plot()
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
_ = ax.axhline(0, color='black', linewidth=.7)
_ = ax.set_ylabel('Raw Score')

输出: enter image description here