Python matplotlib: Showing the same figure after plotting progressively more graphs
Question: I want to do something like this, where the figure is the same.

    
    
    fig = plt.figure()
    
    plt.plot(x1,y1)
    
    plt.show()
    

So it'll show a point in figure 1 at x1, y1

Then if I do a mouse click or press a key, something along the lines of:

    
    
    plt.plot(x2,y2)
    
    plt.show()
    

But the figure window shouldn't close, it should just plot a new point on top
of it.

I want to do this kinda thing for a math presentation, I know its not even
necessary at all but I had this thought and wondered if it was possible for
python. I have done MATLAB in the past and stuff like this is so much easier.


Answer: The simplest way is to do this is to enable "interactive mode" in matplotlib,
which draws automatically on changes. This is a good way to do thing in the
command-line, and is equivalent to how MATLAB does it. However, it is slower,
so it is better not to use it in scripts, so it is not the default:

    
    
    import matplotlib.pyplot as plt
    
    x1 = 1
    x2 = 2
    
    y1 = 1
    y2 = 4
    
    plt.ion()  # turn on interactive mode
    plt.figure()
    plt.xlim(0, 10)  # set the limits so they don't change while plotting
    plt.ylim(0, 10)
    plt.hold(True)  # turn hold on
    
    plt.plot(x1, y1, 'b.')
    
    input()  # wait for user to press "enter", raw_input() on python 2.x
    
    plt.plot(x2, y2, 'b.')
    plt.hold(False)  # turn hold off
    

For a loop, it would work like this:

    
    
    import matplotlib.pyplot as plt
    import numpy as np
    
    xs = np.arange(10)
    ys = np.arange(10)**2
    
    plt.ion()
    plt.figure()
    plt.xlim(0, 10)
    plt.ylim(0, 100)
    plt.hold(True)
    
    for x, y in zip(xs, ys):
        plt.plot(x, y, 'b.')
        input()
    
    plt.hold(False)
    

If you use IPython, however, you can just use `%pylab`, which takes care of
importing everything and enabling interactive mode:

    
    
    %pylab
    
    xs = arange(10)
    ys = arange(10)**2
    
    figure()
    xlim(0, 10)  # set the limits so they don't change while plotting
    ylim(0, 100)
    hold(True)
    
    for x, y in zip(xs, ys):
        plot(x, y, 'b.')
        input()  # raw_input() on python 2.x
    
    hold(False)
    

