Close pre-existing figures in matplotlib when running from eclipse

AnjoMan picture AnjoMan · Feb 21, 2013 · Viewed 155.4k times · Source

My question is simple: I have a python script that generates figures using matplotlib. Every time i run it it generates new windows with figures. How can I have the script close windows that were opened the previous time it ran?

the analogous command in matlab is to put 'close all' at the beginning of your matlab script.

I have seen several suggestions to do something like

import matplotlib.pyplot as plt
plt.close("all")

This solution works if you run your script from the python shell, eg using

>>>> execfile("myScript.py")

However, I have found that this doesn't work if I run the script using Eclipse / PyDev. How can I get it to work in Eclipse?

example:

from numpy import *
from matplotlib.pyplot import *
from scipy import *

close("all") 
    #close any previously open plots - this doesn't work when running via Eclipse

t = linspace(0, 0.1,1000)
w = 60*2*pi

figure()
plot(t,cos(w*t))
plot(t,cos(w*t-2*pi/3))
plot(t,cos(w*t-4*pi/3))
show()

This should plot the ideal waveforms for a nice 3-phase power supply.

Answer

Bi Rico picture Bi Rico · Feb 21, 2013

You can close a figure by calling matplotlib.pyplot.close, for example:

from numpy import *
import matplotlib.pyplot as plt
from scipy import *

t = linspace(0, 0.1,1000)
w = 60*2*pi


fig = plt.figure()
plt.plot(t,cos(w*t))
plt.plot(t,cos(w*t-2*pi/3))
plt.plot(t,cos(w*t-4*pi/3))
plt.show()
plt.close(fig)

You can also close all open figures by calling matplotlib.pyplot.close("all")