0

I am trying to animate multiple lines from a set of data using matplotlib. When each frame comes around, the animation does not delete the old lines.

I followed the format given in this SO post: Matplotlib multiple animate multiple lines

Their lines do not delete either when I run their code. Since the code I am using requires an input file, I'll simply put the code from the other SO thread below. If I can figure out a solution to the problem in their code, I should be able to apply a solution to my code.

import matplotlib.pyplot as plt
from matplotlib import animation
from numpy import random 

fig = plt.figure()
ax1 = plt.axes(xlim=(-108, -104), ylim=(31,34))
line, = ax1.plot([], [], lw=2)
plt.xlabel('Longitude')
plt.ylabel('Latitude')

plotlays, plotcols = [2], ["black","red"]
lines = []
for index in range(2):
    lobj = ax1.plot([],[],lw=2,color=plotcols[index])[0]
    lines.append(lobj)


def init():
    for line in lines:
        line.set_data([],[])
    return lines

x1,y1 = [],[]
x2,y2 = [],[]

# fake data
frame_num = 100
gps_data = [-104 - (4 * random.rand(2, frame_num)), 31 + (3 * random.rand(2, frame_num))]


def animate(i):

    x = gps_data[0][0, i]
    y = gps_data[1][0, i]
    x1.append(x)
    y1.append(y)

    x = gps_data[0][1,i]
    y = gps_data[1][1,i]
    x2.append(x)
    y2.append(y)

    xlist = [x1, x2]
    ylist = [y1, y2]

    #for index in range(0,1):
    for lnum,line in enumerate(lines):
        line.set_data(xlist[lnum], ylist[lnum]) # set data for each line separately. 

    return lines

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=frame_num, interval=10, blit=True)


plt.show()

I would like for there to be 2 lines only displayed on each frame. Instead the lines stack with each frame until the entire plot is filled.

Ckswee
  • 1
  • 1
  • I think you misunderstood the code. It is working as expected. The fact that the line segments accumulate over time is desired, because in each frame, new data is added to the lists. To see this more clearly, replace the `gps_data` with `import numpy as np; x = np.linspace(-108, -104, 100); gps_data = [np.c_[x, x].T, np.c_[np.sin(3*x), np.cos(2*x)].T+32.5]` and set `repeat=False` in the FuncAnimation. – ImportanceOfBeingErnest Jun 20 '19 at 18:45
  • Yes, thank you for the reply. I forgot to update yesterday when I realized the same thing. In the code I provided it can also be updated by placing ```x1,y1 = [],[]``` and ```x2,y2 = [],[]``` inside of the animate function. – Ckswee Jun 21 '19 at 19:04

0 Answers0