最近剛學了matplotlib,想在anaconda的spyder里耍一耍
代碼如下(其實不重要,主要是導入了matplotlib.pyplot報錯)
# -*- coding: utf-8 -*- """ Created on Thu Jul 12 21:36:51 2018 @author: asus """ print("b") import matplotlib.pyplot as plt print("a") a= [1,2,3] b= [1,2,3] plt.plot(a,b) plt.show()
錯誤提示信息:
File "C:\Users\asus\Anaconda3\lib\site-packages\matplotlib\backends\qt_compat.py", line 157, in <module> from PyQt4 import QtCore, QtGui ModuleNotFoundError: No module named 'PyQt4'
問題出在qt_compat.py文件
錯誤提示找不到PyQt4,直觀解決方法是安裝PyQt4包,但經過若干次(耗時兩三天)的各種查資料,各種嘗試,均以失敗告終
基本矛盾是:anaconda環境下默認配置了PyQt5,而matplotlib默認調用PyQt4,即版本問題
最后回到qt_compat.py文件
if rcParams['backend'] == 'Qt5Agg': QT_RC_MAJOR_VERSION = 5 elif rcParams['backend'] == 'Qt4Agg': QT_RC_MAJOR_VERSION = 4
注意到以上代碼,試更改默認版本
解決方案
在qt_compat.py文件中添加代碼:
rcParams['backend']='Qt5Agg'
即:
""" A Qt API selector that can be used to switch between PyQt and PySide. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six import os import logging import sys from matplotlib import rcParams #rcParams['backend']='PyQt5' # added by chen to adapt the matplotlib rcParams['backend']='Qt5Agg' # added by chen to adapt the matplotlib #print("----------------"+rcParams['backend']) _log = logging.getLogger(__name__)
(請忽略注釋行)
保存,運行原文件,成功!

---恢復內容結束---
