问题
I'm experiencing some newly odd behavior from IPython. I just had to do a clean reinstall of my miniconda, so I now have fresh IPython and Matplotlib versions. It turns out that IPython is automatically switching matplotlib to interactive mode (which has the annoying side effect of making my saved figures blank in my scripts, because they save after I close the window).
Here's an example:
Python 3.7.3 | packaged by conda-forge | (default, Jul 1 2019, 21:52:21)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.6.1 -- An enhanced Interactive Python. Type '?' for help.
In [1]: import matplotlib as mpl
In [2]: import matplotlib.pyplot as plt
In [3]: mpl.is_interactive()
Out[3]: False
In [4]: plt.plot([1,2])
Out[4]: [<matplotlib.lines.Line2D at 0x7f0b0b048940>]
In [5]: mpl.is_interactive()
Out[5]: True
Is there a way to stop this behavior?
Note, I've tested the same code in regular python and interactive mode stays off.
回答1:
It's a bug in the interplay between matplotlib and IPython, which got introduced in matplotlib version 3.1.0 (via #12637). It will be fixed in matplotlib 3.2 (via #14979).
Options you have:
- revert to matplotlib 3.0.3
- Use the current matplotlib development version
- Wait for matplotlib 3.2 to be released (scheduled for September 2019)
回答2:
A workaround for this version of ipython/matplotlib would be to define a custom ioff():
import matplotlib.pyplot as plt
import matplotlib as mpl
def my_ioff():
f = plt.figure()
plt.close(f)
plt.ioff()
my_ioff()
print(mpl.is_interactive())
f = plt.figure()
print(mpl.is_interactive())
-----------
-> False
-> False
Whereas before we had:
plt.ioff()
print(mpl.is_interactive())
f = plt.figure()
print(mpl.is_interactive())
-----------
-> False
-> True
来源:https://stackoverflow.com/questions/57153840/ipython-automatically-turning-on-matplotlib-interactive-mode