Matplotlib create real time animated graph

后端 未结 1 1163
不思量自难忘°
不思量自难忘° 2020-12-16 03:00

I am having a hard time setting up my code to create a real time animated graph, my code is graphing after the data is being collected, not showing every iteration. My scrip

相关标签:
1条回答
  • 2020-12-16 03:19

    Solution for pre-computed results

    This makes a decent animation from the data in your output file:

    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()
    

    Solution for a real-time animation as the values are computed

    Here a version that allows real-time animation of data produce by 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()
    

    The class RegrMagic is a helper the mocks Regr_magic(). The __call__method makes an instance of this class behave like a function. It has state and produces the numbers 1, 0.56565, 2, 0.65566 etc. for each call (second number is a random number). It also has a time delay to mimic the computation time.

    The important thing is frames(). Replace Regr_magic() with Regr_magic() and should be good to go.

    Solution for the concrete problem

    A version without mocks:

    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()
    
    0 讨论(0)
提交回复
热议问题