问题一:matplotlib绘图窗口总是在最后面
在Mac系统下使用python的同学肯定遇到过这个问题:用matplotlib绘图的时候,窗口总是在最后面。比如我用的vscode编辑代码的,成图窗口总是在vscode后面,需要将vscode窗口缩小一点才能看到绘图结果。这显然不是我们想要的!
解决办法
import matplotlib as mpl
mpl.use('TkAgg')
import matplotlib.pyplot as plt
在import matplotlib as mpl
之后进阶着跟一句mpl.use('TkAgg')
即可将绘图窗口调到最前面。但是这句代码必须紧跟mpl
且不能放在plt
之后,比如:
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.use('TkAgg')
将会提示错误,而且窗口依然在最后面:
This call to matplotlib.use() has no effect because the backend has already
been chosen; matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.
The backend was *originally* set to 'MacOSX' by the following code:
File "test_MonokaiPro.py", line 3, in <module>
import matplotlib.pyplot as plt
File "/Users/zguo/.pyenv/versions/anaconda3-5.0.1/lib/python3.6/site-packages/matplotlib/pyplot.py", line 69,in <module>
from matplotlib.backends import pylab_setup
File "/Users/zguo/.pyenv/versions/anaconda3-5.0.1/lib/python3.6/site-packages/matplotlib/backends/__init__.py", line 14, in <module>
line for line in traceback.format_stack()
问题二:终端下无法import matplotlib
在终端使用python脚本绘图可能出现如下的错误提示
from matplotlib.backends import _macosx
ImportError: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework. See the Python documentation for more information on installing Python as a framework on Mac OS X. Please either reinstall Python as a framework, or try one of the otherbackends. If you are using (Ana)Conda please install python.app and replace the use of 'python' with 'pythonw'. See 'Working with Matplotlib on OSX' in the Matplotlib FAQ for more information.
解决方法
此问题的解决方法与问题一相同,也可以有第二种解决方法:在~/.matplotlib/matplotlibrc
文件中添加backend: TkAgg
如何快速运行脚本
安装runner插件,然后设置你喜欢的快捷键,比如我喜欢用shift+enter
,聪明的你一下就想到了,没错,这个就是jupyter-notebook的默认运行快捷键!