I'm working with PyQt5 trying to generate a GUI for my data analysis tool. My problem is that I don't understand how to embed a matplotlib plot with full functionality.
All of the tutorials about PyQt5 and how to embed matplotlib show a very simple way where they create all of the graphical object directly in the code. I don't want to do that because my GUI was generated with Qt Designer. I created a QWidget to plot data in it. Therefore, I import the UI file in the code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import numpy as np
from PyQt5.QtGui import QPixmap
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget, QTableWidget, QTableWidgetItem
from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit, QFileDialog
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QSize
from PyQt5 import QtCore, QtGui, uic
import matplotlib
matplotlib.use('QT5Agg')
import matplotlib.pylab as plt
from matplotlib.backends.qt_compat import QtCore, QtWidgets, is_pyqt5
from matplotlib.backends.backend_qt5agg import FigureCanvas, NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
class MyWindow(QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
self.ui = 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)
# add toolbar
self.addToolBar(QtCore.Qt.BottomToolBarArea, NavigationToolbar(self.plotWidget, self))
#########################################
# show window
self.show()
#########################################
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = MyWindow()
sys.exit(app.exec_())
This is test.ui file created by Qt Designer:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>772</width>
<height>650</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<widget class="QWidget" name="plotWidge" native="true">
<property name="geometry">
<rect>
<x>20</x>
<y>20</y>
<width>721</width>
<height>571</height>
</rect>
</property>
</widget>
</widget>
<resources/>
<connections/>
</ui>
What happened is that I can see a toolbar in my window but now data. I can use the "save" icon to save the plot as an image. I think that I'm creating a second instance of a widget object that is not correlated to the one I created in Qt Designer.
How can I solve this problem?
Thanks in advance!
See Question&Answers more detail:
os