如何按组绘制TimeSeries DataFrame,并根据条件改变线型? [英] How to plot timeseries DataFrame by group, and change line type based on condition?

查看:33
本文介绍了如何按组绘制TimeSeries DataFrame,并根据条件改变线型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在同一轴上的DataFrame中绘制时间序列,每组具有不同的线条。我还想根据一些(布尔)条件更改线型。下面是一个示例:

import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from dateutil.parser import parse
from matplotlib import pyplot as plt

df = pd.DataFrame({'value': np.random.rand(18), 
              'group': ['A']*9 + ['B']*9,
              'future': [0, 0, 0, 0, 0, 0, 1, 1, 1]*2}, 
         index=[parse('2018-1-5') + timedelta(days=i) for i in range(9)]*2)

生成的DataFrame:

            future group     value
2018-01-05       0     A  0.076445
2018-01-06       0     A  0.800821
2018-01-07       0     A  0.410351
2018-01-08       0     A  0.039647
2018-01-09       0     A  0.664102
2018-01-10       0     A  0.192097
2018-01-11       1     A  0.456182
2018-01-12       1     A  0.163256
2018-01-13       1     A  0.832768
2018-01-05       0     B  0.139014
2018-01-06       0     B  0.265024
2018-01-07       0     B  0.832062
2018-01-08       0     B  0.738957
2018-01-09       0     B  0.334888
2018-01-10       0     B  0.945192
2018-01-11       1     B  0.707845
2018-01-12       1     B  0.135183
2018-01-13       1     B  0.140647

按组绘图非常简单:

df.groupby('group')['value'].plot(legend='True')
plt.show()

但是,当future的对应值为1时,我希望线条变为虚线。

以下是我尝试的解决方案:

present_data = df.loc[df['future'] == 0]
future_data = df.loc[df['future'] == 1]

present_data.groupby('group')['value'].plot(legend='True')
future_data.groupby('group')['value'].plot(style='--')
plt.show()

但这不是好事。我认为可以通过手动设置颜色来修复它(虽然这仍然会留下线条间隙的问题),但是肯定有比将DataFrame一分为二更好的方法?

非常感谢!

编辑:威尔的解决方案对我很有效,但是我仍然在想如何正确地创建图例。我希望组‘A’和‘B’显示两条实线。

我尝试过:

legends = []
for idx,grp in df_plot.groupby(['group','future']):
    grp['value'].plot(style=s[grp['future'][0]],color=c[grp['group'][0]])
    if grp['future'][0] == 0:
        legends.append(grp['group'][0])
    else:
        legends.append('')
plt.legend(legends)

但这会导致没有添加标签的虚线:

None追加到图例列表也不起作用。如果我完全跳过追加,‘A’和‘B’不对应正确的行:

legends = []
for idx,grp in df_plot.groupby(['group','future']):
    grp['value'].plot(style=s[grp['future'][0]],color=c[grp['group'][0]])
    if grp['future'][0] == 0:
        legends.append(grp['group'][0])
plt.legend(legends)
plt.show()

推荐答案

通过将分组合并到一个步骤中,然后按组打印,可以更轻松地手动指定颜色和样式。 要消除缺口,我认为您需要绘制一个额外的数据点。

extra=df[df.future==1]
extra = extra[extra.index == min(extra.index)] 
extra['future'] = 0
df_plot = pd.concat([df,extra])


s=['','--']
c={'A': 'red', 'B': 'blue'};

for idx,grp in df_plot.groupby(['group','future']):
    grp['value'].plot(style=s[grp['future'][0]],color=c[grp['group'][0]])

这篇关于如何按组绘制TimeSeries DataFrame,并根据条件改变线型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆