Cong
Cong

Reputation: 31

How does one close a figure or replace a figure without having to manually close each figure in Python/pylab?

I have searched numerous sites, used plots, subplots, some basic animation, and other roundabout ways, but the figure will not close despite using close(), clf(), etc.

I have something like this:

    import numpy
    from pylab import *
    import time
    fig = Figure() 
    counter1 = 0
    counter2 = 0

    while counter1<5:
            counter1 = counter1+1
            while counter2<10:
                    scatter(x_list[counter2], y_list[counter2], hold = 'on') ### x_list and y_list are just lists of random numbers
                    counter2 = counter2 + 1
            show()
            sleep(0.5)
            close()

I am looking for any solution, as seen above. Plots, subplots, animation...

Upvotes: 3

Views: 2891

Answers (1)

DSM
DSM

Reputation: 353604

Two side issues to start: first, are you sure that this is the code you're actually running? sleep isn't a function in my version of pylab, so your import time doesn't seem to match your call, it should be time.sleep(0.5).. Second, I don't understand your loops at all. It looks like you're plotting the same thing 5 times, because counter1 has no effect and you add each point to the scatterplot before you pause. Are you trying to plot x_list/y_list point by point?

If you use draw() instead of show() I think it should work; the show() is what's holding the close(). Is the following something like what you want?

import time
from pylab import *
ion()

# test data
x = arange(0, 10, 0.5)
y = 10*x+exp(x)*abs(cos(x))

for j in range(len(x)):
    if j > 0: scatter(x[:j], y[:j])
    # assuming we don't want the limits to change
    xlim(0, 10)
    ylim(0, 1000)
    draw()
    time.sleep(2)
    #close()

Note that I've commented out the close() because this way it produces a nice animation. If you leave it in, it'll keep closing and reopening the window, which could be what you want, but doesn't look very useful to my eyes. YMMV, of course.

Upvotes: 3

Related Questions