我使用的是macOS系統。當在虛擬環(huán)境中嘗試使用matplotlib時淤堵,會出現如下的報錯:
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 other backends. 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 informatio
根據錯誤信息寝衫,要么我們使用Python as Framework,要么我們更換使用的后端(backend)拐邪。Matplot專門就matplotlib的后端問題有一個網頁:Working with Matplotlib in Virtual environments慰毅。文章中提到,Tk
這個框架(即TkAgg
后端)一般來說總是可用的扎阶,不需要額外的外部依賴汹胃。(不過在特定的Linux發(fā)行版本中可能需要安裝python-tk
)。要使用Tk
需要做如下配置過程:
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pylab as plt
每次這么配置比較麻煩东臀,我們可以通過~/.matplotlib/matplitlibrc
文件來固化配置(如果這個文件不存在可以手動創(chuàng)建)着饥,文件中添加如下內容:
backend: TkAgg
不過我在使用過程中發(fā)現使用TkAgg
時會出現系統級的錯誤,拋出了Terminating app due to uncaught exception
的錯誤惰赋。因此我嘗試替換成其他后端宰掉。我主要選擇包括:
Matplotlib可用后端類型
而又因為PySide
只支持比較早的python版本呵哨,因此我選擇了Qt5作為后端。在這之前轨奄,我們需要安裝下面的依賴
brew install qt
pip install PySide2
安裝完成后配置過程和TkAgg
的類似孟害,后端的名字為QT5Agg
。