两个图形的Python函数动画(一个接一个显示)



对于相同的x范围,我有两个数据集y1 = vol1y2 = vol2(步骤为10,从0到5000)。我想使用函数动画,以便首先动画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()

我的想法是制作两个"计数器"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()

相关内容

  • 没有找到相关文章

最新更新