ModuleNotFoundError: No module named 'PyQt4',Spyder 导入 matplotlib 错误

最近刚学了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__)

(请忽略注释行)

 

保存,运行原文件,成功!

 

---恢复内容结束---

posted @ 2018-07-23 17:36  丿隔岸观灬  阅读(5809)  评论(0编辑  收藏  举报