Mac系統(tǒng)下Python-Matplotlib問(wèn)題及解決方法匯總

問(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è)置快捷鍵:雙擊一下然后鍵入你喜歡的快捷鍵
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容