首页 > 解决方案 > 从生成数据的函数中绘制实时数据

问题描述

我是编程的初学者,这是我第一次来这里。我正在尝试为 FEA analisys 编写一个脚本,该脚本从一个巨大的 .msg 文件中读取数据,该文件在模拟期间由第三个软件更新,然后绘制一个图表,每次 .msg 文件由第三个软件更新时都会自行更新。

使用我熟悉的工具,我的策略是:

用他写的代码我得到了错误: 错误

数据收集似乎工作得很好,看起来问题是当我调用激活绘图函数的线程时,因为它需要一个我真的不知道如何定义的位置参数(i)。

我的代码:

import os
from itertools import count
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
import time
import threading

time1 = os.path.getmtime('SM_1Gz_PT_1.msg')

def getdata():

    index = count()
    final=0
    time1=''
    residual_force_list=[]  #lista com as linhas que contem a frase da largest residual force
    residual_forces=[]   #lista com o valor das residual forces
    iteration=[]
    while final == 0:

        if (time1 != os.path.getmtime('SM_1Gz_PT_1.msg')): #acessa o horário da ultima alteraçao no msg

            with open('SM_1Gz_PT_1.msg', 'rt') as lines:

                for line in lines: #Checa se a análise foi ou nao completada e adiciona ultima
                                   #linha de largest residual force à lista residual_force_list

                    if line[0:42].strip()=="THE ANALYSIS HAS BEEN COMPLETED":
                        final=1
                        # print(final)

                    if line[0:23].strip() == "LARGEST RESIDUAL FORCE": #add linha com ultima residual force a lista
                        residual_force_list.append(line)

                residual_forces.append(float(residual_force_list[-1][36:47]))
                force = residual_forces[-1]
                data=open('data.txt','a')
                data.write(f'{force},')
                data.write(f'{next(index)+1} \n')
                data.close()

                print(residual_forces)
                print(iteration, residual_forces)
                print(final)


            time1 = os.path.getmtime('SM_1Gz_PT_1.msg') #atualiza o horário da ultima modificação no msg

        time.sleep(1) #reduz a frequência na qual o loop checa por atualizaçoes no msg

style.use('fivethirtyeight')
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

def animate(i):
    graph_data = open('data.txt','r').read()
    lines = graph_data.split('\n')
    xs = []
    ys = []
    for line in lines:
        if len(line) > 1:
            y, x = line.split(',')
            xs.append(int(x))
            ys.append(float(y))
    ax1.clear()
    ax1.plot(xs, ys)

t1 = threading.Thread(target=getdata)
t2 = threading.Thread(target=animate)

t1.start()
t2.start()

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

标签: pythonmultithreadingmatplotlib

解决方案


推荐阅读