ModuleNotFoundError: No module named ‘PyQt4’ [Spyder Import matplotlib Error]

I just learned Matplotlib recently, and I want to play in Anaconda’s Spyder

The code is as follows (in fact, it’s not important, mainly because matplotlib.pyplot is imported and an error is reported)

# -*- 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()

error message:

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'

The problem is QT_ Compat.py file

The error indicates that PyQt4 can’t be found. The direct solution is to install PyQt4 package. However, after several times (taking two or three days) of various data searching and various attempts, all failed

The basic contradiction is that pyqt5 is configured by default in Anaconda environment, while PyQt4 is called by default in Matplotlib, which is a version problem

Finally, back to QT_ Compat.py file

if rcParams['backend'] == 'Qt5Agg':
    QT_RC_MAJOR_VERSION = 5
elif rcParams['backend'] == 'Qt4Agg':
    QT_RC_MAJOR_VERSION = 4

Notice the above code, try changing the default version


solutions

In QT_ Add code to compat.py file:

rcParams['backend']='Qt5Agg'

Namely:

""" 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__)

(ignore comment line)

Save, run the original file, success

Similar Posts: