Embed a matplotlib plot in a pyqt5 gui

I think you are confusing that you have created a widget called plotWidge in Qt Designer and you doing self.plotWidget = FigureCanvas(fig) are replacing it (even if the names coincide that action is not the one done), so that it does not cause confusion change plotWidge to content_plot in Qt Designer so the plotWidget must be placed in content_plot with the help of a layout.


<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <widget class="QWidget" name="Form">
  <property name="geometry">
  <property name="windowTitle">
  <widget class="QWidget" name="content_plot" native="true">
   <property name="geometry">


import sys
import numpy as np

from PyQt5 import QtCore, QtWidgets, uic

import matplotlib

import matplotlib.pylab as plt
from matplotlib.backends.backend_qt5agg import FigureCanvas 
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar

class MyWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MyWindow, self).__init__()
        uic.loadUi('test.ui', self) 
        # test data
        data = np.array([0.7,0.7,0.7,0.8,0.9,0.9,1.5,1.5,1.5,1.5])        
        fig, ax1 = plt.subplots()
        bins = np.arange(0.6, 1.62, 0.02)
        n1, bins1, patches1 = ax1.hist(data, bins, alpha=0.6, density=False, cumulative=False)
        # plot
        self.plotWidget = FigureCanvas(fig)
        lay = QtWidgets.QVBoxLayout(self.content_plot)  
        lay.setContentsMargins(0, 0, 0, 0)      
        # add toolbar
        self.addToolBar(QtCore.Qt.BottomToolBarArea, NavigationToolbar(self.plotWidget, self))

if __name__ == '__main__':

    app = QtWidgets.QApplication(sys.argv)
    window = MyWindow()

enter image description here

Leave a Comment