Python 两个图形的函数动画(依次显示)

Python function animation for two graphes (displayed after each other)

我有两个数据集 y1 = vol1y2 = vol2 用于相同的 x 范围(0 到 5000,步长为 10)。我想使用函数动画来首先对 y1 进行动画处理,然后对 y2 进行动画处理,而 y1 的图形仍然存在。 这是我从几个例子中得到的(包括 ):

import numpy as np 
from matplotlib import pyplot as plt 
from matplotlib.animation import FuncAnimation


x = range(0, 5000, 10)
y1 = vol1
y2 = vol2

fig, ax = plt.subplots()
ax.set_xlim(0, 5000)
ax.set_ylim(0, 1000)

l1, = plt.plot([],[],'b-')
l2, = plt.plot([],[],'r-')

def init1():
    return l1,
def init2():
    return l2,

def animate1(i):
    l1.set_data(x[:i],y1[:i])
    return l1,
def animate2(i):
    l2.set_data(x[:i-500],y2[:i-500])
    return l2,

def gen1():
    i = 0
    while(i<500):
        yield i
        i += 1
def gen2():
    j = 500
    while(j<1000):
        yield j
        j += 1

ani1 = FuncAnimation(fig, animate1, gen1, interval=1, save_count=len(x),
                    init_func=init1, blit=True,
                    repeat=False) 
ani2 = FuncAnimation(fig, animate2, gen2, interval=1, save_count=len(x),
                        init_func=init2, blit=True,
                        repeat=False)
    # ani.save('ani.mp4')
plt.show()

我的想法是制作两个 'counters' gen1gen2 但是因为我对两个数据集有相同的 x 值,所以我试图在 animate2 功能。但这不起作用.. 显然,我是 python 的新手,非常感谢您的帮助。

我只做一个动画,根据线的长度跟踪帧:

import numpy as np 
from matplotlib import pyplot as plt 
from matplotlib.animation import FuncAnimation, FFMpegWriter

x = np.linspace(0, 2 * np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
k = 0

fig, ax = plt.subplots()
ax.set_xlim(0, x.max())
ax.set_ylim(-1.5, 1.5)

l1, = plt.plot([],[],'b-')
l2, = plt.plot([],[],'r-')

def animate1(i):
    global k
    
    if k > 2 * len(x):
        # reset if "repeat=True"
        k = 0
    
    if k <= len(x):
        l1.set_data(x[:k],y1[:k])
    else:
        l2.set_data(x[:k - len(x)],y2[:k - len(x)])
    k += 1

ani1 = FuncAnimation(fig, animate1, frames=2*len(x), interval=1, repeat=True)
writer = FFMpegWriter(fps=10)
ani1.save("test.mp4", writer=writer)
plt.show()