Search code examples
pythonmatplotlibpyqt5qt-designer

Error using FigureCanvasQTAgg in MatplotlibWidget pyqt5


I would like to plot on my GUI with pyqt5 using matplotlib. I have created a class called MatplotlibWidget which create the figure and canvas of my plot. But I have a problem to generate my canvas with the FigureCanvasQTAgg function (which is a matplotlib function).

Here the part of my code which is bugging:

import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg
from matplotlib.figure import Figure

#Some more code...not relevant

class MatplotlibWidget(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.fig = Figure()
        self.canvas = FigureCanvasQTAgg(self.fig) #line 86
        self.axis = self.fig.add_subplot(111)

        self.layoutVerticalTest = QVBoxLayout(self)
        self.layoutVerticalTest.addWidget(self.canvas)

I have this error :

File "/Users/AlexisTuil/Desktop/projet inno/sc_analysis/visualisation.py", line 86, in 
__init__self.canvas = FigureCanvasQTAgg(self.fig)
File "/usr/local/lib/python3.5/site packages/matplotlib/backends/backend_qt4agg.py", line 76, in     
__init__FigureCanvasQT.__init__(self, figure)
File "/usr/local/lib/python3.5/site-packages/matplotlib/backends/backend_qt4.py", line 71, in
__init__QtWidgets.QWidget.__init__(self)
TypeError: __init__() missing 1 required positional argument: 'figure'
Abort trap: 6

I've searched on many forums but I couldn't find out a solution to my problem. I don't get it why there is a missing "positional argument". Please help me !

I am on MacOS El Capitan with python3.5 64bit. I installed matplotlib with pip if it can help.


Solution

  • If using pyqt5, do this:

    from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg