Quitting matplotlib.pyplot animation gracefully
Question: I have a script that plots data of some photometry apertures, and I want to
plot them in an xy plot. I am using matplotlib.pyplot with python 2.5.

The input data is stored in around 500 files and read. I am aware that this is
not the most efficient way of inputting the data but that's another issue...

Example code:

    
    
    import matplotlib.pyplot as plt
    
    xcoords = []
    ycoords = []
    
    # lists are populated with data from first file
    
    pltline, = plt.plot(xcoords, ycoords, 'rx')
    
    # then loop populating the data from each file
    
    for file in filelist:
        xcoords = [...]
        ycoords = [...]
    
    pltline.set_xdata(xcoords)
    pltline.set_ydata(ycoords)
    plt.draw()
    

As there are over 500 files, I will occasionally want to close the animation
window in the middle of the plotting. My code to plot works but it doesn't
exit very gracefully. The plot window does not respond to clicking the close
button and I have to `Ctrl+C` out of it.

Can anyone help me find a way to close the animation window while the script
is running whilst looking graceful (well more graceful than a series of python
traceback errors)?


Answer: If you update the data and do the draw in a loop, you should be able to
interrupt it. Here's an example (that draws a stationary circle and then moves
a line around the perimeter):

    
    
    from pylab import *
    import time
    
    data = []   # make the data
    for i in range(1000):
        a = .01*pi*i+.0007
        m = -1./tan(a)
        x = arange(-3, 3, .1)
        y = m*x
        data.append((clip(x+cos(a), -3, 3),clip(y+sin(a), -3, 3)))
    
    
    for x, y in data:  # make a dynamic plot from the data
        try:
            plotdata.set_data(x, y)
        except NameError:
            ion()
            fig = figure()
            plot(cos(arange(0, 2.21*pi, .2)), sin(arange(0, 2.21*pi, .2)))
            plotdata = plot(x, y)[0]
            xlim(-2, 2)
            ylim(-2, 2)
        draw()
        time.sleep(.01)
    

I put in the `time.sleep(.01)` command to be extra sure that I could break the
run, but in my tests (running Linux) it wasn't necessary.

