Simple Animated Plot with Matplotlib

Here’s a simple script which is a good starting point for animating a plot using matplotlib’s animation package (which, by their own admission, is really in a beta status as of matplotlib 1.1.0). I find the code needed to perform the animation more cumbersome than I’d like, but importantly, it’s not too cumbersome. In line2 50-51 of the code, where the actual animation call is made, note that

animation.FuncAnimation(fig, simPoints, simData, blit=False,
   interval=10, repeat=True)

has the user function simData as the argument for the user function simPoints. These are two functions that the user has to provide. A little staring at the code, and I think you’ll quickly be able to adapt it to suit your needs.

I don’t think of this as a great example how I eventually want to construct this site, but I think I realize that I should at least start somewhere, and perhaps when I am on sabattical and have more time to devote to this, I’ll nail down some nice structures for archiving, searching and displaying code. For now, I’ll archive the code on PasteBin  (link: SimpleAnimatedPlot.py ), and provide a local copy here (double clicking on the code selects it all):

"""
This short code snippet utilizes the new animation package in
matplotlib 1.1.0; it's the shortest snippet that I know of that can
produce an animated plot in python. I'm still hoping that the
animate package's syntax can be simplified further. 
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

def simData():
# this function is called as the argument for
# the simPoints function. This function contains
# (or defines) and iterator---a device that computes
# a value, passes it back to the main program, and then
# returns to exactly where it left off in the function upon the
# next call. I believe that one has to use this method to animate
# a function using the matplotlib animation package.
#
    t_max = 10.0
    dt = 0.05
    x = 0.0
    t = 0.0
    while t < t_max:
        x = np.sin(np.pi*t)
        t = t + dt
        yield x, t

def simPoints(simData):
    x, t = simData[0], simData[1]
    time_text.set_text(time_template%(t))
    line.set_data(t, x)
    return line, time_text

##
##   set up figure for plotting:
##
fig = plt.figure()
ax = fig.add_subplot(111)
# I'm still unfamiliar with the following line of code:
line, = ax.plot([], [], 'bo', ms=10)
ax.set_ylim(-1, 1)
ax.set_xlim(0, 10)
##
time_template = 'Time = %.1f s'    # prints running simulation time
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)
## Now call the animation package: (simData is the user function
## serving as the argument for simPoints):
ani = animation.FuncAnimation(fig, simPoints, simData, blit=False,\
     interval=10, repeat=True)
plt.show()

About PaulNakroshis

Professor of Physics at the University of Southern Maine.
This entry was posted in Animation, Matplotlib, Plotting and tagged , , , , . Bookmark the permalink.

10 Responses to Simple Animated Plot with Matplotlib

  1. Wil says:

    Thank you so much for this code, I’ve been looking for a way to implement something like this all day! -Wil

  2. jinu says:

    hello,

    i was interested in using this for visualizing stored gps data. do you know how i’d be able to do that?

    thanks

  3. slehar says:

    Very nice, thank you! But the last line of simPoints() is redundant, isn’t it?


    return line, time_text

    You are already “returning” the data through the previous two lines…


    time_text.set_text(time_template%(t))
    line.set_data(t, x)

    What does it even mean to “return” values to the calling function FuncAnimation()? Where do they “go” inside that function? I find it works without that last line.

    • PaulNakroshis says:

      You ask a good question. I am still trying to wrap my head around matplotlib’s animation logic. What I do know is that the code works when run from the terminal on OS X and python 3.6. I suspect I can make it work in the Jupyter notebook if I use the appropriate backend to render the graphics outside the notebook. Hopefully I can get it to run inside the notebook too. Any suggestions to do that?
      -p

  4. Claus Gumprecht says:

    Thanks for the code. But I do not get any Animation.
    I use Python 3.5.1 64bits, Qt 4.8.7, PyQt4 (API v2) 4.11.4 on Windows.
    Has any Body an idea why?
    Thanks
    Claus

    • PaulNakroshis says:

      Copy and paste the code into a text editor and run it from the terminal. I’ll have to check to see if it works in the Jupyter Notebook.
      -p

  5. Jim Check says:

    # I’m still unfamiliar with the following line of code:
    line, = ax.plot([], [], ‘bo’, ms=10)

    ‘bo’ refers to blue circles , ms = marker size

    • PaulNakroshis says:

      Yes, the line, piece befuddles me too. It’s called a generator, and my next step is to figure out how to understand this notation.
      -p

Leave a Reply

Your email address will not be published. Required fields are marked *

*