Search code examples
pythonqtmatplotlibpyqt4pyqtgraph

How to integrate matplotlib fumction with QGraphicView?


I am developing a Desktop application using Qt Designer and PyQt4. I need to display a some figure with contour which in python could be done with matplotlib.pyplot.contourf. I want to display the result inside a QGraphicView object.

I am trying to do it by promoting the QGraphicView to a pygtgraph in Qt-Designer. If object name of QGraphicView is CNOPlot I have written

import matplotlib.pyplot as plt
self.CNOPlot.plot(plt.contourf(xx, yy, Z,cmap=plt.cm.autumn, alpha=0.8))

It is giving output in separate window. I want this is to be ploted inside CNOPlot.


Solution

  • Here is a short example:

    import matplotlib.pyplot as plt
    from PyQt4 import QtGui
    from PyQt4.Qt import Qt
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
    
    class MyView(QtGui.QGraphicsView):
        def __init__(self):
            QtGui.QGraphicsView.__init__(self)
    
            scene = QtGui.QGraphicsScene(self)
            self.scene = scene
    
            figure = Figure()
            axes = figure.gca()
            axes.set_title("title")
            axes.plot(plt.contourf(xx, yy, Z,cmap=plt.cm.autumn, alpha=0.8))
            canvas = FigureCanvas(figure)
            canvas.setGeometry(0, 0, 500, 500)
            scene.addWidget(canvas)
    
            self.setScene(scene)