python - matplotlib 时间序列图表上的颜色填充

标签 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

最佳答案

由于您想要绘制只有一个 '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

关于python - matplotlib 时间序列图表上的颜色填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46528971/

相关文章:

python - 广义加性模型 - Python

python - 按任意间隔对时间索引的 DataFrame 进行分组

python - 如何使用 Matplotlib 在极坐标中绘制具有等高线密度线的散点图?

python-2.7 - 在 Windows 7 64 位上安装 numpy、matplotlib

python - 计算网格中点组合之间的距离

python - GAE 数据存储使用 Python 过滤不返回任何数据

python - TensorFlow 2.0 : Cant run minimal TF Tutorial: TypeError: Can not convert a int64 into a Tensor or Operation

python - Pandas 将 DataFrame 求和到一个更大的 DataFrame 中,该 DataFrame 已经包含具有相同列名的相同索引

python - 如何强制整数刻度标签

python - mysqlclient-python 和安全问题