I have two data sets y1 = vol1
and y2 = vol2
for the same x
range (0 to 5000 in steps of 10). I would like to use function animation in order to first animate y1
and after that animate y2
while the graph of y1
remains.
This is what I got from combing several examples (incl. this):
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()
My idea was to make two 'counters' gen1
andgen2
but since I have the same x values for both data sets, I tried to compensate that in the animate2
function. But this doesn't work..
Obviously, I'm quite new to python and I appreciate any help.
CodePudding user response:
I would do just one animation, keeping track of the frame with respect to the line length:
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()