You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在matplotlib中高亮标记时间序列的异常点区间

实现方案

你不需要额外引入专用库,Matplotlib 原生就支持区间背景高亮能力,使用ax.axvspan()方法即可实现论文示例中的效果,改造后的代码如下:

import matplotlib.pyplot as plt
import seaborn as sns

# 你的异常区间列表
anomaly_intervals = [[10, 20], [23, 38], [45, 56]]

fig = plt.figure(figsize=(25,5)) 
ax1 = plt.subplot(121)
# 绘制基础时间序列
sns.lineplot(data=df['values'], ax=ax1)
# 高亮异常区间
for start, end in anomaly_intervals:
    ax1.axvspan(xmin=start, xmax=end, facecolor='red', alpha=0.3, edgecolor='none')

参数说明:

  • xmin/xmax:区间在横轴上的起止值,若你的横轴为时间格式,直接传入对应的时间戳/ datetime 对象即可适配
  • facecolor:高亮区域的填充色,可根据需求调整为浅橙、浅灰等其他配色
  • alpha:填充色透明度,设置为0.2~0.4区间即可避免遮挡下层折线
  • edgecolor:高亮区域的边框颜色,不需要边框可设为none

如果你仍需要保留异常段折线变色的效果,可保留你原来的第二行sns.lineplot逻辑,和区间高亮叠加使用即可达到和参考示例完全一致的效果。

内容的提问来源于stack exchange,提问作者Fabio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 23:27:04