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()
我检查了文件,每次循环迭代后,文件都会更新,因此它也应该更新图形。我感谢任何帮助或评论。
阿夫欣
解决方案
推荐阅读
- angular - 使用 Angular 7 迭代 HTML 标签?(动态)
- google-chrome - 使用 Google Chrome Headless 模式强制执行屏幕截图分辨率
- walmart-api - 如何获取 Walmart API 的 API 密钥?似乎没有任何工作
- javascript - window.addEventListener 代码在移动设备上不起作用
- javascript - 一些图像逆时针旋转 90 度
- ruby-on-rails - 在 Rails 中初始化数据库行?
- r - 在 papaja 中使用 apa_linplot 绘制错误:min(0, y.values[, "lower_limit"],
- python - 无法将资产文件夹放入烧瓶应用程序
- php - 如何对齐 HTML 单元格值
- python - 如何使用 lambda(python) 从 CloudWatch 警报中获取特定值?