这已经有几年没有发布了,但是我正在处理这个问题,我遇到了一个问题,我需要在每个周期后更新图表。在
我试图使用aliüm的建议:f=open('./dynamicgraph.txt','a', 0),但是缓冲区出现了一个错误“不能设置为0”。在
如果将flush()函数放入FileWriter while循环中,它将在每个循环后更新图形。以下是程序的完整代码,它将在运行时绘制图形:#!usr/bin/python3
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
from random import randrange
from threading import Thread
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
def FileWriter():
f=open('./dynamicgraph.txt','a')
i=0
while True:
i+=1
j=randrange(10)
data = f.write(str(i)+','+str(j)+'\n')
print("wrote data")
time.sleep(1)
f.flush()
def animate(i):
pullData = open("dynamicgraph.txt","r").read()
dataArray = pullData.split('\n')
xar = []
yar = []
for eachLine in dataArray:
if len(eachLine)>1:
x,y = eachLine.split(',')
xar.append(int(x))
yar.append(int(y))
ax1.clear()
ax1.plot(xar,yar)
def Main():
t1=Thread(target=FileWriter)
t1.start()
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
print("done")
Main()