├── grid.PNG ├── README.md ├── matplotlibPyQt5.py ├── matplotPyQt5titlelabel.py └── addingSaveButton.py /grid.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/boxcontrol/matplotlibPyQt5/HEAD/grid.PNG -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # matplotlibPyQt5 2 | 3 | ##Introduction 4 | 5 | Embedding [matplotlib plot](http://matplotlib.org/) on PyQt GUI or some other python GUI library's is noting new when it comes to examples provided by various authors across the web and examples provided in [matplotlib documentation](http://matplotlib.org/examples/user_interfaces/index.html). But as you can see there is no example for embedding matplotlib plot in PyQt5. I wanted to make some small app for my android device and needed plot as part of my application. You can do this with [PySide](http://qt-project.org/wiki/PySide), and I encourage you to do so if you want to make commercial app, for me this was not the case, my app is for my own purpose and at some point I might switch from android to iOS device. Remember that PySide is not going to work on iOS devices while [PyQt5](http://www.riverbankcomputing.com/software/pyqt/download5) will. 6 | 7 | ##Prerequisites 8 | 9 | Like in previous python samples I will use Python 3. All things you need for this: 10 | 11 | - Python 3 12 | - [PyQt5](http://www.riverbankcomputing.com/software/pyqt/download5) 13 | - [Matplotlib 1.4.2](http://matplotlib.org/1.4.2/index.html) 14 | 15 | I'm not sure but previous versions of matplolib don't support PyQt5. 16 | 17 | Embedding matplotlib plot on PyQt5 GUI! 18 | 19 | ##Read in full on my [blog](http://www.boxcontrol.net/embedding-matplotlib-plot-on-pyqt5-gui.html) 20 | 21 | ###Screnshot of matplotlibPyQt5titlelabel.py output: 22 | 23 | ![Alt text](https://github.com/boxcontrol/matplotlibPyQt5/blob/master/grid.PNG) 24 | -------------------------------------------------------------------------------- /matplotlibPyQt5.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import random 3 | import matplotlib 4 | matplotlib.use("Qt5Agg") 5 | from PyQt5 import QtCore 6 | from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget 7 | from numpy import arange, sin, pi 8 | from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas 9 | from matplotlib.figure import Figure 10 | 11 | 12 | class MyMplCanvas(FigureCanvas): 13 | """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.).""" 14 | def __init__(self, parent=None, width=5, height=4, dpi=100): 15 | fig = Figure(figsize=(width, height), dpi=dpi) 16 | self.axes = fig.add_subplot(111) 17 | # We want the axes cleared every time plot() is called 18 | self.axes.hold(False) 19 | 20 | self.compute_initial_figure() 21 | 22 | # 23 | FigureCanvas.__init__(self, fig) 24 | self.setParent(parent) 25 | 26 | FigureCanvas.setSizePolicy(self, 27 | QSizePolicy.Expanding, 28 | QSizePolicy.Expanding) 29 | FigureCanvas.updateGeometry(self) 30 | 31 | def compute_initial_figure(self): 32 | pass 33 | 34 | class MyStaticMplCanvas(MyMplCanvas): 35 | """Simple canvas with a sine plot.""" 36 | def compute_initial_figure(self): 37 | t = arange(0.0, 3.0, 0.01) 38 | s = sin(2*pi*t) 39 | self.axes.plot(t, s) 40 | 41 | 42 | class MyDynamicMplCanvas(MyMplCanvas): 43 | """A canvas that updates itself every second with a new plot.""" 44 | def __init__(self, *args, **kwargs): 45 | MyMplCanvas.__init__(self, *args, **kwargs) 46 | timer = QtCore.QTimer(self) 47 | timer.timeout.connect(self.update_figure) 48 | timer.start(1000) 49 | 50 | def compute_initial_figure(self): 51 | self.axes.plot([0, 1, 2, 3], [1, 2, 0, 4], 'r') 52 | 53 | def update_figure(self): 54 | # Build a list of 4 random integers between 0 and 10 (both inclusive) 55 | l = [random.randint(0, 10) for i in range(4)] 56 | 57 | self.axes.plot([0, 1, 2, 3], l, 'r') 58 | self.draw() 59 | 60 | class ApplicationWindow(QMainWindow): 61 | def __init__(self): 62 | QMainWindow.__init__(self) 63 | self.setAttribute(QtCore.Qt.WA_DeleteOnClose) 64 | self.setWindowTitle("application main window") 65 | 66 | self.file_menu = QMenu('&File', self) 67 | self.file_menu.addAction('&Quit', self.fileQuit, 68 | QtCore.Qt.CTRL + QtCore.Qt.Key_Q) 69 | self.menuBar().addMenu(self.file_menu) 70 | 71 | self.help_menu = QMenu('&Help', self) 72 | self.menuBar().addSeparator() 73 | self.menuBar().addMenu(self.help_menu) 74 | 75 | self.help_menu.addAction('&About', self.about) 76 | 77 | self.main_widget = QWidget(self) 78 | 79 | l = QVBoxLayout(self.main_widget) 80 | sc = MyStaticMplCanvas(self.main_widget, width=5, height=4, dpi=100) 81 | dc = MyDynamicMplCanvas(self.main_widget, width=5, height=4, dpi=100) 82 | l.addWidget(sc) 83 | l.addWidget(dc) 84 | 85 | self.main_widget.setFocus() 86 | self.setCentralWidget(self.main_widget) 87 | 88 | self.statusBar().showMessage("All hail matplotlib!", 2000) 89 | 90 | def fileQuit(self): 91 | self.close() 92 | 93 | def closeEvent(self, ce): 94 | self.fileQuit() 95 | 96 | def about(self): 97 | QMessageBox.about(self, "About", 98 | """embedding_in_qt5.py example 99 | Copyright 2015 BoxControL 100 | 101 | This program is a simple example of a Qt5 application embedding matplotlib 102 | canvases. It is base on example from matplolib documentation, and initially was 103 | developed from Florent Rougon and Darren Dale. 104 | 105 | http://matplotlib.org/examples/user_interfaces/embedding_in_qt4.html 106 | 107 | It may be used and modified with no restriction; raw copies as well as 108 | modified versions may be distributed without limitation.""" 109 | ) 110 | 111 | if __name__ == '__main__': 112 | app = QApplication(sys.argv) 113 | 114 | aw = ApplicationWindow() 115 | aw.setWindowTitle("PyQt5 Matplot Example") 116 | aw.show() 117 | #sys.exit(qApp.exec_()) 118 | app.exec_() 119 | 120 | 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /matplotPyQt5titlelabel.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import random 3 | import matplotlib 4 | matplotlib.use("Qt5Agg") 5 | from PyQt5 import QtCore 6 | from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget 7 | from numpy import arange, sin, pi 8 | from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas 9 | from matplotlib.figure import Figure 10 | from matplotlib import pyplot as plt 11 | 12 | 13 | class MyMplCanvas(FigureCanvas): 14 | """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.).""" 15 | def __init__(self, parent=None, width=5, height=4, dpi=100, title='title'): 16 | self.title = title 17 | fig = Figure(figsize=(width, height), dpi=dpi) 18 | self.axes = fig.add_subplot(111) 19 | fig.suptitle(title) 20 | 21 | # We want the axes cleared every time plot() is called 22 | self.axes.hold(False) 23 | 24 | self.compute_initial_figure() 25 | 26 | 27 | FigureCanvas.__init__(self, fig) 28 | self.setParent(parent) 29 | 30 | FigureCanvas.setSizePolicy(self, 31 | QSizePolicy.Expanding, 32 | QSizePolicy.Expanding) 33 | FigureCanvas.updateGeometry(self) 34 | 35 | def compute_initial_figure(self): 36 | pass 37 | 38 | 39 | class MyStaticMplCanvas(MyMplCanvas): 40 | """Simple canvas with a sine plot.""" 41 | def compute_initial_figure(self): 42 | t = arange(0.0, 3.0, 0.01) 43 | s = sin(2*pi*t) 44 | self.axes.plot(t, s) 45 | self.axes.set_ylabel('label1') 46 | self.axes.set_xlabel('label') 47 | self.axes.grid(True) 48 | 49 | 50 | class MyDynamicMplCanvas(MyMplCanvas): 51 | """A canvas that updates itself every second with a new plot.""" 52 | def __init__(self, *args, **kwargs): 53 | MyMplCanvas.__init__(self, *args, **kwargs) 54 | timer = QtCore.QTimer(self) 55 | timer.timeout.connect(self.update_figure) 56 | timer.start(1000) 57 | 58 | def compute_initial_figure(self): 59 | self.axes.plot([0, 1, 2, 3], [1, 2, 0, 4], 'r') 60 | self.axes.set_ylabel('label1') 61 | self.axes.set_xlabel('label') 62 | self.axes.grid(True) 63 | 64 | def update_figure(self): 65 | # Build a list of 4 random integers between 0 and 10 (both inclusive) 66 | l = [random.randint(0, 10) for i in range(4)] 67 | self.axes.plot([0, 1, 2, 3], l, 'r') 68 | self.axes.set_ylabel('label y din plot') 69 | self.axes.set_xlabel('label x din plot') 70 | self.axes.grid(True) 71 | self.draw() 72 | 73 | 74 | class ApplicationWindow(QMainWindow): 75 | def __init__(self): 76 | QMainWindow.__init__(self) 77 | self.setAttribute(QtCore.Qt.WA_DeleteOnClose) 78 | self.setWindowTitle("application main window") 79 | 80 | self.file_menu = QMenu('&File', self) 81 | self.file_menu.addAction('&Quit', self.fileQuit, 82 | QtCore.Qt.CTRL + QtCore.Qt.Key_Q) 83 | self.menuBar().addMenu(self.file_menu) 84 | 85 | self.help_menu = QMenu('&Help', self) 86 | self.menuBar().addSeparator() 87 | self.menuBar().addMenu(self.help_menu) 88 | 89 | self.help_menu.addAction('&About', self.about) 90 | 91 | self.main_widget = QWidget(self) 92 | 93 | l = QVBoxLayout(self.main_widget) 94 | sc = MyStaticMplCanvas(self.main_widget, width=5, height=4, dpi=100, title='Title 1') 95 | dc = MyDynamicMplCanvas(self.main_widget, width=5, height=4, dpi=100, title='Title 2') 96 | l.addWidget(sc) 97 | l.addWidget(dc) 98 | 99 | self.main_widget.setFocus() 100 | self.setCentralWidget(self.main_widget) 101 | 102 | self.statusBar().showMessage("All hail matplotlib!", 2000) 103 | 104 | def fileQuit(self): 105 | self.close() 106 | 107 | def closeEvent(self, ce): 108 | self.fileQuit() 109 | 110 | def about(self): 111 | QMessageBox.about(self, "About", 112 | """embedding_in_qt5.py example 113 | Copyright 2015 BoxControL 114 | 115 | This program is a simple example of a Qt5 application embedding matplotlib 116 | canvases. It is base on example from matplolib documentation, and initially was 117 | developed from Florent Rougon and Darren Dale. 118 | 119 | http://matplotlib.org/examples/user_interfaces/embedding_in_qt4.html 120 | 121 | It may be used and modified with no restriction; raw copies as well as 122 | modified versions may be distributed without limitation.""") 123 | 124 | 125 | if __name__ == '__main__': 126 | app = QApplication(sys.argv) 127 | 128 | aw = ApplicationWindow() 129 | aw.setWindowTitle("PyQt5 Matplot Example") 130 | aw.show() 131 | #sys.exit(qApp.exec_()) 132 | app.exec_() -------------------------------------------------------------------------------- /addingSaveButton.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import random 3 | import matplotlib 4 | matplotlib.use("Qt5Agg") 5 | from PyQt5 import QtCore 6 | from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget, QPushButton 7 | from numpy import arange, sin, pi 8 | from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas 9 | from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar 10 | from matplotlib.figure import Figure 11 | 12 | 13 | # customize navigation toolbar 14 | class NavToolbar(NavigationToolbar): 15 | toolitems = [('Save', 'Save the figure', 'filesave', 'save_figure')] 16 | 17 | 18 | class MyMplCanvas(FigureCanvas): 19 | """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.).""" 20 | def __init__(self, parent=None, width=5, height=4, dpi=100, title='title'): 21 | self.title = title 22 | fig = Figure(figsize=(width, height), dpi=dpi) 23 | self.axes = fig.add_subplot(111) 24 | fig.suptitle(title) 25 | 26 | # We want the axes cleared every time plot() is called 27 | self.axes.hold(False) 28 | 29 | self.compute_initial_figure() 30 | 31 | 32 | FigureCanvas.__init__(self, fig) 33 | self.setParent(parent) 34 | 35 | FigureCanvas.setSizePolicy(self, 36 | QSizePolicy.Expanding, 37 | QSizePolicy.Expanding) 38 | FigureCanvas.updateGeometry(self) 39 | 40 | def compute_initial_figure(self): 41 | pass 42 | 43 | 44 | class MyStaticMplCanvas(MyMplCanvas): 45 | """Simple canvas with a sine plot.""" 46 | def compute_initial_figure(self): 47 | t = arange(0.0, 3.0, 0.01) 48 | s = sin(2*pi*t) 49 | self.axes.plot(t, s) 50 | self.axes.set_ylabel('label1') 51 | self.axes.set_xlabel('label') 52 | self.axes.grid(True) 53 | #self.axes.set_ylim(0, 0.5) 54 | 55 | 56 | class MyDynamicMplCanvas(MyMplCanvas): 57 | """A canvas that updates itself every second with a new plot.""" 58 | def __init__(self, *args, **kwargs): 59 | MyMplCanvas.__init__(self, *args, **kwargs) 60 | timer = QtCore.QTimer(self) 61 | timer.timeout.connect(self.update_figure) 62 | timer.start(1000) 63 | 64 | def compute_initial_figure(self): 65 | self.axes.plot([0, 1, 2, 3], [1, 2, 0, 4], 'r') 66 | self.axes.set_ylabel('label1') 67 | self.axes.set_xlabel('label') 68 | self.axes.grid(True) 69 | 70 | def update_figure(self): 71 | # Build a list of 4 random integers between 0 and 10 (both inclusive) 72 | l = [random.randint(0, 10) for i in range(4)] 73 | self.axes.plot([0, 1, 2, 3], l, 'r') 74 | self.axes.set_ylabel('label y din plot') 75 | self.axes.set_xlabel('label x din plot') 76 | self.axes.grid(True) 77 | self.draw() 78 | 79 | 80 | class ApplicationWindow(QMainWindow): 81 | def __init__(self): 82 | QMainWindow.__init__(self) 83 | self.setAttribute(QtCore.Qt.WA_DeleteOnClose) 84 | self.setWindowTitle("application main window") 85 | 86 | self.file_menu = QMenu('&File', self) 87 | self.file_menu.addAction('&Quit', self.fileQuit, 88 | QtCore.Qt.CTRL + QtCore.Qt.Key_Q) 89 | self.menuBar().addMenu(self.file_menu) 90 | 91 | self.help_menu = QMenu('&Help', self) 92 | self.menuBar().addSeparator() 93 | self.menuBar().addMenu(self.help_menu) 94 | 95 | self.help_menu.addAction('&About', self.about) 96 | 97 | self.main_widget = QWidget(self) 98 | 99 | l = QVBoxLayout(self.main_widget) 100 | sc = MyStaticMplCanvas(self.main_widget, width=5, height=4, dpi=100, title='Title 1') 101 | dc = MyDynamicMplCanvas(self.main_widget, width=5, height=4, dpi=100, title='Title 2') 102 | scntb = NavigationToolbar(sc, self.main_widget) # full toolbar 103 | dcntb = NavToolbar(dc, self.main_widget) # only save button 104 | 105 | l.addWidget(sc) 106 | l.addWidget(scntb) 107 | l.addWidget(dc) 108 | l.addWidget(dcntb) 109 | 110 | self.main_widget.setFocus() 111 | self.setCentralWidget(self.main_widget) 112 | 113 | self.statusBar().showMessage("All hail matplotlib!", 2000) 114 | 115 | 116 | def fileQuit(self): 117 | self.close() 118 | 119 | def closeEvent(self, ce): 120 | self.fileQuit() 121 | 122 | def about(self): 123 | QMessageBox.about(self, "About", 124 | """embedding_in_qt5.py example 125 | Copyright 2015 BoxControL 126 | 127 | This program is a simple example of a Qt5 application embedding matplotlib 128 | canvases. It is base on example from matplolib documentation, and initially was 129 | developed from Florent Rougon and Darren Dale. 130 | 131 | http://matplotlib.org/examples/user_interfaces/embedding_in_qt4.html 132 | 133 | It may be used and modified with no restriction; raw copies as well as 134 | modified versions may be distributed without limitation.""") 135 | 136 | 137 | if __name__ == '__main__': 138 | app = QApplication(sys.argv) 139 | 140 | aw = ApplicationWindow() 141 | aw.setWindowTitle("PyQt5 Matplot Example") 142 | aw.show() 143 | #sys.exit(qApp.exec_()) 144 | app.exec_() --------------------------------------------------------------------------------