Matplotlib in Virtualenv

我使用的是macOS系統。當在虛擬環境中嘗試使用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發行版本中可能需要安裝python-tk)。要使用Tk需要做如下配置過程:

import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pylab as plt

每次這麼配置比較麻煩,我們可以通過~/.matplotlib/matplitlibrc文件來固化配置(如果這個文件不存在可以手動創建),文件中添加如下內容:

backend: TkAgg

不過我在使用過程中發現使用TkAgg時會出現系統級的錯誤,拋出了Terminating app due to uncaught exception的錯誤。因此我嘗試替換成其他後端。我主要選擇包括:

而又因爲PySide只支持比較早的python版本,因此我選擇了Qt5作爲後端。在這之前,我們需要安裝下面的依賴

brew install qt
pip install PySide2

安裝完成後配置過程和TkAgg的類似,後端的名字爲QT5Agg

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章