python 排行 变化图_从变化的文本fi更新Python实时图形

该博客探讨了如何在Python中实现每个周期后更新图表的问题。作者遇到缓冲区错误,尝试使用aliüm的建议,即在FileWriter循环中使用flush()函数。程序通过创建线程并使用matplotlib的FuncAnimation来实现动态图形更新。代码示例展示了如何读取和写入文件以不断更新图表数据。
摘要由CSDN通过智能技术生成

这已经有几年没有发布了,但是我正在处理这个问题,我遇到了一个问题,我需要在每个周期后更新图表。在

我试图使用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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值