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

matplotlib动态更新多行折线图时如何固定各线条颜色

问题原因

每次循环调用ax.plot()重绘全量数据时,matplotlib会从默认颜色循环的起始位置重新为所有线条分配颜色,且之前绘制的线条没有被清除,多层线条叠加后就会出现颜色跳变、无法固定的问题。同时每次全量重绘也会带来不必要的性能开销。

修复方案

初始化画布时就创建好32条绑定固定颜色的折线对象,后续每次刷新仅更新已有折线的数据源,不重新创建绘图元素,即可固定配色,同时提升动态刷新的流畅度。

修复后完整代码

import numpy as np
import time
import matplotlib.pyplot as plt

start_measurment = time.time()
to_plot = np.zeros((1, 33)) 

# 提前提取32个固定配色,直接复用matplotlib默认颜色循环即可
prop_cycle = plt.rcParams['axes.prop_cycle']
fixed_colors = [item['color'] for item in prop_cycle[:32]]

fig, ax = plt.subplots(1, 1)
ax.set_xlabel('time(s)')
ax.set_ylabel('sim. Data')

# 初始化32条空折线,每条提前绑定固定颜色
lines = []
for c in fixed_colors:
    line, = ax.plot([], [], color=c)
    lines.append(line)

for i in range(20):
    # 模拟新增的一行数据
    Simulated_data = (np.arange(32)*i).reshape((1, 32))
    Simulated_data = np.insert(Simulated_data, 0, [time.time()-start_measurment], axis=1)
    to_plot = np.append(to_plot, Simulated_data, axis=0)
    
    # 逐线更新数据源,不重新调用plot
    for line_idx, line in enumerate(lines):
        line.set_data(to_plot[:, 0], to_plot[:, line_idx+1])
    
    # 动态调整坐标轴范围适配新数据
    ax.set_xlim(to_plot[:, 0].min(), to_plot[:, 0].max())
    ax.set_ylim(to_plot[:, 1:].min(), to_plot[:, 1:].max())
    
    fig.canvas.draw()
    fig.canvas.flush_events()
    time.sleep(1)

补充说明

  • 如果需要自定义配色,直接替换fixed_colors列表为目标颜色集合即可,支持十六进制色值、RGB元组、matplotlib内置颜色名等格式
  • 该方案相比每次全量重绘,动态刷新的性能更高,数据量较大时不会出现明显卡顿
  • 可以根据实际需求提前固定坐标轴范围,避免每次自动调整范围带来的画面闪烁

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 03:51:23