Matplotlib:如何在 FuncAnimation 停止后添加绘图?

Matplotlib: How to add plot after FuncAnimation stopped?

我想要运行一个动画,可以看到一个“点”在移动,留下一个“痕迹”。绘制完整个轨迹后,我想将数据(axis.scatter)绘制到背景中。现在它首先绘制散点图并在其上画线。

所以这是带有深灰色轨迹的移动点:

完成后,我希望它看起来像这样:

figure, axis = plt.subplots()
point, = axis.plot([], [], zorder=3)
trace, = axis.plot([], [], zorder=2)
x_s_reduced = x_s[300::300]  # len(x_s) = 5e5
y_s_reduced = y_s[300::300]  # len(y_s) = 5e5
sampling_period = sampling_period * 300  # sampling_period = 1e-5
#
maxlen = len(x_s_reduced)
history_x, history_y = deque(maxlen=maxlen), deque(maxlen=maxlen)
def update(i):
    if i == 0:
        history_x.clear()
        history_y.clear()
    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:
        #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)
axis.scatter(x_s, y_s, color='lightgrey', zorder=1)
plt.show()

我已经尝试将以下内容添加到更新功能中,但它不起作用:

...
if i == maxlen:
    scatter = axis.scatter(x_s, y_s, color='lightgrey', zorder=1)
    return point, trace, time_text, scatter
...

有没有办法等动画停止后再添加散点图? 或者我必须找到一种方法将其合并到更新功能中吗?

我自己找到了解决方案: 有两种方法可以做到这一点,使用 .set_offfsets 或使用 marker="o"

绘制线图
figure, axis = plt.subplots()
point, = axis.plot([], [], marker="o", color="crimson", zorder=3)
trace, = axis.plot([], [], ',-', zorder=2, color='darkgrey', linewidth=1)
# scatter, = axis.plot([], [], marker="o", color='lightgrey', zorder=1)
scatter = axis.scatter([], [], color='lightgrey', zorder=1)
#
filter = 10
x_s_reduced = x_s[filter::filter]
y_s_reduced = y_s[filter::filter]
sampling_period = sampling_period * filter
#
maxlen = len(x_s_reduced)
history_x, history_y = deque(maxlen=maxlen), deque(maxlen=maxlen)
time_template = 'Time = %.6fs'
time_text = axis.text(0.01, 0.95, '', transform=axis.transAxes, fontsize=14)
def update(i):
    if i == 0:
        history_x.clear()
        history_y.clear()
    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)
    time_text.set_text(time_template % (i * sampling_period))
    #scatter.set_data([], [])
    scatter.set_offsets(np.c_[[], []])
    if i == (maxlen-1):
        print('END')
        #scatter.set_data(x_s, y_s)
        scatter.set_offsets(np.c_[x_s, y_s])
    return point, trace, time_text, scatter
#
beam_video = animation.FuncAnimation(figure, update, frames=maxlen, interval=0.001, repeat=False, blit=True)
plt.show()