通过合并两个时间序列来注释时间序列图



假设我有两个时间序列(或数据框中的两列),如下所示:

rng1 = pd.date_range('1/1/2017', periods=3, freq='H')
ts1 = pd.Series(np.random.randn(len(rng)), index=rng)
ts2 = pd.Series(['HE','NOT','SHE'], index=rng)

我想做一个ts1.plot()图,其中ts2用于注释 ts1 时间序列,但是我只想注释<> NOT时间戳。

到目前为止,我发现使用标记将是我正在寻找的。例如,有一个标记表示"HE",另一个标记用于"SHE",而"NOT"没有标记。但是,我不知道如何使用另一个时间序列作为输入,并且只能注释时间戳<>某个值。

您可以使用

pandas 数据帧groupby方法按正在使用的标签拆分数据集,而忽略您不想绘制的值。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
rng = pd.date_range('1/1/2017', periods=3, freq='H')
ts1 = pd.Series(np.random.randn(len(rng)), index=rng)
ts2 = pd.Series(['HE','NOT','SHE'], index=rng)
df = pd.concat([ts1, ts2], keys=['foo', 'bar'], axis=1)
ax = None # trick to keep everything plotted on a single axis
labels = [] # keep track of the labels you actually use
for key, dat in df.groupby('bar'):
    if key == 'NOT':
        continue
    labels.append(key)
    ax = dat.plot(ax=ax, marker='s', ls='none', legend=False)
# handle the legend through matplotlib directly, rather than pandas' interface
ax.legend(ax.get_lines(), labels)
plt.show()

最新更新