問(wèn)題一:matplotlib繪圖窗口總是在最后面
在Mac系統(tǒng)下使用python的同學(xué)肯定遇到過(guò)這個(gè)問(wèn)題:用matplotlib繪圖的時(shí)候,窗口總是在最后面。比如我用的vscode編輯代碼的,成圖窗口總是在vscode后面,需要將vscode窗口縮小一點(diǎn)才能看到繪圖結(jié)果。這顯然不是我們想要的!
解決辦法
import matplotlib as mpl
mpl.use('TkAgg')
import matplotlib.pyplot as plt
在import matplotlib as mpl之后進(jìn)階著跟一句mpl.use('TkAgg')即可將繪圖窗口調(diào)到最前面。但是這句代碼必須緊跟mpl且不能放在plt之后,比如:
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.use('TkAgg')
將會(huì)提示錯(cuò)誤,而且窗口依然在最后面:
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()
問(wèn)題二:終端下無(wú)法import matplotlib
在終端使用python腳本繪圖可能出現(xiàn)如下的錯(cuò)誤提示
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.
解決方法
此問(wèn)題的解決方法與問(wèn)題一相同,也可以有第二種解決方法:在~/.matplotlib/matplotlibrc文件中添加backend: TkAgg
如何快速運(yùn)行腳本

code runner
安裝runner插件,然后設(shè)置你喜歡的快捷鍵,比如我喜歡用shift+enter,聰明的你一下就想到了,沒(méi)錯(cuò),這個(gè)就是jupyter-notebook的默認(rèn)運(yùn)行快捷鍵!

設(shè)置快捷鍵:雙擊一下然后鍵入你喜歡的快捷鍵