在GUI嵌入式绘图中使用matplotlib Cursor小部件

时间:2017-03-19 05:13:32

标签: python matplotlib plot pyqt

我有一个PyQt4 GUI,其中嵌入了matplotlib图。我想为情节添加一个Cursor小部件(much like this example,这对我有用)。由于某种原因,Cursor不会出现在我的嵌入式绘图中。发生了什么事?

以下是最低(非)工作示例。

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 个答案:

答案 0 :(得分:3)

来自matplotlib.widgets.Cursor documentation

  

要使光标保持响应,您必须保留对它的引用。

最简单的方法是将其分配给类变量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()