简体   繁体   中英

Why does my plot not disappear on exit in ipython mode?

I'm showing some plots using matplotlib in the ipython prompt. When closing the plot window it does not disappear but gets "stuck" in the background and does not respond to user actions. You can try it out yourself with the following code:

# test.py
import matplotlib.pyplot as plt

def f(): 
    plt.plot([1, 2, 3], [4, 3, 5])
    plt.show()

and in the prompt

pingul $ ipython
Python 3.5.2 (default, Jun 27 2016, 03:10:38) 
Type "copyright", "credits" or "license" for more information.

IPython 5.1.0 -- An enhanced Interactive Python.

In [1]: import test
In [2]: test.f()
### Trying to close it now doesn't work

Is this a bug, or can I fix it somehow?

Running the same code with the normal python prompt works as expected.

You should be a bit careful with using pyplot in ipython. Especially plt.show() is blocking the ipython terminal. You should use fig.show() , since it does not block ipython. If you really want to use pyplot, one work-around is to use plt.gcf().show() , which will get the current figure (gcf=get current figure) and only show that figure. However I would recommend creating the figure as fig = plt.figure() and then use fig.show() .

Please note that if you run it with python, you need plt.show() ! Otherwise the figure will show, and then close immediately!

Try running %matplotlib before plotting, so that IPython integrates with the GUI event loop showing the plots.

This shouldn't be necessary once matplotlib 2.0 is released, because it has some code to detect when it's running inside IPython.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM