6

I have noticed that when I run:

import pylab as pl
pl.ion()
# Plot something
pl.show()
pl.close()

The last statement does not fully close the Figure. The figure goes dark, and the contents go away, but the Figure stays on the screen until I exit IPython as shown below

                      enter image description here

I am using the latest stable version of matplotlib (1.3.1) using an Anaconda distribution, on Linux 64 bit, and I connect remotely using ssh -X.

The backend I am using is below:

backend : QT4Agg
backend.qt4 : PySide
Josh
  • 11,979
  • 17
  • 60
  • 96
  • How do you create the plot? Do you use `pl.show()` (that should block the code from reaching the `pl.close` until you close the window manually). What backend do you use? – David Zwicker Dec 05 '13 at 13:54
  • Well, I can't reproduce your problem here. What matplotlib backend are you using? I guess you are running on a linux machine connecting to a linux server?! – David Zwicker Dec 05 '13 at 13:58
  • @DavidZwicker Just updated the OP. Yes, I connect from a Linux box to a Linux server where I run the code. – Josh Dec 05 '13 at 14:08
  • Hmm looks like a normal setup to me. Have you tried switching to another backend like `TkAgg`? As I said I can't reproduce your problem, but it looks like a bug to me. – David Zwicker Dec 05 '13 at 14:12
  • And to confirm, you are using this interactively in an ipython shell? If so this looks like a bug to me, if you are running this as a script, I am not surprised there is something funny with eventloops getting started/not started in pyplot when running in a script. – tacaswell Dec 05 '13 at 15:47

2 Answers2

8

you have to specify wich figure you want to close. In case you want to close all of them:

pl.close('all')

Also, there is a way to just clear but not close a figure:

pl.clf()

Also, seen below from another SO question:

Remember that plt.show() is a blocking function, so in the example code you used above, plt.close() isn't being executed until the window is closed, which makes it redundant.

You can use plt.ion() at the beginning of your code to make it non-blocking, although this has other implications.

Community
  • 1
  • 1
Nils Werner
  • 34,832
  • 7
  • 76
  • 98
0

You can also use the following lines after your plotting

#Your Plotting function
plt.waitforbuttonpress(0) 
plt.close(fig)

The plt.waitforbuttonpress(0) will wait until a user input (Key press) is given. After that it will properly close the matplotlib window properly. It is very important to specify which figure to close.