简体   繁体   English

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

[英]Using matplotlib Cursor widget in GUI embedded plot

I've got a PyQt4 GUI which has a matplotlib plot embedded in it. 我有一个PyQt4 GUI,其中嵌入了matplotlib图。 I want to add a Cursor widget ( much like this example , which does work for me) to the plot. 我想在剧情中添加一个Cursor小部件( 很像这个例子 ,它对我有用)。 For some reason, the Cursor doesn't show up in my embedded plot. 由于某种原因,Cursor不会出现在我的嵌入式绘图中。 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_())

From the matplotlib.widgets.Cursor documentation : 来自matplotlib.widgets.Cursor文档

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM