首页 > 解决方案 > 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()

我检查了文件,每次循环迭代后,文件都会更新,因此它也应该更新图形。我感谢任何帮助或评论。

阿夫欣

标签: python-3.xmatplotlib

解决方案


推荐阅读