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


Python FigureCanvasQTAgg.draw_idle方法代码示例

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


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

示例1: GaitDiagramView

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

#.........这里部分代码省略.........

            self.axes.barh(bottom=contact_label, left=float(min_z), width=length, height=0.5,
                           align='center', color=settings.settings.matplotlib_color[contact_label])

        self.axes.set_xlim([0, self.model.measurement.number_of_frames])
        if na:
            if settings.__human__:
                self.axes.set_yticks(range(0, 2))
                self.axes.set_yticklabels(['Left', 'Right', 'NA'])
            else:
                self.axes.set_yticks(range(0, 5))
                self.axes.set_yticklabels(['Left Front', 'Left Hind', 'Right Front', 'Right Hind', 'NA'])
        else:

            if settings.__human__:
                self.axes.set_yticks(range(0, 2))
                self.axes.set_yticklabels(['Left', 'Right'])
            else:
                self.axes.set_yticks(range(0, 4))
                self.axes.set_yticklabels(['Left Front', 'Left Hind', 'Right Front', 'Right Hind'])
        self.axes.set_xlabel('Frames Since Beginning of Measurement')
        self.axes.yaxis.grid(True)
        self.axes.set_title('Periods of Contacts')

        self.vertical_line = self.axes.axvline(linewidth=4, color='r')
        self.vertical_line.set_xdata(self.frame)
        self.canvas.draw()

    def change_frame(self, frame):
        self.frame = frame
        if self.frame < self.length:
            self.update_entire_plate()
            self.vertical_line.set_xdata(self.frame)
            self.canvas.draw_idle()

    def clear_axes(self):
        self.axes.cla()
        self.canvas.draw()

    def clear_cached_values(self):
        self.clear_axes()
        self.clear_bounding_box()
        self.clear_gait_line()
        self.frame = -1
        self.data = np.zeros((64, 256))
        # Put the screen to black
        self.image.setPixmap(utility.get_qpixmap(self.data, self.degree, self.model.n_max, self.color_table))

    def clear_bounding_box(self):
        # Remove the old ones and redraw
        for box in self.bounding_boxes:
            self.scene.removeItem(box)
        self.bounding_boxes = []

    def clear_gait_line(self):
        # Remove the gait line
        for line in self.gait_lines:
            self.scene.removeItem(line)
        self.gait_lines = []

    def draw_bounding_box(self, contact, current_contact):
        if current_contact:
            current_contact = 0.5
            color = self.colors[-1]
        else:
            current_contact = 0
开发者ID:ivoflipse,项目名称:Pawlabeling,代码行数:70,代码来源:gaitdiagramwidget.py

示例2: ContactView

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

#.........这里部分代码省略.........
        self.main_layout.setStretchFactor(self.canvas, 3)
        height = settings.settings.contacts_widget_height()
        self.setMinimumHeight(height)
        self.setLayout(self.main_layout)

        pub.subscribe(self.clear_cached_values, "clear_cached_values")
        pub.subscribe(self.filter_outliers, "filter_outliers")
        pub.subscribe(self.update_contact, "put_contact")

    def filter_outliers(self):
        if self.parent.active:
            self.clear_cached_values()
            self.draw()

    def update_contact(self):
        if self.contact_label == self.model.contact.contact_label:
            if self.parent.active:
                self.draw()

    def draw(self):
        if not self.model.contacts:
            return

        self.clear_axes()
        interpolate_length = 100
        lengths = []

        force_over_time = []
        self.max_duration = 0
        self.max_force = 0

        for measurement_name, contacts in self.model.contacts.iteritems():
            for contact in contacts:
                # Skip contacts that have been filtered if the toggle is on
                if self.model.outlier_toggle:
                    if contact.filtered or contact.invalid:
                        continue

                force = np.pad(contact.force_over_time, 1, mode="constant", constant_values=0)
                if contact.contact_label == self.contact_label:
                    lengths.append(len(force))
                    interpolated_force = calculations.interpolate_time_series(force, interpolate_length)
                    force_over_time.append(interpolated_force)
                    time_line = calculations.interpolate_time_series(np.arange(np.max(len(force))),
                                                                     interpolate_length)
                    self.axes.plot(time_line, interpolated_force, alpha=0.5)

                if len(force) > self.max_duration:
                    self.max_duration = len(force)
                if np.max(force) > self.max_force:
                    self.max_force = np.max(force)

        # If there's a contact selected, plot that too
        if self.contact_label in self.model.selected_contacts:
            contact = self.model.selected_contacts[self.contact_label]
            force = np.pad(contact.force_over_time, 1, mode="constant", constant_values=0)
            interpolated_force = calculations.interpolate_time_series(force, interpolate_length)
            time_line = calculations.interpolate_time_series(np.arange(np.max(len(force))),
                                                             interpolate_length)
            self.axes.plot(time_line, interpolated_force, color="k", linewidth=4, alpha=0.75)


        # If this is empty, there were no contacts to plot
        if not force_over_time:
            return
        force_over_time = np.array(force_over_time)
        mean_length = np.mean(lengths)
        interpolated_time_line = calculations.interpolate_time_series(np.arange(int(mean_length)), interpolate_length)
        mean_force = np.mean(force_over_time, axis=0)
        std_force = np.std(force_over_time, axis=0)
        self.axes.plot(interpolated_time_line, mean_force, color="r", linewidth=3)
        self.axes.plot(interpolated_time_line, mean_force + std_force, color="r", linewidth=1)
        self.axes.fill_between(interpolated_time_line, mean_force - std_force, mean_force + std_force, facecolor="r",
                               alpha=0.5)
        self.axes.plot(interpolated_time_line, mean_force - std_force, color="r", linewidth=1)
        self.vertical_line = self.axes.axvline(linewidth=4, color='r')
        self.vertical_line.set_xdata(self.frame)
        self.axes.set_xlim([0, self.model.max_length + 2])  # +2 because we padded the array
        if self.model.outlier_toggle:
            self.axes.set_xlim([0, self.model.filtered_length + 2]) # 2 because of the padding
        self.axes.set_ylim([0, self.max_force * 1.1])
        self.canvas.draw()


    def change_frame(self, frame):
        self.frame = frame
        self.vertical_line.set_xdata(self.frame)
        #self.canvas.draw()
        self.canvas.draw_idle()

    def clear_axes(self):
        self.axes.cla()
        self.canvas.draw()

    def clear_cached_values(self):
        # Put the screen to black
        self.clear_axes()
        self.forces = None
        self.max_duration = None
        self.max_force = None
开发者ID:ivoflipse,项目名称:Pawlabeling,代码行数:104,代码来源:forceviewwidget.py

示例3: streamPick

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

#.........这里部分代码省略.........
                <h4>Plot Controls:</h4>
                <blockquote>
                Use mouse wheel to zoom in- and out. Middle mouse button moves
                plot along x-axis.<br>
                Hit <b>Ctrl</b> to manipulate a single plot.
                <br>
                </blockquote>
                <div>
                Programm stores filter parameters in <code>.pick_filter</code>
                and a backup of recent picks in
                <code>.picks-obspy.xml.bak</code>.<br><br>
                See <a href=http://www.github.org/miili/StreamPick>
                http://www.github.org/miili/StreamPick</a> and
                <a href=http://www.obspy.org>http://www.obspy.org</a>
                for further documentation.
                </div>
                """ % (
                    self._shortcuts['st_next'],
                    self._shortcuts['st_previous'],
                    self._shortcuts['filter_apply'],
                    self._shortcuts['pick_p'],
                    self._shortcuts['pick_s'],
                    self._shortcuts['pick_custom'],
                    self._shortcuts['pick_remove'],
                    )
        QtGui.QMessageBox.about(self, 'About', msg)

    def _canvasDraw(self):
        '''
        Redraws the canvas and re-sets mouse focus
        '''
        for _i, _ax in enumerate(self.fig.get_axes()):
            _ax.set_xticklabels(_ax.get_xticks() * self._current_st[_i].stats.delta)
        self.canvas.draw_idle()
        self.canvas.flush_events()
        self.canvas.setFocus()
        return

    def closeEvent(self, evnt):
        '''
        This function is called upon closing the QtGui
        '''
        # Save Picks
        pickle.dump(self.bpfilter, open('.pick_filters', 'w'))
        # Save Catalog
        if len(self._picks) > 0:
            self._saveCatalog('.picks-obspy.xml.bak')
        if self.savefile is None and len(self._picks) > 0:
            ask = QtGui.QMessageBox.question(self, 'Save Picks?',
                'Do you want to save your picks?',
                QtGui.QMessageBox.Save |
                QtGui.QMessageBox.Discard |
                QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Save)
            if ask == QtGui.QMessageBox.Save:
                self._saveCatalog()
            elif ask == QtGui.QMessageBox.Cancel:
                evnt.ignore()
        print self._picks


    # Filter Dialog
    class defFilter(QtGui.QDialog):
        def __init__(self, parent=None, filtervalues=None):
            '''
            Bandpass filter dialog... Qt layout and stuff
            '''
开发者ID:d-chambers,项目名称:StreamPick,代码行数:70,代码来源:streamPick.py

示例4: guiapp

# 需要导入模块: from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg import draw_idle [as 别名]
class guiapp(QtGui.QMainWindow, cursortest.Ui_Dialog):
    def __init__(self):
        super(self.__class__, self).__init__()

        self.setupUi(self)

        self.setupfigure()

        self.populateplt()

        self.addcursor()

        self.visible = True
        self.horizOn = True
        self.vertOn = True
        self.useblit = True
        self.background = None
        self.needclear = False

        self.canvas.setVisible(True)
        cid2 = self.canvas.mpl_connect('button_press_event', self.onmove)

    def setupfigure(self):
        self.fig = Figure()
        self.ax = self.fig.add_subplot(111)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.plt2d)
        self.ax.set_title('title')
        self.ax.set_xlabel('x label')
        self.ax.set_ylabel('y label')

        # navigation toolbar
        self.navbar = NavigationToolbar(self.canvas, self.plt2d, coordinates=True)

    def populateplt(self):
        data = np.random.rand(200,200)
        self.ax.imshow(data)

    def addcursor(self):
        self.cursor = Cursor(self.ax,horizOn=True,vertOn=True,useblit=False, color='black')

        self.lineh = self.ax.axhline(self.ax.get_ybound()[0], visible=False)
        self.linev = self.ax.axvline(self.ax.get_xbound()[0], visible=False)

    def onmove(self, event):
        'on mouse motion draw the cursor if visible'
        if event.inaxes != self.ax:
            self.linev.set_visible(False)
            self.lineh.set_visible(False)

            if self.needclear:
                self.canvas.draw()
                self.needclear = False
            return
        self.needclear = True
        if not self.visible: return
        self.linev.set_xdata((event.xdata, event.xdata))

        self.lineh.set_ydata((event.ydata, event.ydata))
        self.linev.set_visible(self.visible and self.vertOn)
        self.lineh.set_visible(self.visible and self.horizOn)

        self._update()
        print('%d, %d'%(self.linev.get_xydata()[0,0],self.lineh.get_xydata()[0,1]))


    def _update(self):

        if self.useblit:
            if self.background is not None:
                self.canvas.restore_region(self.background)
            self.ax.draw_artist(self.linev)
            self.ax.draw_artist(self.lineh)
            self.canvas.blit(self.ax.bbox)
        else:
            self.canvas.draw_idle()

        return False
开发者ID:ss3-ee,项目名称:pythonwork,代码行数:80,代码来源:main_cursortest.py

示例5: MainDialog

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

#.........这里部分代码省略.........
			elif '#rows:' in line: 
				self.numStrips = int(line.split(':')[1])
				print 'numStrips = ' + str(self.numStrips)

			elif '#columns:' in line: 
				self.numChannels = int(line.split(':')[1])
				print 'numChannels = ' + str(self.numChannels)

			else:
				# Read the data into an (numStrips)x(1) list
				dataList.append(line.split())
		dataFile.close() 

		# Call buildComboBox
		self.buildComboBoxList()

		# Convert dataList to global numpy array
		self.dataArray = np.asarray(dataList, int)

		# Integrate counts on each strip
		self.dataArrayTotalCounts = np.sum(self.dataArray, axis=1)
		print 'Total Number of Events = ' + str(np.sum(self.dataArrayTotalCounts))

	def buildComboBoxList(self):
		# Get the number of channels from the data file
		print 'building checkBoxes!'

		for i in range(0, self.numStrips):
			self.ui.comboBox.addItem('pixel_' + str(i))
			self.ui.comboBox_R1.addItem('pixel_' + str(i))
			self.ui.comboBox_R2.addItem('pixel_' + str(i))

	def plot(self):
		print 'plotButton pressed!'

		# Give the file and line number, but skip the header lines:
		# (#name: spect, #type: matrix, #rows: 384, #columns: 4096)
		stripNumber = int(self.ui.comboBox.currentText().split('_')[1])

		# create a sub plot
		self.figure1.add_subplot(111)

		# plot the data
		pyPlot.plot(self.dataArray[stripNumber], '-', label=str(stripNumber))
		#pyPlot.bar(np.arange(0, self.numChannels, 1), self.dataArray[stripNumber], width=1, color='none', alpha=0.1, label=str(stripNumber))

		# add labels
		pyPlot.title(self.dataType, fontsize=16)
		pyPlot.xlabel('Energy (ADC units)', fontsize=10)
		pyPlot.ylabel('Counts', fontsize=10)

		# add legend
		newLeg = pyPlot.legend(loc=1, frameon=True, fancybox=True, shadow=False, mode='none', title='Pixel' )
		
		# change the colour
		self.figure1.set_facecolor('white')

		# refresh the canvas
		self.canvas1.draw_idle()

	def plotRange(self):
		print 'plot all strips!'
		
		lowStrip = int(self.ui.comboBox_R1.currentText().split('_')[1])
		highStrip = int(self.ui.comboBox_R2.currentText().split('_')[1])

		for pixel in range(lowStrip, highStrip+1):
			tempIndex = self.ui.comboBox.findText('pixel_' + str(pixel))
			self.ui.comboBox.setCurrentIndex(tempIndex)
			self.plot()
			
	def clearPlot(self):
		print 'clear plot!'
		self.figure1.clf()
		self.canvas1.draw()

	def plotImage(self):
		print 'plot all strips with spectrum as a image!'			#TODO: Add Spectrum Colour Code 
		self.figure1.clf()

		# Plot as image, cmap(spectral, hot,), aspect(changes pixel ratio)   
		pyPlot.imshow(self.dataArray, cmap='hot', interpolation='nearest', aspect=3) # clim=(0, 500))
		pyPlot.title('Spectrum from each Strip')
		pyPlot.xlabel('Energy (ADC units)')
		pyPlot.ylabel('Strip Address')
		pyPlot.colorbar(spacing='uniform', fraction=0.01, pad=0.01, orientation='vertical')
		self.figure1.set_facecolor('white')
		self.canvas1.draw_idle()

	def plotStrips(self):
		print 'plot all strips with integrated counts'				
		self.figure1.clf()
		#pyPlot.fill(np.arange(0, self.numStrips, 1), self.dataArrayTotalCounts, 'yellow', alpha=0.5)
		pyPlot.bar(np.arange(0, self.numStrips, 1), self.dataArrayTotalCounts, width=1, color='blue', alpha=0.5)
		pyPlot.title('Total Counts per Strip')
		pyPlot.xlabel('Strip Address')
		pyPlot.ylabel('Counts')
		pyPlot.grid(True)
		self.figure1.set_facecolor('white')
		self.canvas1.draw_idle()
开发者ID:rcjwoods,项目名称:GSD,代码行数:104,代码来源:qtGSD_GUI.py

示例6: DiagramView

# 需要导入模块: from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg import draw_idle [as 别名]
class DiagramView(QtGui.QWidget):
    def __init__(self, parent, label):
        super(DiagramView, self).__init__(parent)
        self.label = QtGui.QLabel(label)
        self.parent = parent
        self.model = model.model
        self.degree = settings.settings.interpolation_results()
        self.colors = settings.settings.colors
        self.image_color_table = utility.ImageColorTable()
        self.color_table = self.image_color_table.create_color_table()

        self.frame = -1
        self.length = 0
        self.ratio = 1

        self.dpi = 100
        # This figsize may not always work out!
        self.fig = Figure(dpi=self.dpi) # figsize=(10.0, 5.0)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        self.axes = self.fig.add_subplot(111)

        self.vertical_line = self.axes.axvline(linewidth=4, color='r')
        self.vertical_line.set_xdata(0)

        self.main_layout = QtGui.QVBoxLayout(self)
        self.main_layout.addWidget(self.label)
        self.main_layout.addWidget(self.canvas, stretch=3)
        self.setLayout(self.main_layout)

        pub.subscribe(self.draw, "put_measurement")
        pub.subscribe(self.draw, "update_current_contact")
        pub.subscribe(self.clear_cached_values, "clear_cached_values")

    def draw(self):
        self.clear_cached_values()
        self.update_gait_diagram()

    def update_gait_diagram(self):
        if not self.model.contacts:
            return

        self.clear_axes()
        na = False

        for contact in self.model.contacts[self.model.measurement_name]:
            min_z = contact.min_z
            length = contact.length

            contact_label = contact.contact_label
            if contact_label < 0:
                if settings.__human__:
                    contact_label = 2
                else:
                    contact_label = 4
                na = True

            self.axes.barh(bottom=contact_label, left=float(min_z), width=length, height=0.5,
                           align='center', color=settings.settings.matplotlib_color[contact_label])

        self.length = self.model.measurement.number_of_frames
        self.axes.set_xlim([0, self.length])
        if na:
            if settings.__human__:
                self.axes.set_yticks(range(0, 2))
                self.axes.set_yticklabels(['Left', 'Right', 'NA'])
            else:
                self.axes.set_yticks(range(0, 5))
                self.axes.set_yticklabels(['Left Front', 'Left Hind', 'Right Front', 'Right Hind', 'NA'])
        else:

            if settings.__human__:
                self.axes.set_yticks(range(0, 2))
                self.axes.set_yticklabels(['Left', 'Right'])
            else:
                self.axes.set_yticks(range(0, 4))
                self.axes.set_yticklabels(['Left Front', 'Left Hind', 'Right Front', 'Right Hind'])
        self.axes.set_xlabel('Frames Since Beginning of Measurement')
        self.axes.yaxis.grid(True)
        self.axes.set_title('Periods of Contacts')

        self.vertical_line = self.axes.axvline(linewidth=4, color='r')
        self.vertical_line.set_xdata(self.frame)
        self.canvas.draw()

    def change_frame(self, frame):
        self.frame = frame
        if self.frame < self.length:
            self.vertical_line.set_xdata(self.frame)
            self.canvas.draw_idle()

    def clear_axes(self):
        self.axes.cla()
        self.canvas.draw()

    def clear_cached_values(self):
        self.clear_axes()
        self.frame = -1
开发者ID:ivoflipse,项目名称:Pawlabeling,代码行数:100,代码来源:diagramwidget.py

示例7: __init__

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

#.........这里部分代码省略.........

    def connect(self, event_name, callback):
        """
        Attach an event handler to the canvas through the native GTK interface.

        :param event_name: Name of the event
        :type event_name: str
        :param callback: Function to call
        :type callback: function
        :return: Nothing
        """
        self.canvas.connect(event_name, callback)

    def clear(self):
        """
        Clears axes and figure.

        :return: None
        """

        # Clear
        self.axes.cla()
        try:
            self.figure.clf()
        except KeyError:
            FlatCAMApp.App.log.warning("KeyError in MPL figure.clf()")

        # Re-build
        self.figure.add_axes(self.axes)
        self.axes.set_aspect(1)
        self.axes.grid(True)

        # Re-draw
        self.canvas.draw_idle()

    def adjust_axes(self, xmin, ymin, xmax, ymax):
        """
        Adjusts all axes while maintaining the use of the whole canvas
        and an aspect ratio to 1:1 between x and y axes. The parameters are an original
        request that will be modified to fit these restrictions.

        :param xmin: Requested minimum value for the X axis.
        :type xmin: float
        :param ymin: Requested minimum value for the Y axis.
        :type ymin: float
        :param xmax: Requested maximum value for the X axis.
        :type xmax: float
        :param ymax: Requested maximum value for the Y axis.
        :type ymax: float
        :return: None
        """

        # FlatCAMApp.App.log.debug("PC.adjust_axes()")

        width = xmax - xmin
        height = ymax - ymin
        try:
            r = width / height
        except ZeroDivisionError:
            FlatCAMApp.App.log.error("Height is %f" % height)
            return
        canvas_w, canvas_h = self.canvas.get_width_height()
        canvas_r = float(canvas_w) / canvas_h
        x_ratio = float(self.x_margin) / canvas_w
        y_ratio = float(self.y_margin) / canvas_h
开发者ID:anwar-hegazy,项目名称:FlatCAM,代码行数:69,代码来源:PlotCanvas.py

示例8: streamPick

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

#.........这里部分代码省略.........
                <h4>Plot Controls:</h4>
                <blockquote>
                Use mouse wheel to zoom in- and out. Middle mouse button moves
                plot along x-axis.<br>
                Hit <b>Ctrl</b> to manipulate a single plot.
                <br>
                </blockquote>
                <div>
                Programm stores filter parameters in <code>.pick_filter</code>
                and a backup of recent picks in
                <code>.picks-obspy.xml.bak</code>.<br><br>
                See <a href=http://www.github.org/miili/StreamPick>
                http://www.github.org/miili/StreamPick</a> and
                <a href=http://www.obspy.org>http://www.obspy.org</a>
                for further documentation.
                </div>
                """ % (
            self._shortcuts["st_next"],
            self._shortcuts["st_previous"],
            self._shortcuts["filter_apply"],
            self._shortcuts["pick_p"],
            self._shortcuts["pick_s"],
            self._shortcuts["pick_custom"],
            self._shortcuts["pick_remove"],
        )
        QtGui.QMessageBox.about(self, "About", msg)

    def _canvasDraw(self):
        """
        Redraws the canvas and re-sets mouse focus
        """
        for _i, _ax in enumerate(self.fig.get_axes()):
            _ax.set_xticklabels(_ax.get_xticks() * self._current_st[_i].stats.delta)
        self.canvas.draw_idle()
        self.canvas.flush_events()
        self.canvas.setFocus()
        return

    def closeEvent(self, evnt):
        """
        This function is called upon closing the QtGui
        """
        # Save Picks
        pickle.dump(self.bpfilter, open(".pick_filters", "w"))
        # Save Catalog
        if len(self._picks) > 0:
            self._saveCatalog(".picks-obspy.xml.bak")
        if self.savefile is None and len(self._picks) > 0:
            ask = QtGui.QMessageBox.question(
                self,
                "Save Picks?",
                "Do you want to save your picks?",
                QtGui.QMessageBox.Save | QtGui.QMessageBox.Discard | QtGui.QMessageBox.Cancel,
                QtGui.QMessageBox.Save,
            )
            if ask == QtGui.QMessageBox.Save:
                self._saveCatalog()
            elif ask == QtGui.QMessageBox.Cancel:
                evnt.ignore()
        print self._picks

    # Filter Dialog
    class defFilter(QtGui.QDialog):
        def __init__(self, parent=None, filtervalues=None):
            """
            Bandpass filter dialog... Qt layout and stuff
开发者ID:calum-chamberlain,项目名称:StreamPick,代码行数:70,代码来源:streamPick.py

示例9: FilterDesignDialog

# 需要导入模块: from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg import draw_idle [as 别名]
class FilterDesignDialog(QtGui.QDialog):
    """A dialog to apply Takanami's AR picking method to a selected piece of a
    seismic signal.

    Attributes:
        document: Current opened document containing a seismic record.
        seismic_event: A seismic event to be refined by using Takanami method.
            If no event is provided, then a new seismic event will be created
            by using the estimated arrival time after clicking on 'Accept'
    """

    def __init__(self, stream, trace_list=None, parent=None):
        super(FilterDesignDialog, self).__init__(parent)

        # Calc max. frequency
        traces = stream.traces if not trace_list else trace_list
        self.max_freq = max([trace.fs for trace in traces])

        self._init_ui()
        self.load_settings()
        # Initial draw
        w, h_db, angles = self._retrieve_filter_plot_data()
        self._module_data = self.module_axes.plot(w, h_db, 'b')[0]
        self._phase_data = self.phase_axes.plot(w, angles, 'g')[0]
        self.module_axes.set_ylim([-60,10])
        self.phase_axes.set_ylim([min(angles), max(angles)])
        self.canvas.draw_idle()

        self.start_point_spinbox.valueChanged.connect(self.on_freq_min_changed)
        self.end_point_spinbox.valueChanged.connect(self.on_freq_max_changed)
        self.start_point_spinbox.valueChanged.connect(self._draw_filter_response)
        self.end_point_spinbox.valueChanged.connect(self._draw_filter_response)
        self.number_coefficient_spinbox.valueChanged.connect(self._draw_filter_response)
        self.zeroPhaseCheckBox.toggled.connect(self._draw_filter_response)
        self.button_box.accepted.connect(self.accept)
        self.button_box.rejected.connect(self.reject)
        self.button_box.clicked.connect(self.on_click)

    def _init_ui(self):
        self.setWindowTitle("Filter Design (Butterworth-Bandpass Filter)")
        self.fig, _ = plt.subplots(1, 1, sharex=True)
        # Set up filter axes
        self.module_axes = self.fig.axes[0]
        self.phase_axes = self.module_axes.twinx()
        self.module_axes.set_title('Digital filter frequency response (Butterworth-Bandpass filter)')
        self.module_axes.set_xlabel('Frequency [Hz]')
        self.module_axes.set_ylabel('Amplitude [dB]', color='b')
        self.module_axes.axis('tight')
        self.module_axes.grid(which='both', axis='both')
        self.phase_axes.set_ylabel('Angle (radians)', color='g')
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setMinimumSize(self.canvas.size())
        self.canvas.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Policy.Expanding,
                                                    QtGui.QSizePolicy.Policy.Expanding))
        self.toolBarNavigation = navigationtoolbar.NavigationToolBar(self.canvas, self)
        self.group_box = QtGui.QGroupBox(self)
        self.group_box2 = QtGui.QGroupBox(self)
        self.group_box3 = QtGui.QGroupBox(self)
        self.group_box4 = QtGui.QGroupBox(self)
        self.group_box.setTitle("")
        self.group_box2.setTitle("")
        self.group_box3.setTitle("Parameters")
        self.start_point_label = QtGui.QLabel("Lower cutoff frequency (Hz): ")
        self.start_point_label.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Policy.Maximum,
                                                               QtGui.QSizePolicy.Policy.Preferred))

        self.start_point_spinbox = QtGui.QDoubleSpinBox(self.group_box)
        self.start_point_spinbox.setMinimum(1.0)
        self.start_point_spinbox.setSingleStep(1.00)
        self.start_point_spinbox.setAccelerated(True)
        self.start_point_spinbox.setMaximum(self.max_freq * 0.5)
        self.end_point_label = QtGui.QLabel("Higher cutoff frequency (Hz):")
        self.end_point_label.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Policy.Maximum,
                                                               QtGui.QSizePolicy.Policy.Preferred))
        self.end_point_spinbox = QtGui.QDoubleSpinBox(self.group_box4)
        self.end_point_spinbox.setMinimum(1.0)
        self.end_point_spinbox.setSingleStep(1.00)
        self.end_point_spinbox.setAccelerated(True)
        self.end_point_spinbox.setMaximum(self.max_freq * 0.5)
        self.end_point_spinbox.setValue(5.0)
        #######################################################################

        self.number_coefficient_label = QtGui.QLabel("Order: ")
        self.number_coefficient_label2 = QtGui.QLabel("")
        self.number_coefficient_label.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Policy.Maximum,
                                                               QtGui.QSizePolicy.Policy.Preferred))
        self.number_coefficient_label2.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Policy.Maximum,
                                                               QtGui.QSizePolicy.Policy.Preferred))
        self.number_coefficient_spinbox = QtGui.QSpinBox(self.group_box3)
        self.number_coefficient_spinbox.adjustSize()
        self.number_coefficient_spinbox.setMinimum(1)
        self.number_coefficient_spinbox.setSingleStep(1)
        self.number_coefficient_spinbox.setAccelerated(True)
        self.zeroPhaseCheckBox = QtGui.QCheckBox("Zero phase filtering", self.group_box2)
        self.zeroPhaseCheckBox.setChecked(True)

        #######################################################################

        self.group_box_layout = QtGui.QHBoxLayout(self.group_box)
        self.group_box_layout.setContentsMargins(9, 9, 9, 9)
#.........这里部分代码省略.........
开发者ID:cageo,项目名称:Romero-2016,代码行数:103,代码来源:FilterDesing.py

示例10: ROISelect

# 需要导入模块: from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg import draw_idle [as 别名]
class ROISelect(QMdiSubWindow):
    ###########
    # Signals #
    ###########
    plotSignal = pyqtSignal()

    ########################
    # Initializing Methods #
    ########################
    def __init__(self, title, imgfile, control, parent=None):
        '''
        Initializes internal variables
        '''
        QMdiSubWindow.__init__(self, parent)
        self.setWindowTitle(title)
        self.imgfile = imgfile
        self.control = control
        self.xys = []
        self.ROI = np.zeros((600,800)).astype(np.bool)
        for i in range(800):
            for j in range(600):
                self.xys.append((i,j))
        self.create_main_frame()
        self.onDraw()

    def create_main_frame(self):
        '''
        Creates the main window
        '''
        # Widgets 
        self.main_frame = QWidget()
        self.fig = Figure()
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)
        self.axes = self.fig.add_subplot(111)
        self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)
        self.reset = QPushButton('&Reset')
        
        # Connections
        self.cid = self.canvas.mpl_connect('button_press_event', self.onpress)
        self.control.imageChanged.connect(self.onImageChanged)
        self.control.closeSignal.connect(self.close)
        self.connect(self.reset, SIGNAL('clicked()'), self.onReset)

        # Layouts
        vbox = QVBoxLayout()
        vbox.addWidget(self.canvas)
        vbox.addWidget(self.mpl_toolbar)
        vbox.addWidget(self.reset)

        self.main_frame.setLayout(vbox)
        self.setWidget(self.main_frame)

    #########
    # Slots #
    #########
    def onReset(self):
        self.ROI = np.zeros((600,800)).astype(np.bool)
        self.cid = self.canvas.mpl_connect('button_press_event', self.onpress)
        self.onDraw()

    def onDraw(self):
        self.axes.clear()
        img = Image.open(self.imgfile)
        img = np.asarray(img)
        self.axes.imshow(img)  
        self.axes.imshow(self.ROI, alpha=0.1, cmap='gray')
        self.plotSignal.emit()
        self.canvas.draw()
      
    def getROI(self, verts):
        ind = points_inside_poly(self.xys, verts)
        self.canvas.draw_idle()
        self.canvas.widgetlock.release(self.lasso)
        del self.lasso
        self.ROI = ind
        self.ROI = self.ROI.reshape((600,800), order='F')
        self.canvas.mpl_disconnect(self.cid)
        self.onDraw()

    def onpress(self, event):
        if self.canvas.widgetlock.locked(): return
        if event.inaxes is None: return
        self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.getROI)
        self.canvas.widgetlock(self.lasso)
        
    def onImageChanged(self, filename):
        '''
        Catches the signal from the ControlPanel that the current image has changed
        '''
        self.imgfile = str(filename)
        self.onDraw()
开发者ID:jjberry,项目名称:EchoTools,代码行数:94,代码来源:ROISelect.py

示例11: SignalViewerWidget

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

#.........这里部分代码省略.........
            self.minimap.playback_marker.set_position(position)

    def set_playback_marker_visible(self, show_marker):
        if self.playback_marker is not None:
            self.playback_marker.set_visible(show_marker)
            self.minimap.playback_marker.set_visible(show_marker)

    def on_event_right_clicked(self, event):
        self.last_right_clicked_event = event
        self.event_context_menu.exec_(QtGui.QCursor.pos())

    def apply_takanami_to_selected_event(self):
        takanamidialog.TakanamiDialog(self.document,
                                      seismic_event=self.last_right_clicked_event).exec_()

    def apply_takanami_to_selection(self):
        xleft, xright = self.get_selector_limits()
        takanamidialog.TakanamiDialog(self.document, xleft, xright).exec_()

    def create_event_on_selection(self):
        xleft, xright = self.get_selector_limits()
        xleft, xright = xleft * self.fs, xright * self.fs
        cf = self.cf[xleft:xright]
        if cf.size > 0:
            time = (xleft + np.argmax(cf))
        else:
            time = (xleft + ((xright - xleft) / 2.0))
        self.document.createEvent(time=time)

    def draw(self):
        if self.animated:
            self._draw_animate()
        else:
            self.canvas.draw_idle()

    def _draw_animate(self):
        self.canvas.restore_region(self.background)
        for artist in self._get_animated_artists():
            if artist.get_visible():
                ax = artist.get_axes()
                if ax is not None:
                    if artist.get_axes().get_visible():
                        self.fig.draw_artist(artist)
                else:
                    self.fig.draw_artist(artist)
        self.canvas.blit(self.fig.bbox)

    def _set_animated(self, value):
        if self.animated != value:
            self.animated = value
            for artist in self._get_animated_artists():
                artist.set_animated(value)
            if self.animated == True:
                images = []
                for ax in self.fig.axes:
                    images.extend(ax.images)
                for image in images:
                    image.set_visible(False)

                self.canvas.draw()
                self.background = self.canvas.copy_from_bbox(self.fig.bbox)

                for image in images:
                    image.set_visible(True)

    def _get_animated_artists(self):
开发者ID:cageo,项目名称:Romero-2016,代码行数:70,代码来源:svwidget.py

示例12: AcquirePlotWidget

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

#.........这里部分代码省略.........
        self.y1_line, = self.y1_axes.plot([float('nan')],'b-')
        self.y2_line, = self.y2_axes.plot([float('nan')], 'r--')
        self.canvas = FigureCanvas(self.figure)

        # Qt stuff
        self.YAxisComboBox = QComboBox()
        self.YAxisComboBox.addItems(['Raw Signal'])
        self.YAxisComboBox.currentIndexChanged.connect(self.update_axes)
        self.XAxisComboBox = QComboBox()
        self.XAxisComboBox.addItems(['Wavelength (nm)',
                                     'Energy (eV)',
                                     'Wavenumber (1/cm)'])
        self.XAxisComboBox.currentIndexChanged.connect(self.update_axes)
        self.YScaleComboBox = QComboBox()
        self.YScaleComboBox.addItems(['linear',
                                      'log'])
        self.YScaleComboBox.currentIndexChanged.connect(self.update_yscale)

        hbox = QHBoxLayout()
        hbox.addWidget(QLabel('X Axis:'))
        hbox.addWidget(self.XAxisComboBox)
        hbox.addWidget(QLabel('Y Axis:'))
        hbox.addWidget(self.YAxisComboBox)
        hbox.addWidget(QLabel('Y Scale:'))
        hbox.addWidget(self.YScaleComboBox)
        hbox.addStretch(1)

        layout = QVBoxLayout()
        layout.addLayout(hbox)
        layout.addWidget(self.canvas)
        layout.setContentsMargins(0, 0, 0, 0)

        self.setLayout(layout)

    @Slot(object)
    def add_data(self, scan):
        self.scan = scan
        if not self._has_sysresrem and self.scan.sysresrem:
            self._has_sysresrem = True
            self.YAxisComboBox.addItem('Sys. Res. Removed')
        elif self._has_sysresrem and not self.scan.sysresrem: 
            self._has_sysresrem = False
            i = self.YAxisComboBox.findText('Sys. Res. Removed')
            self.YAxisComboBox.removeItem(i)
        self.update_axes()

    @Slot()
    def update_axes(self):
        xaxis = self.XAxisComboBox.currentText()
        if not xaxis:
            self.XAxisComboBox.setCurrentIndex(0)
            return
        if 'nm' in xaxis:
            x = self.scan.nm
            self.y1_axes.set_xlabel(r'Wavelength (nm)')
        elif 'eV' in xaxis:
            x = [1239.842/nm for nm in self.scan.nm]
            self.y1_axes.set_xlabel(r'Energy (eV)')
        elif '1/cm' in xaxis:
            x = [1e7/nm for nm in self.scan.nm]
            self.y1_axes.set_xlabel(r'Wavenumber (cm$\mathrm{^{-1}}$)')
        else:
            raise RuntimeError('Unsupported X Axis: %s'%xaxis)
        yaxis = self.YAxisComboBox.currentText()
        if not yaxis:
            self.YAxisComboBox.setCurrentIndex(0)
            return
        if 'Raw' in yaxis:
            y = self.scan.R
            self.y1_axes.set_ylabel(r'Raw Signal (V$\mathrm{_{RMS}}$)')
        elif 'Sys. Res. Removed' == yaxis:
            y = self.scan.sysresrem
            self.y1_axes.set_ylabel(r'Sysrem Response Removed (arb. u.)')
        else:
            raise RuntimeError('Unsupported Y Axis: %s'%yaxis)
        self.y1_line.set_data(x, y)
        self.y2_line.set_data(x, self.scan.theta)
        self.update_figure()

    @Slot()
    def update_yscale(self):
        yscale = self.YScaleComboBox.currentText()
        if 'linear' in yscale:
            self.y1_axes.set_yscale('linear')
            self.y1_axes.yaxis.major.formatter.set_powerlimits((0,0))
        elif 'log' in yscale:
            try:
                self.y1_axes.set_yscale('log')
            except ValueError:
                self.y1_axes.set_yscale('linear')
                self.YScaleComboBox.setCurrentIndex(0)
        self.update_figure()

    @Slot()
    def update_figure(self):
        self.y1_axes.relim()
        self.y1_axes.autoscale_view()
        self.y2_axes.relim()
        self.y2_axes.autoscale_view()
        self.canvas.draw_idle()
开发者ID:scott-maddox,项目名称:photonacq,代码行数:104,代码来源:acquire_plot_widget.py


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