Matplotlib如何根据signal字段值为单条折线的不同分段设置两种颜色
按signal字段给折线分段配色解决方案
实现原理
你当前已经完成了折线拆分为独立线段的步骤,segments 数组的每一个元素对应相邻两个数据点组成的线段,总线段数 = 数据点总数 - 1。只需要将每个线段和对应的signal值绑定映射为颜色即可。
完整实现代码
import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.collections import LineCollection # 你的现有代码 first = combine[:200000] # 取前20万行数据 x = first.index y = first.price.values points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) # 新增配色逻辑 # 每个线段取起始点的signal值映射颜色,也可根据需求改为.iloc[1:]取结束点的signal colors = ['green' if s else 'red' for s in first['signal'].iloc[:-1]] # 创建线段集合对象 lc = LineCollection(segments, colors=colors, linewidth=2) # 绘图 fig, ax = plt.subplots(figsize=(15, 7)) ax.add_collection(lc) # LineCollection不会自动适配坐标轴范围,需手动触发自动缩放 ax.autoscale() # 可根据需求添加坐标轴样式调整,比如时间轴旋转 plt.xticks(rotation=45) plt.xlabel('Time') plt.ylabel('Price') plt.show()
注意事项
- 如果时间索引绘图出现格式异常,可以将x转换为matplotlib支持的时间数值格式:
x = first.index.astype('datetime64[ns]').values - 若需要调整线段粗细,直接修改
LineCollection的linewidth参数即可
内容的提问来源于stack exchange,提问作者Volatil3
相关产品推荐
相关产品推荐

