当激活图形缩放工具时,如何隐藏十字线光标或活动的十字线光标?

时间:2018-12-03 12:00:26

标签: python matplotlib pyqt5

当我的缩放工具栏处于活动状态时,我的十字光标不起作用。如何隐藏现有的十字光标。如果我无法隐藏先前的十字光标。我想启用十字光标。

我的main.py文件

import sys
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
from matplotlib.widgets import MultiCursor
from PyQt5.QtWidgets import QMainWindow,QVBoxLayout
from PyQt5.QtWidgets import QApplication
from PyQt5 import QtCore, QtGui, QtWidgets
from multicursor_c import *
from Toolbar import MyToolbar
import datetime
from matplotlib.dates import num2date, date2num
from matplotlib.dates import  DateFormatter, WeekdayLocator, HourLocator,DayLocator, SUNDAY
from mpl_finance import candlestick_ochl as candlestick
import numpy as np
class MainWindow_code_serarch(object):

    def setup_code_serarch(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(870, 680)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.verticalLayoutWidget1 = QtWidgets.QWidget(self.centralwidget)
        self.verticalLayoutWidget1.setGeometry(QtCore.QRect(17, 30, 341, 153))
        self.verticalLayoutWidget1.setObjectName("verticalLayoutWidget")
        self.verticalLayout1 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget1)
        self.verticalLayout1.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout1.setObjectName("verticalLayout1")

        self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(17, 150, 741, 553))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.figure = Figure(figsize=None, dpi=80, facecolor='k')
        self.canvas = FigureCanvas(self.figure)
        self.navigation_toolbar = MyToolbar(self.canvas, self)
        self.navigation_toolbar.coordinates = False

        self.verticalLayout.addWidget(self.canvas)
        self.verticalLayout1.addWidget(self.navigation_toolbar)
        axes, axes2 = self.figure.subplots(nrows=2, sharex=True)



        dates = ['2018/10/30', '2018/11/03', '2018/11/04', '2018/11/05', '2018/11/07', '2018/11/10', '2018/11/11']
        x = date2num([datetime.datetime.strptime(d, '%Y/%m/%d').date() for d in dates])
        print(x)

        # date_list = np.array(dates.index.to_pydatetime())

        open = [8824, 8726.31, 8642.14, 8531.51, 8630.25, 8602.50, 8640.22]
        high = [8858, 8748.60, 8551.36, 8653.16, 8476.69, 8630, 8570.56]
        low = [8688, 8743.67, 8550.76, 8449.50, 8631.83, 8602.18, 8743.22]
        close = [8820, 8747.17, 8550.52, 8553., 8517.10, 8628.78, 8588.52]
        volume = [17759.56, 120000.17, 18739.52, 38599.50, 16517.10, 17723.78, 15588.52]
        candle_trace = zip(*[x, open, high, low, close, volume])

        lines, patches =  candlestick(axes, candle_trace, width=.7,colorup='g', colordown='r',alpha=.9)
        for line, patch in zip(lines, patches):
            patch.set_edgecolor("y")
            patch.set_linewidth(0.72)
            patch.set_antialiased(False)
            line.set_color("w")
            line.set_zorder(0)
        axes2.plot(x,[1, 2, 3, 4,7,8,9])

        # mondays = WeekdayLocator(SUNDAY)
        # alldays = DayLocator()
        weekFormatter = DateFormatter('%b %d')
        dayFormatter = DateFormatter('%d')

        # axes.xaxis.set_major_locator(mondays)
        # axes2.xaxis.set_major_locator(mondays)

        # axes2.xaxis.set_minor_locator(alldays)
        # axes.xaxis.set_minor_locator(alldays)
        # axes.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))

        axes.set_position([0.02, 0.37, 0.88, 0.6])
        axes2.set_position([0.02, 0.15, 0.88, 0.22])
        axes.tick_params(axis='both', color='#ffffff', labelcolor='#ffffff')
        axes.yaxis.tick_right()
        axes2.tick_params(axis='both', color='#ffffff', labelcolor='#ffffff')
        axes2.grid(color='lightgray', linewidth=.5, linestyle=':')
        axes.grid(color='lightgray', linewidth=.5, linestyle=':')
        axes2.yaxis.tick_right()
        axes.autoscale_view()
        axes2.autoscale_view()
        axes2.xaxis_date()
        axes.xaxis_date()

        axes.margins(0, .5)
        axes2.margins(0, .5)
        axes.set_facecolor('#041105')
        axes2.set_facecolor('#041105')

        self.multi = FigureCursor(self.figure, horizOn=True, vertOn=True, color='r', lw=1)
        self.canvas.draw()


        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 246, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        # self.pushButton.clicked.connect(self.graphShowCode)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        # self.pushButton.setText(_translate("MainWindow", "OK"))






if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = MainWindow_code_serarch()
    ui.setup_code_serarch(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

这是我的main.py文件,我已经导入了multicursor_c.py文件和Toolbar.py文件。我在multicursor_c.py文件中实现了图形光标。在Toolbar.py中,我继承了matplotlib NavigationToolbar类

multicursor_c.py文件

from matplotlib.widgets import MultiCursor
from matplotlib.widgets import *
from matplotlib.figure import Figure
class FigureCursor(Widget):
    def __init__(self, fig, horizOn=True, vertOn=True, useblit=True, **lineprops):
        self._cidmotion = None
        self._ciddraw = None
        self.background = None
        self.needclear = False
        self.visible = True
        self.canvas = fig.canvas
        self.fig = fig
        self.horizOn = horizOn
        self.vertOn = vertOn
        self.useblit = useblit
        lineprops = dict(color='w', linestyle='--',linewidth=1, alpha=0.5)
        self.vline, = fig.axes[0].plot([1, 1], [0., 1.], visible=vertOn, transform=self.fig.transFigure,
                                       clip_on = False, **lineprops)
        self.hline, = fig.axes[0].plot([0., 1.], [-1., 0.], visible=horizOn, transform=self.fig.transFigure,
                                       clip_on=False, **lineprops)
        self.connect()

    def connect(self):
        """connect events"""
        self._cidmotion = self.canvas.mpl_connect('motion_notify_event', self.onmove)
        self._ciddraw = self.canvas.mpl_connect('draw_event', self.clear)

    def disconnect(self):
        """disconnect events"""
        self.canvas.mpl_disconnect(self._cidmotion)
        self.canvas.mpl_disconnect(self._ciddraw)

    def clear(self, event):
        """clear the cursor"""
        if self.ignore(event):
            return
        if self.useblit:
            self.background = (
                self.canvas.copy_from_bbox(self.canvas.figure.bbox))
        for line in [self.vline, self.hline]:
            line.set_visible(False)

    def onmove(self, event):
        if self.ignore(event):
            return
        if event.inaxes is None:
            return
        if not self.canvas.widgetlock.available(self):
            return
        self.needclear = True
        if not self.visible:
            return
        trans = event.inaxes.transData + self.fig.transFigure.inverted()
        x_fig, y_fig = trans.transform([event.xdata, event.ydata])
        if self.vertOn:
            self.vline.set_xdata([x_fig, x_fig])
            self.vline.set_visible(self.visible)
        if self.horizOn:
            self.hline.set_ydata([y_fig, y_fig])
            self.hline.set_visible(self.visible)
        self._update()

    def _update(self):
        if self.useblit:
            if self.background is not None:
                self.canvas.restore_region(self.background)
            if self.vertOn:
                self.fig.draw_artist(self.vline)
            if self.horizOn:
                self.fig.draw_artist(self.hline)
            self.canvas.blit(self.canvas.figure.bbox)
        else:
            self.canvas.draw_idle()

我的Toolbar.py文件

from matplotlib.backends.backend_qt5 import NavigationToolbar2QT as NavigationToolbar
class MyToolbar(NavigationToolbar):
  def __init__(self, figure_canvas, parent= None):
    self.toolitems = (
        # ('Home', 'Lorem ipsum dolor sit amet', 'home', 'home'),
        ('Back', 'consectetuer adipiscing elit', 'back', 'back'),
        ('Forward', 'sed diam nonummy nibh euismod', 'forward', 'forward'),
        (None, None, None, None),
        ('Pan', 'tincidunt ut laoreet', 'move', 'pan'),
        ('Zoom', 'dolore magna aliquam', 'zoom_to_rect', 'zoom'),
        (None, None, None, None),
        ('Subplots', 'putamus parum claram', 'subplots', 'configure_subplots'),
        ('Save', 'sollemnes in futurum', 'filesave', 'save_figure'),
        # ('Port', 'Select', "select", 'select_tool'),
        ('Home', 'Lorem ipsum dolor sit amet', 'home', 'home'),
        )
    NavigationToolbar.__init__(self, figure_canvas, parent= None)

  def select_tool(self):
    print ("You clicked the selection tool")

enter image description here

python 3.5 pyqt5 matplotlib

0 个答案:

没有答案