【问题标题】:Matplotlib create real time animated graphMatplotlib 创建实时动画图
【发布时间】:2016-03-26 09:42:33
【问题描述】:

我很难设置我的代码来创建实时动画图,我的代码在收集数据后绘制图形,而不是显示每次迭代。我的脚本运行一个回归函数,然后存储在一个文件中,然后我访问这些文件并绘制它们,这就是我所拥有的,我需要移动或更改什么来让它实时绘制?我尝试在 for 循环内移动绘图函数,但没有奏效,有什么建议吗?

 fig = plt.figure()
 ax1 = fig.add_subplot(1,1,1)

 num = 10 
 for idx in range(1,num):
    c,e = Regr_magic()
        with open("CK_output.txt",'a') as CK:
            CK.write("{0},{1}\n".format(idx,c))
        with open("error_output.txt",'a') as E:
            E.write("{0},{1}\n".format(idx,e))



    def animate(i):
        pull = open('error_output.txt','r').read()
        data = pull.split('\n')
        xar = []
        yar = []

        for each in data:
            if len(each)>1:
                x,y = each.split(',')
                xar.append(float(x))
                yar.append(float(y))
            ax1.plot(xar, yar)
    ani = animation.FuncAnimation(fig, animate, interval=1000)
    plt.show()

仅供参考,数据文件包含以下内容,迭代次数和 Ck 值或错误,所以它们看起来像这样

1,.0554
2,.0422
3,.0553
4,.0742
5,.0232

【问题讨论】:

    标签: python matplotlib code-organization


    【解决方案1】:

    预计算结果的解决方案

    这会根据输出文件中的数据制作出不错的动画:

    from matplotlib import pyplot as plt
    from matplotlib import animation
    
    
    fig = plt.figure()
    
    with open('error_output.txt') as fobj:
        x, y = zip(*([float(x) for x in line.split(',')] for line in fobj))
    
    
    def animate(n):
        line, = plt.plot(x[:n], y[:n], color='g')
        return line,
    
    anim = animation.FuncAnimation(fig, animate, frames=len(x), interval=1000)
    plt.show()
    

    计算值时实时动画的解决方案

    这是一个允许regr_magic产生的数据实时动画的版本:

    import random
    import time
    
    from matplotlib import pyplot as plt
    from matplotlib import animation
    
    
    class RegrMagic(object):
        """Mock for function Regr_magic()
        """
        def __init__(self):
            self.x = 0
        def __call__(self):
            time.sleep(random.random())
            self.x += 1
            return self.x, random.random()
    
    regr_magic = RegrMagic()
    
    def frames():
        while True:
            yield regr_magic()
    
    fig = plt.figure()
    
    x = []
    y = []
    def animate(args):
        x.append(args[0])
        y.append(args[1])
        return plt.plot(x, y, color='g')
    
    
    anim = animation.FuncAnimation(fig, animate, frames=frames, interval=1000)
    plt.show()
    

    RegrMagic 类是模拟 Regr_magic() 的助手。 __call__方法使这个类的实例表现得像一个函数。它具有状态并为每个呼叫生成数字1, 0.565652, 0.65566 等(第二个数字是随机数)。它也有一个时间延迟来模拟计算时间。

    重要的是frames()。将Regr_magic() 替换为Regr_magic() 应该可以了。

    具体问题的解决方案

    没有模拟的版本:

    import random
    import time
    
    from matplotlib import pyplot as plt
    from matplotlib import animation
    
    
    def frames():
        while True:
            yield Regr_magic()
    
    
    fig = plt.figure()
    
    x = []
    y = []
    def animate(args):
        x.append(args[0])
        y.append(args[1])
        return plt.plot(x, y, color='g')
    
    
    anim = animation.FuncAnimation(fig, animate, frames=frames, interval=1000)
    plt.show()
    

    【讨论】:

    • 谢谢!现在我看到了我缺少的东西,当数据文件被新数据附加时,这会即时工作吗?
    • 这需要一些改变。 frames 需要是一个生成器,在另一个之后产生价值。
    • 我不知道该怎么做,我不熟悉 python 中的产量。但是我需要将 x 作为收益返回吗?
    • 另外,你使用Class有关系吗?因为我的回归函数c,e=Regr_magic()是一个返回两个不同变量的函数
    • 该类只是使其工作的助手。你可以把它扔掉并使用你的函数:yield Regr_magic()。注意大写R
    猜你喜欢
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    • 2018-04-18
    • 1970-01-01
    相关资源
    最近更新 更多