By ari


2012-09-17 13:04:39 8 Comments

I am currently trying to embed a graph I want to plot in a pyqt4 user interface I designed. As I am almost completely new to programming - I do not get how people did the embedding in the examples I found - this one (at the bottom) and that one.

It would be awesome if anybody could post a step-by-step explanation or at least a very small, very simple code only creating e.g. a graph and a button in one pyqt4 GUI.

2 comments

@Avaris 2012-09-17 19:26:05

It is not that complicated actually. Relevant Qt widgets are in matplotlib.backends.backend_qt4agg. FigureCanvasQTAgg and NavigationToolbar2QT are usually what you need. These are regular Qt widgets. You treat them as any other widget. Below is a very simple example with a Figure, Navigation and a single button that draws some random data. I've added comments to explain things.

import sys
from PyQt4 import QtGui

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure

import random

class Window(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on
        self.figure = Figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # Just some button connected to `plot` method
        self.button = QtGui.QPushButton('Plot')
        self.button.clicked.connect(self.plot)

        # set the layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def plot(self):
        ''' plot some random stuff '''
        # random data
        data = [random.random() for i in range(10)]

        # create an axis
        ax = self.figure.add_subplot(111)

        # discards the old graph
        ax.clear()

        # plot data
        ax.plot(data, '*-')

        # refresh canvas
        self.canvas.draw()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    main = Window()
    main.show()

    sys.exit(app.exec_())

Edit:

Updated to reflect comments and API changes.

  • NavigationToolbar2QTAgg changed with NavigationToolbar2QT
  • Directly import Figure instead of pyplot
  • Replace deprecated ax.hold(False) with ax.clear()

@Laurence Billingham 2014-10-01 20:03:14

Note that according to this SO note, one should not import pyplot when embedding. It does funky things like running its own GUI with its own main loop.There is a Matplotlib example on embedding

@GSandro_Strongs 2015-10-26 22:22:49

I have an error: MatplotlibDeprecationWarning: This class has been deprecated in 1.4 as it has no additional functionality over NavigationToolbar2QT. Please change your code to use NavigationToolbar2QT instead mplDeprecation)

@SAAD 2016-05-20 10:12:38

@gs_developer_user3605534 replacing NavigationToolbar2QTAgg by NavigationToolbar2QT kills the message

@C Winkler 2017-05-11 09:47:32

When I use this code, it creates two windows, one Qt main window and one matplotlib figure. How can I avoid that so that it creates just one Qt main window? I use python 3.4 32bit, matplotlib 1.5.3 and PyQt4 ( I also had to change NavigationToolbar2QTAgg to NavigationToolbar2QT). I found that one solution is using IPython

@Kajsa 2018-01-10 22:06:28

I'm using this to put a QVBoxLayout inside a main window. Is there a way to get the canvas and figure to fill a tall rectangle (approximately 1.5 times as tall as it is wide)?

@Avaris 2018-01-10 23:00:22

@Kajsa, it should be doable with heightForWidth.

@iperetta 2018-10-17 21:26:01

With QT5, just change to: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas and from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar

@Neeraj Kumar 2019-07-23 14:26:13

How do I resize the canvas?

@Avaris 2019-07-23 15:11:28

@NeerajKumar What do you mean "resize"? My example uses all the available space on the window. It'll grow/shrink with the window.

@Neeraj Kumar 2019-07-23 15:23:57

I don't want it to take all the available space but just a portion of it. Also, instead of plotting a graph I want to plot an image there (like plt.imshow(<numpymatrix>) ) . How do I do that?

@Avaris 2019-07-23 19:32:03

ax.imshow instead of ax.plot. Regarding size, depends on what else is going to occupy rest of it. Qt layouts handle sizing widgets based on SizePolicy. You need to adjust that.

@Anabar 2017-03-13 22:08:05

Below is an adaptation of previous code for using under PyQt5 and Matplotlib 2.0. There are a number of small changes: structure of PyQt submodules, other submodule from matplotlib, deprecated method has been replaced...


import sys
from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt

import random

class Window(QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on
        self.figure = plt.figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # Just some button connected to `plot` method
        self.button = QPushButton('Plot')
        self.button.clicked.connect(self.plot)

        # set the layout
        layout = QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def plot(self):
        ''' plot some random stuff '''
        # random data
        data = [random.random() for i in range(10)]

        # instead of ax.hold(False)
        self.figure.clear()

        # create an axis
        ax = self.figure.add_subplot(111)

        # discards the old graph
        # ax.hold(False) # deprecated, see above

        # plot data
        ax.plot(data, '*-')

        # refresh canvas
        self.canvas.draw()

if __name__ == '__main__':
    app = QApplication(sys.argv)

    main = Window()
    main.show()

    sys.exit(app.exec_())

@Pierre H. 2017-03-22 13:51:32

Very useful update, runs fine! Could you give a reference for ax.hold being deprecated? Also, why not use ax.clear to reuse the Axes instance?

@hhprogram 2018-08-29 07:20:30

I think it's not best practice to import matplotlib.pyplot when embedding matplotlib into pyqt (please correct me if I'm wrong in this siutation). If I am correct, I embedded my matplotlib using this method on this SO post, which doesn't import pyplot: stackoverflow.com/questions/43947318/…

@Neeraj Kumar 2019-07-23 14:28:14

How do I plot images on the canvas?

Related Questions

Sponsored Content

40 Answered Questions

[SOLVED] How to make a flat list out of list of lists?

10 Answered Questions

34 Answered Questions

[SOLVED] How do I sort a dictionary by value?

42 Answered Questions

[SOLVED] How do I merge two dictionaries in a single expression?

21 Answered Questions

[SOLVED] How do I list all files of a directory?

  • 2010-07-08 19:31:22
  • duhhunjonn
  • 3893487 View
  • 3474 Score
  • 21 Answer
  • Tags:   python directory

25 Answered Questions

[SOLVED] How can I safely create a nested directory?

38 Answered Questions

[SOLVED] How do I check whether a file exists without exceptions?

27 Answered Questions

[SOLVED] How do I check if a list is empty?

  • 2008-09-10 06:20:11
  • Ray Vega
  • 2625486 View
  • 3234 Score
  • 27 Answer
  • Tags:   python list

16 Answered Questions

[SOLVED] How do you change the size of figures drawn with matplotlib?

18 Answered Questions

[SOLVED] Save plot to image file instead of displaying it using Matplotlib

  • 2012-03-08 17:38:10
  • Homunculus Reticulli
  • 1485335 View
  • 1085 Score
  • 18 Answer
  • Tags:   python matplotlib plot

Sponsored Content