颜色填充matplotlib时间序列图表

时间:2017-10-02 15:44:49

标签: python pandas matplotlib

考虑以下pandas数据帧:

time                val server   state
2015-01-01 00:00:00 10   server01 normal
2015-01-01 00:02:00 18  server01 high
2015-01-01 00:03:00 41  server01 high
2015-01-01 00:04:00 22  server01 high
2015-01-01 01:05:00 32  server01 normal
2015-01-01 01:06:00 10  server01 high   
2015-01-01 01:07:00 42  server01 normal
2015-01-01 01:08:00 24  server01 normal
...........

在时间序列图表上绘制时,如何绘制state = high

的区域

这样的事情:

enter image description here

1 个答案:

答案 0 :(得分:6)

由于您想要绘制仅具有一个'high'状态的句点的跨度,您需要建立一个人工缓冲区来分别设置每组的最大值和最小值。

p = pd.Timedelta(30, unit='s')

df.val.plot()
for (state, _), g in df.groupby(['state', df.state.ne('high').cumsum()]):
    if  state == 'high':
        start = g.index.min() - p
        end = g.index.max() + p
        plt.axvspan(start, end, color='r', alpha=0.2)

enter image description here