当前位置: 首页>>代码示例>>Python>>正文


Python FigureCanvasQTAgg.setParent方法代码示例

本文整理汇总了Python中matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg.setParent方法的典型用法代码示例。如果您正苦于以下问题:Python FigureCanvasQTAgg.setParent方法的具体用法?Python FigureCanvasQTAgg.setParent怎么用?Python FigureCanvasQTAgg.setParent使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg的用法示例。


在下文中一共展示了FigureCanvasQTAgg.setParent方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: MPLibWidget

# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setParent [as 别名]
class MPLibWidget(QtWidgets.QWidget):
    """
    base MatPlotLib widget
    """
    def __init__(self, parent=None):
        super(MPLibWidget, self).__init__(parent)
        
        self.figure = Figure()
        self.canvas = FigureCanvasQTAgg(self.figure)
        self.canvas.setParent(self)
        
        self.mpl_toolbar = NavigationToolbar2QT(self.canvas, self)
        
        self.canvas.mpl_connect('key_press_event', self.on_key_press)
        
        self.axes = self.figure.add_subplot(111)
        # self.axes.hold(False)

        self.compute_initial_figure()
        
        self.layoutVertical = QtWidgets.QVBoxLayout(self)
        self.layoutVertical.addWidget(self.canvas)
        self.layoutVertical.addWidget(self.mpl_toolbar)
        
    def on_key_press(self, event):
        """not working"""
        print('you pressed', event.key)
        # implement the default mpl key press events described at
        # http://matplotlib.org/users/navigation_toolbar.html#navigation-keyboard-shortcuts
        key_press_handler(event, self.canvas, self.mpl_toolbar)    
        
    def compute_initial_figure(self):
        pass
开发者ID:VDFaller,项目名称:Optical-Modeling,代码行数:35,代码来源:Main.py

示例2: GraphTab

# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setParent [as 别名]
class GraphTab(QWidget):
    def __init__(self, options):
        super(GraphTab, self).__init__()
        self.options = options
        self.options.reset.connect(self.reset)
        self.options.redraw.connect(self.redraw)

        self.commodities = CommodityBox(options)
        self.commodities.changed.connect(self.redraw)

        self.fig = Figure()
        self.ax = self.fig.add_subplot(111)

        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)

        self.mpl_toolbar = NavigationToolbar(self.canvas, self)
        self.cmap = get_cmap('gist_ncar')

        graphLayout = QVBoxLayout()
        graphLayout.addWidget(self.canvas)
        graphLayout.addWidget(self.mpl_toolbar)

        layout = QHBoxLayout(self)
        layout.addWidget(self.commodities)
        layout.addLayout(graphLayout)

        self.running_total = None

    def reset(self):
        options = self.options
        self.commodity = options.show_currency.currentText()
        self.merge = bool(self.commodity and options.merge.isChecked())

        filter = options.filter.text()
        self.running_total, self.total = options.journal.time_series(filter, self.commodity, self.merge)
        self.redraw()

    def redraw(self):
        self.ax.clear()
        if not self.running_total:
            return

        lines = len(self.total)
        colors = map(self.cmap, ((x+0.5)/lines for x in range(lines)))

        for color, (commodity, amount) in zip(colors, sorted(self.total.items(), key=lambda x: x[1].number(), reverse=True)):
            if commodity not in self.commodities:
                continue
            series = self.running_total[commodity]
            x = sorted(series.keys())
            y = [series[i].number() for i in x]
            label = ("%s (%." + str(amount.commodity.precision) + "f %s)") % (commodity, amount.number(), amount.commodity.symbol)
            self.ax.plot_date(x, y, fmt='o-', color=color, label=label)

        if self.commodity:
            self.ax.set_ylabel(self.commodity)
        self.ax.legend(loc='upper left')
        self.fig.canvas.draw()
开发者ID:mistotebe,项目名称:visualise_ledger,代码行数:61,代码来源:app.py

示例3: _create_canvas

# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setParent [as 别名]
    def _create_canvas(self, parent):
        print(self.__class__.__name__, ": Creating canvas (_create_canvas)")
        # matplotlib commands to create a canvas
        frame = QtGui.QWidget()
        mpl_canvas = FigureCanvas(self.value)
        mpl_canvas.setParent(frame)
        mpl_toolbar = NavigationToolbar2QT(mpl_canvas, frame)

        # mpl_toolbar.setIconSize(QtCore.QSize(30, 30))  # activate for smaller icon sizes

        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(mpl_canvas)
        vbox.addWidget(mpl_toolbar)
        frame.setLayout(vbox)

        return frame
开发者ID:SirJohnFranklin,项目名称:TraitsMatplotlibWidget,代码行数:18,代码来源:TraitsMPLWidget.py

示例4: QFigureWidget

# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setParent [as 别名]
class QFigureWidget(QtWidgets.QWidget):
    """Widget to layout the actual figure and toolbar. Further it forwards.
    the key press events from the widget to the figure."""

    def __init__(self, fig, *args, **kw):
        super(QFigureWidget, self).__init__(*args, **kw)
        self.fig = fig

        self.canvas = FigureCanvasQTAgg(self.fig)
        self.canvas.setParent(self)
        self.canvas.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.canvas.setFocus()

        color = fig.get_facecolor()
        self.toolbar = QNavigationToolbar(self.canvas, self)

        self.toolbar.setStyleSheet("QNavigationToolbar { background-color: %s }"
                                   %rgb2hex(color))
        self.toolbar.setIconSize(QtCore.QSize(16, 16))
        self.canvas.mpl_connect('key_press_event', self.on_key_press)

        vbox = QtWidgets.QVBoxLayout(self)
        vbox.addWidget(self.canvas)
        vbox.addWidget(self.toolbar)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)

    def hideToolbar(self):
        self.toolbar.hide()

    def showToolbar(self):
        self.toolbar.show()

    def close(self):
        super(QFigureWidget, self).close()

    def on_key_press(self, event):
        # sometimes mpl has a weird ideas what oo-programing is.
        # any could overwrite method by my self

        # no fullscreen unless self is a window!
        if event.key == "t":
            self.toolbar.toggle()
        elif event.key not in rcParams["keymap.fullscreen"]:
            key_press_handler(event, self.canvas, self.toolbar)
开发者ID:manerotoni,项目名称:afw,代码行数:47,代码来源:qmpl.py

示例5: _add_figure

# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setParent [as 别名]
    def _add_figure(self, key, label, *args, **kwargs):
        tab = QWidget()
        fig, _ = plt.subplots(*args, **kwargs)
        canvas = FigureCanvas(fig)
        canvas.setMinimumWidth(640)
        canvas.setParent(tab)
        toolbar = NavigationToolbar(canvas, tab)
        tab_label = QLabel(label)
        tab_label.setMaximumHeight(20)

        layout = QVBoxLayout()
        layout.addWidget(tab_label)
        layout.addWidget(canvas)
        layout.addWidget(toolbar)
        tab.setLayout(layout)
        self.add_tab(tab, label)
        self._figures[key] = fig
        return fig
开发者ID:CJ-Wright,项目名称:bluesky-browser,代码行数:20,代码来源:figures.py

示例6: SensorWidget

# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setParent [as 别名]
class SensorWidget():
    # ToDo: Add signal to this object and emit value each time new value
    # is taken from queue
    def __init__(self, parent=None):
        self.figure, self.axes = plt.subplots()
        self.x_axis = []
        self.y_values = []
        self.sensor_plot_queue = Queue(maxsize=N_POINTS_ON_PLOT)

        self.compute_initial_figure()
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setParent(parent)

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.update_figure)
        self.timer.start(50)

    def compute_initial_figure(self):
        self.axes.plot(self.y_values)

    def feed_value(self, value):
        self.sensor_plot_queue.put(value)

    def update_figure(self):
        self.axes.cla()
        # ToDo: Need to add lock here and iterate through all elements
        if not self.sensor_plot_queue.empty():
            self.y_values.append(self.sensor_plot_queue.get())
        if len(self.y_values) > N_POINTS_ON_PLOT:
            self.y_values.pop(0)
            self.x_axis = [x + 1 for x in self.x_axis]
        else:
            self.axes.set_xlim(0, N_POINTS_ON_PLOT)
            while len(self.x_axis) < len(self.y_values):
                self.x_axis.append(len(self.y_values))
        self.axes.plot(self.x_axis, self.y_values, ".")
        self.axes.plot(self.x_axis, self.y_values, "-")
        logging.debug("Drawing new plot")
        self.canvas.draw()
开发者ID:Qrlet,项目名称:Power_Inverter,代码行数:41,代码来源:gui.py

示例7: FigureCanvas

# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setParent [as 别名]
class FigureCanvas(QtGui.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.fig = Figure()
        self.axes = self.fig.add_subplot(111)
        self.canvas = FigureCanvasQTAgg(self.fig)
        self.canvas.setParent(self)
        self.toolbar = NavigationToolbar2QT(self.canvas, self)

        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        self.setLayout(layout)

        self.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        self.updateGeometry()

    def contextMenuEvent(self, event):
        menu = QtGui.QMenu(self)
        clearAction = menu.addAction("Clear content")
        action = menu.exec_(self.mapToGlobal(event.pos()))
        if action == clearAction:
            self.axes.cla()
开发者ID:jaj42,项目名称:dyngraph,代码行数:25,代码来源:debug.py

示例8: MplGraphQt5Widget

# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setParent [as 别名]
class MplGraphQt5Widget(QWidget):
    def __init__(self, parent=None):
        super(MplGraphQt5Widget, self).__init__(parent)

        self.width = 3
        self.height = 3
        self.dpi = 100

        self._dataY = np.array([])
        self._dataX = np.array([])

        self._spCols = 1
        self._spRows = 1
        self.all_sp_axes = []
        self.fig = Figure(figsize=(self.width, self.height), dpi=self.dpi)
        self.all_sp_axes.append(self.fig.add_subplot(self._spCols, self._spRows, 1))
        self.fig.set_frameon(False)
        self.fig.set_tight_layout(True)

        self.canvas = Canvas(self.fig)

        self._navBarOn = False
        self.mpl_toolbar = NavigationToolbar(self.canvas, parent)
        self.mpl_toolbar.dynamic_update()

        self.canvas.mpl_connect('key_press_event', self.on_key_press)
        self.canvas.mpl_connect('button_press_event', self.on_button_press)
        self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
        self.canvas.setFocusPolicy(Qt.ClickFocus)
        self.canvas.setFocus()

        self.canvas.setParent(parent)
        self.canvas.clearMask()
        self.canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.canvas.updateGeometry()

        vbox = QVBoxLayout()
        vbox.addWidget(self.canvas)
        vbox.addWidget(self.mpl_toolbar)
        if not self._navBarOn:
            self.mpl_toolbar.hide()
        self.setLayout(vbox)



    def get_icon(name):
        """Return Matplotlib icon *name*"""
        return QIcon(osp.join(rcParams['datapath'], 'images', name))


    key_pressed = pyqtSignal(object, name='keyPressed')

    def on_key_press(self, event):
        self.key_pressed.emit(event)
        key_press_handler(event, self.canvas, self.mpl_toolbar)

    button_pressed = pyqtSignal(object, name='buttonPressed')

    def on_button_press(self, event):
        self.button_pressed.emit(event)
        key_press_handler(event, self.canvas, self.mpl_toolbar)

    mouse_move = pyqtSignal(object, name='mouseMoved')

    def on_mouse_move(self, event):
        self.mouse_move.emit(event)
        key_press_handler(event, self.canvas, self.mpl_toolbar)


    def generateNewAxes(self):
        for ax in self.all_sp_axes:
            self.fig.delaxes(ax)
        self.all_sp_axes = []
        numOfAxes = (self._spRows*self._spCols)+1
        for i in np.arange(1,numOfAxes):
            self.all_sp_axes.append(self.fig.add_subplot(self._spRows, self._spCols, i))
        self.canvas.setGeometry(100, 100, 300, 300)  #Used to update the new number of axes
        self.canvas.updateGeometry()  #This will bring the size of the canvas back to the original (defined by the vbox)

    spRowsChanged = pyqtSignal(int)

    def getspRows(self):
        return self._spRows

    @pyqtSlot(int)
    def setspRows(self, spRows):
        self._spRows = spRows
        self.generateNewAxes()
        self.spRowsChanged.emit(spRows)

    def resetspRows(self):
        self.setspRows(1)

    spRows = pyqtProperty(int, getspRows, setspRows, resetspRows)

    spColsChanged = pyqtSignal(int)

    def getspCols(self):
        return self._spCols

#.........这里部分代码省略.........
开发者ID:georgedimitriadis,项目名称:themeaningofbrain,代码行数:103,代码来源:mplgraphqt5widget.py

示例9: MplWidget

# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setParent [as 别名]
class MplWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)

        self.fig = Figure()
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)
        self.canvas.setFocus()
        self.canvas.setParent(self)
        self.canvas.mpl_connect('scroll_event', self.onWheel)
        self.canvas.mpl_connect('button_press_event', self.start_pan)
        self.canvas.mpl_connect('button_release_event', self.pan)
        self.canvas.mpl_connect('motion_notify_event', self.pan_motion)

        self.axes = self.fig.add_subplot(111)
        self.fig.tight_layout()

        self.dragx = None
        self.dragy = None
        # self.mpl_toolbar = NavigationToolbar(self.canvas, self)

        vbox = QtWidgets.QVBoxLayout()
        vbox.addWidget(self.canvas)
        # vbox.addWidget(self.mpl_toolbar)
        self.setLayout(vbox)

    def start_pan(self, event):
        if event.button == 3:
            self.dragx, self.dragy = event.xdata, event.ydata

    def do_pan(self, xdata, ydata):
        diffx, diffy = self.dragx - xdata, self.dragy - ydata
        x1, x2 = self.axes.get_xlim()
        y1, y2 = self.axes.get_ylim()
        self.axes.set_xlim(x1 + diffx, x2 + diffx)
        self.axes.set_ylim(y1 + diffy, y2 + diffy)
        self.canvas.draw_idle()

    def stop_pan(self):
        self.dragx, self.dragy = None, None

    def pan(self, event):
        if event.button == 3:
            if event.inaxes is not None and \
                        self.dragx is not None and self.dragy is not None and \
                        event.xdata is not None and event.ydata is not None:
                self.do_pan(event.xdata, event.ydata)
            self.stop_pan()

    def pan_motion(self, event):
        if event.inaxes is not None and \
                        self.dragx is not None and self.dragy is not None and \
                        event.xdata is not None and event.ydata is not None:
            self.do_pan(event.xdata, event.ydata)

    def _rescale(self, lo, hi, step, pt=None, bal=None, scale='linear'):
        """
        Rescale (lo,hi) by step, returning the new (lo,hi)
        The scaling is centered on pt, with positive values of step
        driving lo/hi away from pt and negative values pulling them in.
        If bal is given instead of point, it is already in [0,1] coordinates.

        This is a helper function for step-based zooming.
        """
        # Convert values into the correct scale for a linear transformation
        # TODO: use proper scale transformers
        if scale == 'log':
            lo, hi = math.log10(lo), math.log10(hi)
            if pt is not None: pt = math.log10(pt)

        # Compute delta from axis range * %, or 1-% if percent is negative
        if step > 0:
            delta = float(hi - lo) * step / 100
        else:
            delta = float(hi - lo) * step / (100 - step)

        # Add scale factor proportionally to the lo and hi values, preserving the
        # point under the mouse
        if bal is None:
            bal = float(pt - lo) / (hi - lo)
        lo -= bal * delta
        hi += (1 - bal) * delta

        # Convert transformed values back to the original scale
        if scale == 'log':
            lo, hi = math.pow(10., lo), math.pow(10., hi)

        return (lo, hi)

    def onWheel(self, event):
        """
        Process mouse wheel as zoom events
        """
        ax = event.inaxes

        # Older versions of matplotlib do not have event.step defined
        try:
            step = 20.0 * event.step
        except:
            if event.button == 'up':
#.........这里部分代码省略.........
开发者ID:nlw0,项目名称:safl,代码行数:103,代码来源:mplwidget.py

示例10: __init__

# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setParent [as 别名]
class FlyBallPlotterContinuous:
    def __init__(self, 
                 data_q, 
                 geometry_cummulative, 
                 geometry_polar_plot, 
                 central_widget, 
                 experiment_dir ):
        
        self.data_q = data_q
        self.experiment_dir = experiment_dir
        
        ##################################
        # Setup plot area for cummulative
        ##################################
        self.plot_area = QWidget( central_widget )    
        self.plot_area.setGeometry( geometry_cummulative )
        w = geometry_cummulative.width()
        h = geometry_cummulative.height()
        self.dpi = 80
        
        w_inch = math.ceil(float(w) / float(self.dpi)) 
        h_inch = math.ceil(float(h) / float(self.dpi))

        # print "ball_tracker: w_inch, h_inch: ( %f %f )" % ( w_inch, h_inch )
        # print "ball_tracker: w, h: ( %f %f )" % ( w, h )

        self.fig = Figure( figsize=(4, 4), dpi=self.dpi, facecolor="w" )        
        self.canvas = FigureCanvas( self.fig )
        self.canvas.setParent( self.plot_area )

        self.axes = self.fig.add_subplot( 111 )
        ##################################



                
        ##################################
        # Setup plot area for polar plot 1
        ##################################
        matplotlib.rc('grid', color='#316931', linewidth=1, linestyle='-')
        matplotlib.rc('xtick', labelsize=10)
        matplotlib.rc('ytick', labelsize=10)

        self.plot_area_polar = QWidget( central_widget )    
        self.plot_area_polar.setGeometry( geometry_polar_plot )
        w = geometry_polar_plot.width()
        h = geometry_polar_plot.height()
        self.dpi = 80
        
        w_inch = math.ceil(float(w) / float(self.dpi)) 
        h_inch = math.ceil(float(h) / float(self.dpi))

        # print "ball_tracker: w_inch, h_inch: ( %f %f )" % ( w_inch, h_inch )
        # print "ball_tracker: w, h: ( %f %f )" % ( w, h )

        self.fig_polar = Figure( figsize=(3, 4), dpi=self.dpi, facecolor="w" )        
        self.canvas_polar = FigureCanvas( self.fig_polar )
        self.canvas_polar.setParent( self.plot_area_polar )

        self.fig_polar.subplots_adjust(hspace=0.3)
        self.polar_axes_1 = self.fig_polar.add_subplot( 211, polar=True, axisbg='#d5de9c')               
        self.polar_axes_2 = self.fig_polar.add_subplot( 212, polar=True, axisbg='#d5de9c')
        ##################################

        # Setup update timer
        self.update_freq = 0.5
        self.timer = QTimer()
        self.timer.timeout.connect( self.updatePlot )
        self.timer.start( 1000.0 / self.update_freq )

        # 
        self.cur_traj_x = 0
        self.cur_traj_y = 0        

        self.t_all = np.zeros(0)
        self.dx_all = np.zeros(0)
        self.dy_all = np.zeros(0)
        self.FORMAT = '%Y_%m%d_%H%M%S'
        self.RAWDATA_FLUSH_THRESHOLD = 100000
        self.rmax = 2000

        self.dir_cumm_x = 0.0
        self.dir_cumm_y = 0.0        
        self.vel_cumm_sum_x = 0.0
        self.vel_cumm_sum_y = 0.0
        self.vel_cumm_count = 0

        self.NUM_UPDATES_TO_TRACK = 50
        self.start_time = 0.0
        self.dir_win_x = 0.0
        self.dir_win_y = 0.0        
        self.vel_win_sum_x = 0.0
        self.vel_win_sum_y = 0.0
        self.vel_win_count = 0
        self.update_count = 0

        self.f_on = Event()
        self.f_on.set()

    def save_figs(self):
#.........这里部分代码省略.........
开发者ID:SashaRayshubskiy,项目名称:fly_tracker,代码行数:103,代码来源:fly_tracker_ball_tracker.py

示例11: PopUp

# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setParent [as 别名]
class PopUp(QtWidgets.QMainWindow):
    def __init__(self, parent=None,plotFunc=None,title='', showMe=True):
        self.parent = parent
        if self.parent == None:
            self.app = QtWidgets.QApplication([])  
        super(PopUp,self).__init__(parent)
        self.setWindowTitle(title)
        self.plotFunc = plotFunc
        self.create_main_frame(title)
        self.create_status_bar()
        if plotFunc != None:
            #plotFunc(fig=self.fig,axes=self.axes)
            plotFunc(self)
        if showMe == True:
            self.show()

    def draw(self):
        self.fig.canvas.draw()

    def create_main_frame(self,title):
        self.main_frame = QtWidgets.QWidget()
      # Create the mpl Figure and FigCanvas objects. 
        self.dpi = 100
        self.fig = Figure((5, 5), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)
        self.axes = self.fig.add_subplot(111)
        #self.axes.set_title(title)

        # Create the navigation toolbar, tied to the canvas
        vbox = QtWidgets.QVBoxLayout()
        vbox.addWidget(self.canvas)
        self.main_frame.setLayout(vbox)
        self.setCentralWidget(self.main_frame)

    def create_status_bar(self):
        self.status_text = QtWidgets.QLabel("")
        self.statusBar().addWidget(self.status_text, 1)


    def plotArray(self,image,normNSigma=3,title='',showColorBar=True,**kwargs):
        self.image = image
        if not 'vmax' in kwargs:
            goodImage = image[np.isfinite(image)]
            kwargs['vmax'] = np.mean(goodImage)+normNSigma*np.std(goodImage)
        if not 'cmap' in kwargs:
            defaultCmap=matplotlib.cm.gnuplot2
            defaultCmap.set_bad('0.15')
            kwargs['cmap'] = defaultCmap
        if not 'origin' in kwargs:
            kwargs['origin'] = 'lower'

        if 'button_press_event' in kwargs:
            cid = self.fig.canvas.mpl_connect('button_press_event',partial(kwargs.pop('button_press_event'),self))
            
        self.handleMatshow = self.axes.matshow(image,**kwargs)
        if showColorBar:
            self.fig.cbar = self.fig.colorbar(self.handleMatshow)
            cid = self.fig.canvas.mpl_connect('scroll_event', self.onscroll_cbar)
            cid = self.fig.canvas.mpl_connect('button_press_event', self.onclick_cbar)
        self.axes.set_title(title)
        cid = self.fig.canvas.mpl_connect('motion_notify_event', self.hoverCanvas)



        self.draw()

    def show(self):
        super(PopUp,self).show()
        if self.parent == None:
            self.app.exec_()

    def hoverCanvas(self,event):
        if event.inaxes is self.axes:
            col = int(round(event.xdata))
            row = int(round(event.ydata))
            if row < np.shape(self.image)[0] and col < np.shape(self.image)[1]:
                self.status_text.setText('({:d},{:d}) {}'.format(col,row,self.image[row,col]))
            

    def create_status_bar(self):
        self.status_text = QtWidgets.QLabel("Awaiting orders.")
        self.statusBar().addWidget(self.status_text, 1)
        
    def onscroll_cbar(self, event):
        if event.inaxes is self.fig.cbar.ax:
            increment=0.05
            currentClim = self.fig.cbar.mappable.get_clim()
            currentRange = currentClim[1]-currentClim[0]
            if event.button == 'up':
                if QtWidgets.QApplication.keyboardModifiers()==QtCore.Qt.ControlModifier:
                    newClim = (currentClim[0]+increment*currentRange,currentClim[1])
                elif QtWidgets.QApplication.keyboardModifiers()==QtCore.Qt.NoModifier:
                    newClim = (currentClim[0],currentClim[1]+increment*currentRange)
            if event.button == 'down':
                if QtWidgets.QApplication.keyboardModifiers()==QtCore.Qt.ControlModifier:
                    newClim = (currentClim[0]-increment*currentRange,currentClim[1])
                elif QtWidgets.QApplication.keyboardModifiers()==QtCore.Qt.NoModifier:
                    newClim = (currentClim[0],currentClim[1]-increment*currentRange)
            self.fig.cbar.mappable.set_clim(newClim)
#.........这里部分代码省略.........
开发者ID:srmeeker,项目名称:DarknessPipeline,代码行数:103,代码来源:arrayPopup.py

示例12: SCNR

# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setParent [as 别名]
class SCNR(QMainWindow):
    _window_title = "SCNR"
    _heartbeat = 100  # ms delay at which the plot/gui is refreshed, and the gamepad moves the stage

    def __init__(self, parent=None):
        super(SCNR, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.positions = np.matrix([ [0.0,0.0], [0.0,10.0], [10.0,0.0]])
        self.posModel = NumpyModel(self.positions)
        self.ui.posTable.setModel(self.posModel)
        self.vh = self.ui.posTable.verticalHeader()
        self.vh.setVisible(False)
        self.hh = self.ui.posTable.horizontalHeader()
        self.hh.setModel(self.posModel)
        self.hh.setVisible(True)

        self.settings = Settings()

        self.fig = Figure()
        self.axes = self.fig.add_subplot(111)
        self.axes.hold(False)
        #self.axes.autoscale(False)
        #self.axes.set_xlim([self.settings.min_wl, self.settings.max_wl])

        self.Canvas = FigureCanvas(self.fig)
        self.Canvas.setParent(self.ui.plotwidget)

        self.Canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.Canvas.updateGeometry()

        l = QVBoxLayout(self.ui.plotwidget)
        l.addWidget(self.Canvas)

        self.ui.status.setText("Ready")

        #self.savedir = "."+path.sep+"Spectra"+path.sep
        #self.path = "."+path.sep

        self.savedir = "./Spectra/"
        self.path = "./"

        self.x_step = .0
        self.y_step = .0
        self.step_distance = 1  # in um

        try:
            #pass
            self.stage = PIStage.E545(self.settings.stage_ip,self.settings.stage_port)
        except:
            self.stage = None
            self.stage = PIStage.Dummy()
            print("Could not initialize PIStage, using Dummy instead")

        self.spectrum = Spectrum(self.stage, self.settings, self.ui.status, self.ui.progressBar, self.enable_buttons,
                                 self.disable_buttons)  # logger class which coordinates the spectrometer and the stage

        self.spec = self.spectrum.get_spec()  # get an initial spectrum for display
        self._wl = self.spectrum.get_wl()  # get the wavelengths
        #self.update_plot(None)
        #self.spectrum.getspecthread.dynamicSpecSignal.connect(self.update_plot)
        self.spectrum.specSignal.connect(self.update_plot)
        self.spectrum.updatePositions.connect(self.update_positions)
        self.padthread = GamepadThread()
        self.padthread.BSignal.connect(self.on_search_clicked)
        self.padthread.XSignal.connect(self.on_addpos_clicked)
        self.padthread.YSignal.connect(self.on_stepup_clicked)
        self.padthread.ASignal.connect(self.on_stepdown_clicked)
        self.padthread.xaxisSignal.connect(self.on_xaxis)
        self.padthread.yaxisSignal.connect(self.on_yaxis)
        self.ax = 0.0
        self.ay = 0.0

        self.padthread.start()
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.check_pad_analog)
        self.timer.start(100)
        self.pad_active = True

        self.settings_dialog = dialogs.Settings_Dialog(self.settings)
        self.settings_dialog.updateSignal.connect(self.update_settings)
        self.update_settings()
        self.ui.label_stepsize.setText(str(self.settings.stepsize))


    def disable_buttons(self):
        self.ui.tabWidget.setDisabled(True)
        self.ui.stage_frame.setDisabled(True)
        self.ui.Button_searchmax.setDisabled(True)
        self.ui.Button_stepup.setDisabled(True)
        self.ui.Button_stepdown.setDisabled(True)
        self.ui.Button_stop.setDisabled(False)
        #self.pad_active = False


    def enable_buttons(self):
        self.ui.tabWidget.setDisabled(False)
        self.ui.stage_frame.setDisabled(False)
        self.ui.Button_searchmax.setDisabled(False)
#.........这里部分代码省略.........
开发者ID:sdickreuter,项目名称:lock-in-spectrum,代码行数:103,代码来源:SCNR.py

示例13: Window

# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setParent [as 别名]

#.........这里部分代码省略.........
                    self.structure.setAlignment(Qt.AlignCenter)
            except:
                self.molformulaLabel = QLabel("<b>Mol. Formula:</b> Unknown")
                self.molwtLabel = QLabel("<b>Mol. Weight:</b> Unknown")
                self.structure.setText("No Structure Available")
                self.structure.setAlignment(Qt.AlignCenter)

        else:
            self.smilesLabel = QLabel("<b>SMILES:</b> Unknown")
            self.molformulaLabel = QLabel("<b>Mol. Formula:</b> Unknown")
            self.molwtLabel = QLabel("<b>Mol. Weight:</b> Unknown")
            self.structure.setText("No Structure Available")
            self.structure.setAlignment(Qt.AlignCenter)

        self.editinfoButton = QPushButton('Edit Compound Info')
        self.editinfoButton.setToolTip("Opens a window to edit compound information") # TODO: Set tooltip
        self.restoreinfoButton = QPushButton('Restore Compound Info')
        self.restoreinfoButton.setToolTip("Resets compound information to original imported values") # TODO: Set tooltip
        self.savestructureButton = QPushButton('Save Structure Image')
        self.savestructureButton.setToolTip("Tooltip") # TODO: Set tooltip


    def initSpectrum(self):
        # Compound Spectrum Tab
        matplotlib.projections.register_projection(My_Axes)
        self.scale = 1.05
        self.show_ignored = True
        self.show_ignored_peaks = True
        self.compoundtab2 = QWidget()
        self.compoundtab2.setStyleSheet("QWidget{background-color: white;}")
        self.fig = plt.gcf()
        self.fig.patch.set_facecolor('white')
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        self.canvas.setFocusPolicy(Qt.StrongFocus)
        self.canvas.setFocus()
        self.canvas.setMinimumHeight(100)
        self.canvas.setMinimumWidth(100)
        self.mpl_toolbar = NavigationToolbar2(self.canvas, self)
        self.mpl_toolbar.hide()
        self.mpl_toolbar.pan()
        self.canvas.mpl_connect('scroll_event', self.zooming)
        ins = "Left-click+drag to pan x-axis / Right-click+drag to zoom x-axis / Scroll-wheel to change intensity scale"
        self.instructionLabel = QLabel(ins)
        self.instructionLabel.setStyleSheet('QLabel{qproperty-alignment: AlignCenter; font-size: 10px;}')
        self.showignoredregionsCheckBox = QCheckBox("Show Ignored Regions")
        self.showignoredregionsCheckBox.setToolTip("Shows the ranges set by the solvent/buffer ignore regions, if any.")
        self.showignoredregionsCheckBox.setLayoutDirection(Qt.RightToLeft)
        self.showignoredregionsCheckBox.setChecked(True)
        self.showignoredpeaksCheckBox = QCheckBox("Show Ignored Peaks")
        self.showignoredpeaksCheckBox.setToolTip("Shows any compound peaks that are in the solvent/buffer ignore regions, if any.\n"
                                                 "These peaks are ignored and are not evaluated during mixing.")
        self.showignoredpeaksCheckBox.setLayoutDirection(Qt.RightToLeft)
        self.showignoredpeaksCheckBox.setChecked(True)
        self.resetviewButton = QPushButton("Reset View")
        self.resetviewButton.setToolTip("Resets the spectrum to the default view.")
        self.savespectrumButton = QPushButton("Save Spectrum")
        self.savespectrumButton.setToolTip("Saves the image in the spectrum window.")

    def initPeaklistTable(self):
        # Compound Peaklist Tab
        self.compoundtab3 = QWidget()
        self.compoundtab3.setStyleSheet("QWidget{background-color: white;}")
        self.peakTable = QTableWidget(0, 4, self)
        # self.peakTable.setMinimumWidth(400)
        self.peakTable.setSelectionMode(QAbstractItemView.NoSelection)
开发者ID:JaimeStark,项目名称:NMRmix,代码行数:70,代码来源:compound_info.py

示例14: CoqTextgridView

# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setParent [as 别名]
class CoqTextgridView(QtWidgets.QWidget):
    def __init__(self, *args, **kwargs):
        super(CoqTextgridView, self).__init__(*args, **kwargs)
        self._dynamic_range = 50
        self._window_length = 0.005
        self._textgrid = None
        self._sound = None
        self._spectrogram = None
        self._drag = False
        self._start_pos = None

        self.scrollbar = QtWidgets.QScrollBar(QtCore.Qt.Horizontal)
        self.scrollbar.valueChanged.connect(self.change_position)

        self.figure = CoqFigure()
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setParent(self)
        self.canvas.mpl_connect('key_press_event', self.on_key_press)
        self.canvas.mpl_connect('button_release_event', self.on_button_release)
        self.canvas.mpl_connect('button_press_event', self.on_button_press)
        self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
        #self.toolbar = NavigationToolbar(self.canvas, self)
        #self.toolbar.press_zoom = types.MethodType(press_zoom, self.toolbar)

        self.canvas.setSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                  QtWidgets.QSizePolicy.Expanding)
        self.canvas.updateGeometry()

        gs = mpl.gridspec.GridSpec(3, 1, height_ratios=[2.5, 5, 2.5])
        self.ax_waveform = self.figure.add_subplot(gs[0],
                                                   projection="LockedAxes")
        self.ax_spectrogram = self.figure.add_subplot(gs[1],
                                                      sharex=self.ax_waveform,
                                                      projection="LockedAxes")
        self.ax_textgrid = self.figure.add_subplot(gs[2],
                                                   sharex=self.ax_waveform,
                                                   projection="LockedAxes")
        self.figure.subplots_adjust(hspace=0)

        # prepare axes
        self.ax_waveform.set_ylim([-1, 1])
        self.ax_waveform.set_ylabel("Amplitude")
        self.ax_waveform.get_xaxis().set_visible(False)
        self.ax_spectrogram.set_ylabel("Frequency (Hz)")
        self.ax_spectrogram.get_xaxis().set_visible(False)
        self.ax_textgrid.set_xlabel("Time (s)")
        self.ax_textgrid.xaxis.get_offset_text().set_visible(False)

        self.selector_waveform = SpanSelector(
            self.ax_waveform, self.on_select, 'horizontal', useblit=True,
            rectprops=dict(alpha=0.25, facecolor='red'), span_stays=False,
            button=1)
        self.selector_spectrogram = SpanSelector(
            self.ax_spectrogram, self.on_select, 'horizontal', useblit=True,
            rectprops=dict(alpha=0.25, facecolor='red'), span_stays=False,
            button=1)

        layout = QtWidgets.QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)

        self.setLayout(layout)
        #self.layout().addWidget(self.toolbar)
        self.layout().addWidget(self.canvas)
        self.layout().addWidget(self.scrollbar)

    def clear(self):
        #self.layout().removeWidget(self.toolbar)
        self.layout().removeWidget(self.canvas)
        #del self.toolbar
        del self.canvas
        del self.figure

    def on_key_press(self, *args, **kwargs):
        pass

    def on_button_press(self, event):
        print(event)
        if event.button == 1:
            if event.inaxes == self.ax_textgrid:
                print("clicked", event.xdata)
                tier = self._textgrid.get_tier_by_name(
                    self._textgrid.get_tier_names()[0])
                print(tier.intervals)
                print("nearest", tier.get_annotations_by_time(event.xdata))
                interval = tier.get_annotations_by_time(event.xdata)[0]
                self._sound.extract_sound(interval.start_time,
                                          interval.end_time).play()
        elif event.button == 3:
            QtCore.QCoreApplication.instance().setOverrideCursor(
                QtGui.QCursor(QtCore.Qt. SizeHorCursor))
            self._drag = True
            self._start_pos = event.xdata

    def on_mouse_move(self, event):
        if not event.button:
            return
        if self._drag and event.xdata:
            dist = self._start_pos - event.xdata
            trans = self.ax_textgrid.transAxes.transform([dist, 0])[0]
#.........这里部分代码省略.........
开发者ID:gkunter,项目名称:coquery,代码行数:103,代码来源:textgridview.py

示例15: Window

# 需要导入模块: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg import setParent [as 别名]
class Window(QDialog):
    def __init__(self, params_object, library_object, group, parent=None):
        QDialog.__init__(self, parent)
        self.params = params_object
        self.library = library_object
        self.group = group
        matplotlib.projections.register_projection(My_Axes)
        self.region_colors = {0:'gray', 1:'red', 2:'green', 3:'orange', 4:'teal', 5:'pink',
                              6:'cyan', 7:'magenta', 8:'gold'}
        if self.group == 'ALL':
            self.plural_group = "s"
        else:
            self.plural_group = ""
        self.setWindowTitle("NMRmix: Peaks Histogram for %s Group%s" % (self.group, self.plural_group))
        self.scale = 1.05
        self.setAttribute(Qt.WA_DeleteOnClose, True)
        self.createMainFrame()

    def createMainFrame(self):
        self.fig = plt.gcf()
        self.fig.patch.set_facecolor('white')
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        self.canvas.setFocusPolicy(Qt.StrongFocus)
        self.canvas.setFocus()
        self.canvas.setMinimumHeight(100)
        self.canvas.setMinimumWidth(100)

        self.mpl_toolbar = NavigationToolbar2(self.canvas, self)
        self.mpl_toolbar.hide()
        self.mpl_toolbar.pan()
        self.canvas.mpl_connect('scroll_event', self.zooming)
        ins = "Left-click+drag to pan x-axis / Right-click+drag to zoom x-axis"
        self.instructionLabel = QLabel(ins)
        self.instructionLabel.setStyleSheet('QLabel{qproperty-alignment: AlignCenter; font-size: 12px;}')

        self.showignoredregionsCheckBox = QCheckBox("Show Ignored Regions")
        self.showignoredregionsCheckBox.setChecked(True)
        self.showignoredregionsCheckBox.setToolTip("Tooltip") # TODO: Tooltip
        self.showignoredregionsCheckBox.stateChanged.connect(self.handleIgnored)
        self.closeButton = QPushButton("Close")
        self.closeButton.setStyleSheet("QPushButton{color: red; font-weight: bold;}")
        self.closeButton.clicked.connect(self.closeEvent)
        self.saveButton = QPushButton("Save")
        self.saveButton.setStyleSheet("QPushButton{color: green; font-weight: bold;}")
        self.saveButton.clicked.connect(self.saveResults)
        self.resetButton = QPushButton("Reset")
        self.resetButton.setStyleSheet("QPushButton{color: blue; font-weight: bold;}")
        self.resetButton.clicked.connect(self.resetGraph)
        self.calculateAllHistogram()
        self.calculateIntenseHistogram()
        self.drawIgnoredRegions()
        winLayout = QVBoxLayout(self)
        winLayout.addWidget(self.canvas)
        winLayout.addWidget(self.instructionLabel)
        winLayout.addWidget(self.showignoredregionsCheckBox)
        buttonLayout = QHBoxLayout()
        buttonLayout.addWidget(self.closeButton)
        buttonLayout.addWidget(self.resetButton)
        buttonLayout.addWidget(self.saveButton)
        winLayout.addLayout(buttonLayout)
        winLayout.setAlignment(self.showignoredregionsCheckBox, Qt.AlignCenter)
        self.fig.tight_layout(pad=3)
        self.canvas.draw()

    def calculateAllHistogram(self):
        self.ax1 = self.fig.add_subplot(211, projection="My_Axes")
        self.ax1.set_title("Peaks Histogram for %s Group%s" % (self.group, self.plural_group), fontweight='bold')
        self.ax1.set_xlabel("Chemical Shift (ppm)", fontweight='bold')
        self.ax1.set_ylabel("Number of Peaks", fontweight='bold')
        data = list(self.library.stats[self.group]['Peaklist'])
        y, binEdges = np.histogram(data, bins=np.arange(-1, 12, 0.02))
        bincenters = 0.5 * (binEdges[1:] + binEdges[:-1])
        self.ax1.set_xlim(self.params.shift_range[self.params.nuclei])
        self.upper_ylim_all = max(y)+(math.ceil(max(y)*0.05))
        self.ax1.set_ylim([0, self.upper_ylim_all])
        self.ax1.plot(bincenters, y, '-', color='blue')

    def calculateIntenseHistogram(self):
        self.ax2 = self.fig.add_subplot(212, sharex=self.ax1, projection="My_Axes")
        self.ax2.set_title("Intense Peaks Histogram for %s Group%s" % (self.group, self.plural_group),
                           fontweight='bold')
        self.ax2.set_xlabel("Chemical Shift (ppm)", fontweight='bold')
        self.ax2.set_ylabel("Number of Peaks", fontweight='bold')
        data = list(self.library.stats[self.group]['Intense Peaklist'])
        y, binEdges = np.histogram(data, bins=np.arange(-1, 12, 0.02))
        bincenters = 0.5 * (binEdges[1:] + binEdges[:-1])
        self.ax2.set_xlim([12, -1])
        self.upper_ylim_intense = max(y)+(math.ceil(max(y)*0.05))
        self.ax2.set_ylim([0, self.upper_ylim_intense])
        self.ax2.plot(bincenters, y, '-', color='purple')

    def resetGraph(self):
        self.mpl_toolbar.home()

    def drawIgnoredRegions(self):
        groups = ['ALL']
        if self.group != 'ALL':
            groups.append(self.group)
        for region in self.library.ignored_regions:
#.........这里部分代码省略.........
开发者ID:JaimeStark,项目名称:NMRmix,代码行数:103,代码来源:peak_histogram.py


注:本文中的matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg.setParent方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。