首页 > 解决方案 > 使用 matplotlib 为多行设置动画时不会删除旧行

问题描述

我正在尝试使用 matplotlib 从一组数据中为多行设置动画。当每一帧出现时,动画不会删除旧行。

我遵循了这篇 SO 帖子中给出的格式:Matplotlib multiple animate multiple lines

当我运行他们的代码时,他们的行也不会删除。由于我使用的代码需要一个输入文件,我将简单地将来自另一个 SO 线程的代码放在下面。如果我能在他们的代码中找出问题的解决方案,我应该能够将解决方案应用于我的代码。

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()

我希望每帧只显示 2 行。相反,线条与每一帧堆叠在一起,直到填满整个绘图。

标签: pythonmatplotlib

解决方案


推荐阅读