Search code examples
pythonmatplotlibmatplotlib-animation

How can I animate a matplotlib plot from within for loop


I would like to update my matplotlibplot with values calculated in each iteration of a for loop. The idea is that I can see in real time which values are calculated and watch the progress iteration by iteration as my script is running. I do not want to first iterate through the loop, store the values and then perform the plot.

Some sample code is here:

from itertools import count
import random

from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt


def animate(i, x_vals, y_vals):
    plt.cla()
    plt.plot(x_vals, y_vals)

if __name__ == "__main__":
    x_vals = []
    y_vals = []
    fig = plt.figure()
    index = count()

    for i in range(10):
        print(i)
        x_vals.append(next(index))
        y_vals.append(random.randint(0, 10))
        ani = FuncAnimation(fig, animate, fargs=(x_vals, y_vals))
        plt.show()

Most of the examples I have seen online, deal with the case where everything for the animation is global variables, which I would like to avoid. When I use a debugger to step through my code line by line, the figure does appear and it is animated. When I just run the script without the debugger, the figure displays but nothing is plot and I can see that my loop doesn't progress past the first iteration, first waiting for the figure window to be closed and then continuing.


Solution

  • You should never be using a loop when animating in matplotlib.

    The animate function gets called automatically based on your interval.

    Something like this should work

    def animate(i, x=[], y=[]):
        plt.cla()
        x.append(i)
        y.append(random.randint(0, 10))
        plt.plot(x, y)
    
    
    if __name__ == "__main__":
        fig = plt.figure()
        ani = FuncAnimation(fig, animate, interval=700)
        plt.show()