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

Matplotlib实现单条多分段不同颜色时间序列线图的简便方法

实现Matplotlib分段彩色连续线图的简便方案

要给特定x区间的线段单独上色,避免直接用掩码绘制导致非连续区间错误连接的问题,**LineCollection**是最省心的工具——它专门用来处理分段样式的线条,完全不需要手动构建复杂的掩码字典。

具体实现步骤

  1. 导入依赖库
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
  1. 生成时间序列数据
y = np.random.random(100) - 0.5
x = np.arange(len(y))  # 用arange比range更适配后续数组操作
  1. 定义需要高亮的x区间
highlight_intervals = [(0, 10), (34, 37), (68, 91)]
  1. 构建线段分段数据
    LineCollection需要由连续点对组成的线段数组,先把x和y组合成坐标点,再拆分成相邻线段:
# 组合x,y为坐标点数组
points = np.column_stack((x, y))
# 拆分成相邻两点组成的线段(共99条线段)
segments = np.array([points[i:i+2] for i in range(len(points)-1)])
  1. 给线段分配颜色
    先默认所有线段为红色,再根据高亮区间筛选出需要改色的线段:
# 计算每条线段的x中点,用来判断是否属于高亮区间
seg_x_mid = (x[:-1] + x[1:]) / 2

# 初始化颜色数组,默认红色
colors = np.array(['red'] * len(segments))

# 遍历高亮区间,把对应线段改成绿色
for a, b in highlight_intervals:
    # 筛选出中点在(a,b)范围内的线段
    mask = (seg_x_mid > a) & (seg_x_mid < b)
    colors[mask] = 'green'
  1. 绘制分段彩色线图
fig, ax = plt.subplots(figsize=(10, 4))
# 创建LineCollection对象并添加到轴上
lc = LineCollection(segments, colors=colors, linewidth=2)
ax.add_collection(lc)

# 设置坐标轴范围(LineCollection不会自动适配范围,需手动设置)
ax.set_xlim(x.min(), x.max())
ax.set_ylim(y.min() - 0.1, y.max() + 0.1)  # 留边距让图表更美观

plt.show()

方案优势

  • 无需手动编写每个区间的掩码,只要定义高亮区间列表即可,适配任意数量的离散/连续区间
  • 彻底避免非连续区间线段错误连接的问题,每条线段独立绘制
  • 可灵活调整线段宽度、颜色等样式,扩展性强

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 04:30:10