# Problems with animation

I have the following minimum source for an animation

``````import math
import argparse
import os
import json

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

line_x=[ 0,1,2,3,4,5,6,7,8,9,10,11,12  ]
line1_y=[ 3,5,7,9,11,19,23,26,29,31,37,40,45  ]
line2_y=[0,2,5,7,10,10,8,5,3,2,1,3,5]
line3_y=[39,38,32,29,26,22,19,13,10,8,7,6,3]

set_lines=[line1_y,line2_y,line3_y]

n_lineas=[1,2,3,1,3,2,3,1,3,2,1,2]

show=True #False #True

def get_n(thelist,c):
while(c>=len(thelist)):
c-len(thelist)
return thelist[c]

class Update:
def __init__(self,ax,limit_x):
self.ax = ax
if limit_x!=0:
self.ax.set_xlim(0,limit_x)
self.ax.set_ylim(0,45)
self.ax.set_aspect('equal')
self.ax.grid(True)
self.lines=()
self.counter=0

def __call__(self, frame):
print("Frame: ",frame)
lines=[]

n_lines_this_time=get_n(n_lineas,self.counter)
self.counter+=1
print(n_lines_this_time,"lines this time")

for myline in range(n_lines_this_time):
#line,=self.ax.plot([],[],'.-',color=gt_color,label=legend)
line,=self.ax.plot([],[],'.-')
x = []
y = []
for v in range(13):
x.append(line_x[v])
y.append(set_lines[myline][v])
line.set_xdata(x)
line.set_ydata(y)
lines.append(line)

self.lines=tuple(lines)
return self.lines

def init(self):
print("Init")
line,=self.ax.plot([],[])
return line,

fig, ax = plt.subplots(1, 1,figsize=(10,10))
plt.gcf().canvas.mpl_connect(
'key_release_event',
lambda event: [exit(0) if event.key == 'escape' else None])
plt.xlabel("Y (meters)")
plt.ylabel("X (meters)")
ug_i = Update(ax,13)
anim = FuncAnimation(fig, ug_i,init_func=ug_i.init, frames=10, interval=5000, blit=True,repeat=False)

if not show:  #This is not working. It does not erase the plots
writervideo = FFMpegWriter(fps=60)
anim.save('whatever.mp4', writer=writervideo)
print('done')
plt.close()
else:
plt.legend()
plt.show()
``````

The problem is that when shown I can see the animation but when saved to a file, all frames all piled up onto another and so the animation is not correctly portrait. How can I get a video that correctly finishes with two lines?

Please see Faster rendering by using blitting — Matplotlib 3.6.2 documentation for an explaination of how blitting works.

This issue is that every pass through you are creating new `Line2D` objects rather than updating the existing ones. When you run it interactively, it looks OK because the initial background does not contain any lines and hence you only see the “newest” lines. On the other hand, when we save we render each frame from scratch (which maybe we should not, but that is neither here nor there) so you see all the line.

The fix is to stash the line you created in `init` and then updating it in `__call__`. If you need to create extra lines as you go that is also OK, but stash them before returning from `__call__` and re-use them the next pass through.