анимация matplotlib не работает при обновлении файла, выполняемого циклом

#python-3.x #matplotlib

#python-3.x #matplotlib

Вопрос:

У меня есть онлайн-график, созданный animation.FuncAnimation , который считывает данные из файла и обновляет фигуру. Код является:

 %matplotlib notebook

from time import sleep
import matplotlib.pyplot as plt
import matplotlib.animation as animation

figure = plt.figure()
anim = figure.add_subplot(1,1,1)

def animate(i):
    data = open('results.txt', 'r ')
    lines = data.readlines()
    lines = [x.strip() for x in lines]
    xa = []
    ya = []
    for line in lines:
        if len(line) > 1:
            x, y = line.split(',')
#             print(x,y)
            xa.append(float(x))
            ya.append(float(y))
    anim.clear()
    anim.scatter(xa,ya)

ani = animation.FuncAnimation(figure,animate, interval = 1000)
plt.show()
  

Когда я вручную добавляю точку в results.txt , она быстро обновляет фигуру. Также я использую

 data = open('results.txt', 'a')
x = 13
data.write("%d" % x)
data.write(",")
y = 21321
data.write("%d" % y)
data.write("n")
print (x,y)
data.close()
  

чтобы добавить новую точку в results.txt , он обновляет рисунок.
Но, когда я добавляю точки в results.txt через цикл (см. Ниже), это не обновляет рисунок до тех пор, пока цикл не будет завершен.

 for i in range(100):
    data = open('results.txt', 'a')
    x = i
    data.write("%d" % x)
    data.write(",")
    y = 9*i*i
    data.write("%d" % y)
    data.write("n")
    print (x,y)
    sleep(0.2)
    data.close()
  

Я проверил файл, и после каждой итерации цикла файл обновляется, так что он также должен обновлять рисунок.
Я ценю любую помощь или комментарии.

Afshin