Someone in office wanted a quick demo on how to use zoom functionality of matplotlib with pyQt. Pointed him to some good and basic matplotlib examples but none was good enough.
Next day morning, just went to net and found this post titled How to embed matplotib in pyqt – for Dummies. And building on the supplied code, I added the needed functionally.
So here’s the code to embed matplotlib with pyQt with the ability to zoom, pan the data.
""" Created on Thu Dec 12 08:38:21 2013 @author: Sukhbinder Singh Simple QTpy and MatplotLib example with Zoom/Pan Built on the example provided at How to embed matplotib in pyqt - for Dummies http://stackoverflow.com/questions/12459811/how-to-embed-matplotib-in-pyqt-for-dummies """ import sys from PyQt4 import QtGui from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar import matplotlib.pyplot as plt import random class Window(QtGui.QDialog): def __init__(self, parent=None): super(Window, self).__init__(parent) self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas, self) self.toolbar.hide() # Just some button self.button = QtGui.QPushButton('Plot') self.button.clicked.connect(self.plot) self.button1 = QtGui.QPushButton('Zoom') self.button1.clicked.connect(self.zoom) self.button2 = QtGui.QPushButton('Pan') self.button2.clicked.connect(self.pan) self.button3 = QtGui.QPushButton('Home') self.button3.clicked.connect(self.home) # set the layout layout = QtGui.QVBoxLayout() layout.addWidget(self.toolbar) layout.addWidget(self.canvas) layout.addWidget(self.button) layout.addWidget(self.button1) layout.addWidget(self.button2) layout.addWidget(self.button3) self.setLayout(layout) def home(self): self.toolbar.home() def zoom(self): self.toolbar.zoom() def pan(self): self.toolbar.pan() def plot(self): ''' plot some random stuff ''' data = [random.random() for i in range(25)] ax = self.figure.add_subplot(111) ax.hold(False) ax.plot(data, '*-') self.canvas.draw() if __name__ == '__main__': app = QtGui.QApplication(sys.argv) main = Window() main.setWindowTitle('Simple QTpy and MatplotLib example with Zoom/Pan') main.show() sys.exit(app.exec_())
I don’t particularly like Qt. But I guess the exercise was worth it as it sparked a series of other experiments.
Leave a comment