1
votes

I've got a PyQt4 GUI which has a matplotlib plot embedded in it. I want to add a Cursor widget (much like this example, which does work for me) to the plot. For some reason, the Cursor doesn't show up in my embedded plot. What's going on?

Below is a minimum (non-)working example.

import sys
from PyQt4 import QtGui

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
from matplotlib.widgets import Cursor

import random

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

        plt.style.use('ggplot')
        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)

        # 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 '''
        data = [random.random() for i in range(25)]
        ax = self.figure.add_subplot(111)
        ax.hold(False)
        ax.plot(data, '*-')
        Cursor(ax, lw = 2)
        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_())
1

1 Answers

3
votes

From the matplotlib.widgets.Cursor documentation:

For the cursor to remain responsive you must keep a reference to it.

The easiest way to do this is to assign it to a class variable, self.cursor=Cursor(..).

def plot(self):
    ''' plot some random stuff '''
    data = [random.random() for i in range(25)]
    ax = self.figure.add_subplot(111)
    #ax.hold(False)  <- don't use ax.hold!
    ax.plot(data, '*-')
    self.cursor = Cursor(ax, lw = 2)
    self.canvas.draw()