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

Matplotlib如何在FuncAnimation动画停止后添加背景散点图

解决Matplotlib动画结束后再绘制背景散点的问题

问题原因

  • 你当前把axis.scatter直接写在plt.show()之前,画布初始化时就会先绘制散点,自然会出现在轨迹下方但一开始就显示,不符合需求。
  • 你在update函数里判断i == maxlen不会触发,因为FuncAnimation的frames参数传maxlen时,i的取值范围是0 ~ maxlen-1,永远不会等于maxlen。
  • 开启blit=True模式时,新增的绘图元素必须在update的返回值中返回,才会被渲染到画布上,否则即使执行了scatter代码也不会显示。

解决方法

这里提供两种可行方案,选一种即可:

方案1:修改update判断逻辑(适配blit模式)

直接在最后一帧绘制散点,代码修改如下:

from collections import deque
import matplotlib.pyplot as plt
import matplotlib.animation as animation

# 以下x_s、y_s、sampling_period、time_text为你提前定义好的变量
figure, axis = plt.subplots()
point, = axis.plot([], [], zorder=3)
trace, = axis.plot([], [], zorder=2)
x_s_reduced = x_s[300::300]
y_s_reduced = y_s[300::300]
sampling_period = sampling_period * 300

maxlen = len(x_s_reduced)
history_x, history_y = deque(maxlen=maxlen), deque(maxlen=maxlen)
# 提前定义散点占位变量
scatter = None

def update(i):
    global scatter
    if i == 0:
        history_x.clear()
        history_y.clear()
        # 重置散点,适配可能的重复播放场景
        if scatter is not None:
            scatter.remove()
            scatter = None
    history_x.appendleft(x_s_reduced[i])
    history_y.appendleft(y_s_reduced[i])
    point.set_data(x_s_reduced[i], y_s_reduced[i])
    trace.set_data(history_x, history_y)
    
    # 最后一帧时添加散点
    if i == maxlen - 1:
        scatter = axis.scatter(x_s, y_s, color='lightgrey', zorder=1)
        return point, trace, time_text, scatter
    return point, trace, time_text

beam_video = animation.FuncAnimation(figure, update, frames=maxlen, interval=0.001, repeat=False, blit=True)
plt.show()

方案2:绑定动画结束事件(无需修改update逻辑)

如果你不想改动现有update的代码,可以直接绑定动画结束的回调函数:

# 保留你原来的所有代码,删掉plt.show()之前的axis.scatter行,新增以下代码即可
def on_anim_finish(event):
    axis.scatter(x_s, y_s, color='lightgrey', zorder=1)
    figure.canvas.draw_idle()

# 绑定动画结束事件
beam_video._stop = on_anim_finish
plt.show()

内容的提问来源于stack exchange,提问作者T-Dog

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 10:09:03