首页 > 解决方案 > 如何从不同的 txt 文件在 matplotlib 中同时制作几个动画图

问题描述

我正在尝试从不同的 txt 文件中制作一些动画实时图表。我有 3 个文件。第 1(时间,错位)第 2(时间,速度),第 3(时间,加速度)。我想做一个使所有图表都依赖于 txt 文件的函数。就像我为第一个图表解决了它:

import methods

style.use('ggplot')
f = Figure(figsize=(5, 4), dpi=100)
f1 = Figure(figsize=(5, 4), dpi=100)
f2= Figure(figsize=(5, 4), dpi=100)

a = f.add_subplot(111)
b = f1.add_subplot(111)
c1 = f2.add_subplot(111)


def animate(i):
    pullData = open('przemieszczenie.txt', 'r').read()
    pullData1 = open('predkosc.txt', 'r').read()
    pullData2=open('przyspieszenie.txt', 'r').read()
    dataArray = pullData.split('\n')
    dataArray1 = pullData1.split('\n')
    dataArray2 = pullData2.split('\n')
    xar = []
    yar = []
    xbr = []
    ybr = []
    xcr = []
    ycr = []
    for eachLine in dataArray:
        if len(eachLine) > 1:
            x, y = eachLine.split(',')
            xar.append(float(x))
            yar.append(float(y))
    for eachLine in dataArray1:
        if len(eachLine) > 1:
            x1, y1 = eachLine.split(',')
            xbr.append(float(x1))
            ybr.append(float(y1))
    for eachLine in dataArray2:
        if len(eachLine) > 1:
            x2, y2 = eachLine.split(',')
            xcr.append(float(x2))
            ycr.append(float(y2))
    a.clear()
    a.plot(xar, yar)
    b.clear()
    b.plot(xbr, ybr)
    c1.clear()
    c1.plot(xcr, ycr)

def chart(tab2, file,a,f):


    with open(file) as file:
        lines = file.readlines()
        x = [line.split(',')[0] for line in lines]
        y = [line.split(',')[1] for line in lines]
    style.use('ggplot')

    a.plot(x, y)
    if(file == "przemieszczenie.txt"):
        f.text(0.5, 0.04, 'Time [s]', ha='center', va='center')
        f.text(0.07, 0.5, 'Displacement [m]', ha='center', va='center', rotation='vertical')
    if (file == "predkosc.txt"):
        f.text(0.5, 0.04, 'Time [s]', ha='center', va='center')
        f.text(0.07, 0.5, 'Velocity [m/s]', ha='center', va='center', rotation='vertical')
    if (file == "przemieszczenie.txt"):
        f.text(0.5, 0.04, 'Time [s]', ha='center', va='center')
        f.text(0.07, 0.5, 'Acceleration [m/s^2]', ha='center', va='center', rotation='vertical')
    canvas = FigureCanvasTkAgg(f, tab2)
    canvas.draw()
    canvas.get_tk_widget().pack(side=Tk.BOTTOM, fill=Tk.BOTH, expand=True)
    toolbar = NavigationToolbar2TkAgg(canvas, tab2)
    toolbar.update()
    canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=True)

我像这样调用函数(def图表在methods.py中,我想将gui与文件中的方法分开,AFAIK是它的好习惯):

methods.chart(tab2, 'przemieszczenie.txt',a,f)
methods.chart(tab3, 'predkosc.txt', b, f1)
methods.chart(tab4, 'przyspieszenie.txt',c1,f2)
ani = animation.FuncAnimation(f, animate, interval=1)

只有第一个情节是动画和更新。其余的都不起作用;c

标签: pythonmatplotlibtkinter

解决方案


推荐阅读