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


Python FigureCanvasQTAgg.copy_from_bbox方法代码示例

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


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

示例1: MatplotlibWidget

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

        self.figure = Figure()
        self.canvas = FigureCanvasQTAgg(self.figure)
        #: Initialize Plots
        self.axis1 = self.figure.add_subplot(211)
        self.axis2 = self.figure.add_subplot(212)
        self.axis1.set_autoscaley_on(False)  #: Disable Auto scale
        self.axis1.set_xlim([0, 2000])
        self.axis1.set_ylim([-1.5, 1.5])
        self.axis2.set_autoscaley_on(False)
        self.axis2.set_xlim([1, 60])
        self.axis2.set_ylim([0, 65000])
        self.axis1.set_xticks(np.arange(0, 2000, 100))
        self.axis1.set_yticks(np.arange(-1.5, 1.5, 0.3))
        self.axis1.grid(False)  #: Useless. True doesnt work either.
        #: Non dynamic parts are cached so that we can decrease the draw time
        self.background = self.canvas.copy_from_bbox(self.axis1.bbox)
        self.layoutVertical = QtGui.QVBoxLayout(self)
        self.layoutVertical.addWidget(self.canvas)
开发者ID:limlug,项目名称:pyecg,代码行数:24,代码来源:ecg.py

示例2: RTWindowWidget

# 需要导入模块: from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg import copy_from_bbox [as 别名]
class RTWindowWidget(QtGui.QWidget):
    """Matplotlib wxFrame with animation effect"""
    ### connects widgets and signals ###
    def __init__(self, parent = None):
        super(RTWindowWidget, self).__init__(parent)

        # Matplotlib Figure
        self.fig = Figure((6, 4), 100)
        # bind the Figure to the backend specific canvas
        self.canvas = FigureCanvas(self.fig)
        # add a subplot
        self.ax = self.fig.add_subplot(111)

        # limit the X and Y axes dimensions
        # we prefer 2 separate functions for clarity
        self.ax.set_ylim([0, 100])
        self.ax.set_xlim([0, POINTS])
        # but we want a "frozen" window (defined by y/xlim functions)
        self.ax.set_autoscale_on(False)

        # we do not want ticks on X axis
        self.ax.set_xticks([])
        # we want a tick every 10 point on Y (101 is to have 100 too)
        self.ax.set_yticks(range(0, 101, 10))
        # disable autoscale, since we don't want the Axes to adapt
        # draw a grid (it will be only for Y)
        self.ax.grid(True)

        # generates first "empty" plots
        self.user = [None] * POINTS
        self.nice = [None] * POINTS
        self.sys  = [None] * POINTS
        self.idle = [None] * POINTS

        self.l_user, = self.ax.plot(range(POINTS), self.user, label='User %')
        self.l_nice, = self.ax.plot(range(POINTS), self.nice, label='Nice %')
        self.l_sys,  = self.ax.plot(range(POINTS),  self.sys,  label='Sys %')
        self.l_idle, = self.ax.plot(range(POINTS), self.idle, label='Idle %')

        # add the legend
        self.ax.legend(loc='upper center',
                           ncol=4,
                           prop=font_manager.FontProperties(size=10))

        # force a draw on the canvas()
        # trick to show the grid and the legend
        self.canvas.draw()

        # save the clean background - everything but the line
        # is drawn and saved in the pixel buffer background
        self.bg = self.canvas.copy_from_bbox(self.ax.bbox)

        # take a snapshot of CPU usage, needed for the update algorithm
        self.before = self.prepare_cpu_usage()


        # timerCallback = lambda: self.onTimer()
        myTimer = QtCore.QTimer()
        myTimer.timeout.connect(self.onTimer)
        myTimer.start(1000) #once a sec
        # print 1
        self.canvas.show()


    def prepare_cpu_usage(self):
        """helper function to return CPU usage info"""

        # get the CPU times using psutil module
        t = p.cpu_times()

        # return only the values we're interested in
        if hasattr(t, 'nice'):
            return [t.user, t.nice, t.system, t.idle]
        else:
            # special case for Windows, without 'nice' value
            return [t.user, 0, t.system, t.idle]


    def get_cpu_usage(self):
        """Compute CPU usage comparing previous and current measurements"""

        # take the current CPU usage information
        now = self.prepare_cpu_usage()
        # compute deltas between current and previous measurements
        delta = [now[i]-self.before[i] for i in range(len(now))]
        # compute the total (needed for percentages calculation)
        total = sum(delta)
        # save the current measurement to before object
        self.before = now
        # return the percentage of CPU usage for our 4 categories
        return [(100.0*dt)/total for dt in delta]


    def onTimer(self):
        """callback function for timer events"""

        print 1
        # get the CPU usage information
        tmp = self.get_cpu_usage()

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

示例3: mpl_widget

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

#.........这里部分代码省略.........
        elif event.key == 'escape':
            self.clear_selection()


    def change_coordinate_formatter(self, ax, data2d,  bruteforce_flag=None, bruteforce_dims=None):
        ''' see http://stackoverflow.com/questions/14754931/matplotlib-values-under-cursor
        '''
        numrows, numcols = data2d.shape
        bruteforce_mode_on = False
        bruteforce_mode_on = (bruteforce_flag == '2DXY' and bruteforce_dims[-1] and bruteforce_dims[-2])


        def format_coord(x, y):
            col = int(x+0.5)
            row = int(y+0.5)

            if not bruteforce_mode_on:
                if col >= 0 and col < numcols and row >= 0 and row < numrows:
                    #z = data2d[row, col]
                    # sice we have artificially reversed y-coordinate axes, now reverse data!
                    # numrows-1, because if nrows=10 => row=[0:9]
                    z = data2d[numrows-1-row, col]
                    #return 'x=%1.1f y=%1.1f z=%1.6f' % (x, y, z)
                    return 'i=%d j=%d z=%.6f' % (col, row, z)
                else:
                    #return 'x=%1.4f, y=%1.4f' % (x, y)
                    return 'outside data area'

            elif bruteforce_flag == '2DXY' and bruteforce_dims[-1] and bruteforce_dims[-2]:
                '''
                our extend in X=[-0.5:numcols-0.5], Y=[-0.5:numrows-0.5], because col,row is cell center!
                '''
                if col >= 0 and col < numcols and row >= 0 and row < numrows:
                    #z = data2d[row, col]
                    # sice we have artificially reversed y-coordinate axes, now reverse data!
                    # numrows-1, because if nrows=10 => row=[0:9]
                    z = data2d[numrows-1-row, col]
                    real_x, real_y = self.get_real_xy(x, y, bruteforce_dims)

                    #return 'x=%1.1f y=%1.1f z=%1.6f' % (x, y, z)
                    #return 'i=%d j=%d z=%.3f x=%.4f y=%.4f' % (col, row, z, real_x, real_y)
                    return 'i=%d j=%d z=%.3f, %s=%.2f %s=%.2f' % (
                        col, row, z, bruteforce_dims[-1], real_x, bruteforce_dims[-2], real_y)
                else:
                    #return 'x=%1.4f, y=%1.4f' % (x, y)
                    return 'outside data area'
            else:
                raise ValueError('bruteforce_flag can be $None$ or $"2DXY"$. Passed %s' % bruteforce_flag)
        ax.format_coord = format_coord


    def allow_menu(self):
        allow = False
        #print "self.mainWidget.get_plotType():", self.mainWidget.get_plotType()
        #print "self.mainWidget.get_plotType_for_timeseries():", self.mainWidget.get_plotType_for_timeseries()
        if self.mainWidget.get_plotType() == "2D" and not self.mainWidget.get_plotType_for_timeseries() == "2DZT":
            allow = True
        return allow
    

    def get_real_xy(self, i, j, dimension_list):
        '''
        functions returns values of x,y based on passed indexes i, j

        '''
        if any(dimension_list[-2:-1]) is None:
            print 'Dimensions X,Y of current variable are not specified (variables that have same name as dimensions not found)'
            raise ValueError('Dimensions X,Y of current variable are not specified (variables that have same name as dimensions not found)')
        nc = self.mainWidget.get_selected_ncfile_instance()
        try:
            x_var = nc.variables[dimension_list[-1]]
            y_var = nc.variables[dimension_list[-2]]
            
        except:
            
            print ('Failed to load variables: {0}, {1}'.format(dimension_list[-1], dimension_list[-2]))
            raise ValueError('Failed to load variables: {0}, {1}'.format(dimension_list[-1], dimension_list[-2]))


        x_ratio = (x_var[-1]-x_var[0])/(len(x_var)-1)
        y_ratio = (y_var[-1]-y_var[0])/(len(y_var)-1)

        #x[i] = x_var[0]+x_ratio*i
        #y[j] = y_var[0]+y_ratio*j
        x = x_var[0] + x_ratio*i
        y = y_var[0] + y_ratio*j
        nc.close()
        return (x, y)

    def get_axes(self):
        return self.fig.get_axes()
    

    def fast_redraw(self, artist):
        background = [self.canvas.copy_from_bbox(self.get_axes()[0].bbox)]
        self.get_axes()[0].draw_artist(artist)
        self.canvas.restore_region(background)
        self.canvas.blit(self.get_axes()[0].bbox)
        self.canvas.update()
        self.canvas.flush_events()
开发者ID:cdd1969,项目名称:ncinfo,代码行数:104,代码来源:my_matplotlib_widget.py

示例4: StreamViewerWidget

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

#.........这里部分代码省略.........
                                self.selection_made.emit(True)
                            self._selected_traces.add(i)
                        else:
                            self.trace_selected.emit(i)
                            self.selection_made.emit(True)
                            self._selected_traces = {i}
                        break
            # if the user clicked out of any trace (and he's not using shift), then deselect all
            if not trace_selected and not self.shift_pressed:
                self._selected_traces = set()
                self.selection_made.emit(False)
            # Now update selection status on plots
            for i, plot in enumerate(self.trace_plots):
                plot.set_selected(i in self._selected_traces)
            self.draw()

    def _event_to_fig_coords(self, event):
        inv = self.fig.transFigure.inverted()
        return inv.transform((event.x, event.y))

    def set_stream(self, stream):
        self.stream = stream
        self._selected_traces = set()
        # Clear canvas
        for plot in self.trace_plots:
            plot.remove()
        self.trace_plots = []
        # Plot stream traces
        for i, trace in enumerate(self.stream.traces):
            self.trace_plots.append(TracePlot(self, trace, fig_nrows=len(stream), ax_pos=i + 1))
        # Draw canvas
        self.subplots_adjust()
        self.canvas.draw()
        self.background = self.canvas.copy_from_bbox(self.fig.bbox)
        self.draw()

    def refresh_stream_data(self):
        for plot in self.trace_plots:
            plot.update_data()

    def draw(self):
        self.canvas.draw()
        #self.draw_animate()

    def draw_animate(self):
        size = self.fig.bbox.width, self.fig.bbox.height
        if size != self.size:
            self.size = size
            self.canvas.draw()
            self.background = self.canvas.copy_from_bbox(self.fig.bbox)
        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 _get_animated_artists(self):
        artists = []
        for ax in self.fig.axes:
            artists.extend(ax.images)
            artists.extend(ax.lines)
开发者ID:cageo,项目名称:Romero-2016,代码行数:70,代码来源:tsvwidget.py

示例5: Plotter

# 需要导入模块: from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg import copy_from_bbox [as 别名]
class Plotter(QMainWindow):
    def __init__(self,groundtruthfile,n_particles,parent=None):
        # init parent class
        QMainWindow.__init__(self,parent)
        # load ground truth
        f = tables.openFile(groundtruthfile)
        self.true_traj = f.root.traj[:]
        self.true_map = f.root.staticMap[:]
        f.close()
        
        self.n_particles = n_particles
        self.create_widgets()
        self.logfiles = []
        self.frame = 0 
        self.data_loaded = False
        self.poses = []
        self.maps = []
        self.particle_poses = []
        self.weights = []

        
    def create_widgets(self):
        self.top_widget = QWidget()        
        
        self.fig = Figure(figsize=(12,6))
        self.canvas = FigureCanvas(self.fig)
        
        gs = GridSpec(2,4)        
        
        # main axes
        self.ax = self.fig.add_subplot(gs[:,0:2])
        self.ax.plot( self.true_traj[:,0], self.true_traj[:,1],'k' )
        self.ax.plot( self.true_map[:,0], self.true_map[:,1],'k*')
        
        # particle scatterplot axes
        self.ax_particles = self.fig.add_subplot(gs[0,2])
        self.ax_particles.set_xmargin(0.1)
        self.ax_particles.set_ymargin(0.1)
        
        # particle weights axes
        self.ax_weights = self.fig.add_subplot(gs[0,3])
            
        # cardinality axes
        self.ax_cn = self.fig.add_subplot(gs[1,2:])
        
        self.canvas.draw()
        self.background = self.canvas.copy_from_bbox(self.ax.bbox)
        self.background_particles = self.canvas.copy_from_bbox(self.ax_particles.bbox)
        
        # define animated artists
        init_x = [self.true_traj[0,0]]
        init_y = [self.true_traj[0,1]]
        self.est_pose, = self.ax.plot(init_x, init_y, 'rd', ms=8, mec='r', 
                                      mew=2,mfc='None',animated=True )
        self.est_traj, = self.ax.plot(init_x, init_y, 
                                      'r--',animated=True)   
        self.est_map = []
        self.zlines = []
        for i in xrange(100):
            l, = self.ax.plot([0],[0],color='b',linestyle='None',animated=True)
            self.est_map.append(l)
            l, = self.ax.plot([0],[0],color='g',linestyle='None',animated=True)
            self.zlines.append(l)
        self.particles, = self.ax.plot(init_x*ones(self.n_particles),
                                       init_y*ones(self.n_particles),color='b',
                                       animated=True,marker=',',ls='None')                                     
        self.particles2, = self.ax_particles.plot(init_x*ones(self.n_particles),
                                                  init_y*ones(self.n_particles),
                                                  color='b',animated=True,
                                                  marker='.',ls='None') 
                                                  
        self.load_button = QPushButton('Load Data')
        self.play_button = QPushButton('Play')
        self.play_button.setEnabled(False)
        self.play_button.setCheckable(True)
        self.timer = QTimer()
        self.timer.setInterval(100)
        
        # signals and slots
        self.connect(self.load_button,SIGNAL('clicked()'),self.load_callback)    
        self.connect(self.play_button,SIGNAL('clicked()'),self.play_callback)
        self.connect(self.timer,SIGNAL('timeout()'),self.timer_callback)
        
        hbox = QHBoxLayout()
        hbox.addWidget(self.load_button)
        hbox.addWidget(self.play_button)
        vbox = QVBoxLayout()
        vbox.addWidget(self.canvas)
        vbox.addLayout(hbox)
        self.top_widget.setLayout(vbox)                               
        self.setCentralWidget(self.top_widget)                                       
        
    def update_plot(self):
        if not self.data_loaded:
            return
            
        if self.frame >= self.n_steps:
            return
        
        # append the pose to the estimated trajectory
#.........这里部分代码省略.........
开发者ID:bwshan,项目名称:cuda-PHDSLAM,代码行数:103,代码来源:plot_phdslam.py

示例6: __init__

# 需要导入模块: from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg import copy_from_bbox [as 别名]
class PlotCanvas:
    """
    Class handling the plotting area in the application.
    """

    def __init__(self, container):
        """
        The constructor configures the Matplotlib figure that
        will contain all plots, creates the base axes and connects
        events to the plotting area.

        :param container: The parent container in which to draw plots.
        :rtype: PlotCanvas
        """
        # Options
        self.x_margin = 15  # pixels
        self.y_margin = 25  # Pixels

        # Parent container
        self.container = container

        # Plots go onto a single matplotlib.figure
        self.figure = Figure(dpi=50)  # TODO: dpi needed?
        self.figure.patch.set_visible(False)

        # These axes show the ticks and grid. No plotting done here.
        # New axes must have a label, otherwise mpl returns an existing one.
        self.axes = self.figure.add_axes([0.05, 0.05, 0.9, 0.9], label="base", alpha=0.0)
        self.axes.set_aspect(1)
        self.axes.grid(True)

        # The canvas is the top level container (Gtk.DrawingArea)
        self.canvas = FigureCanvas(self.figure)
        # self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)
        # self.canvas.setFocus()

        #self.canvas.set_hexpand(1)
        #self.canvas.set_vexpand(1)
        #self.canvas.set_can_focus(True)  # For key press

        # Attach to parent
        #self.container.attach(self.canvas, 0, 0, 600, 400)  # TODO: Height and width are num. columns??
        self.container.addWidget(self.canvas)  # Qt

        # Copy a bitmap of the canvas for quick animation.
        # Update every time the canvas is re-drawn.
        self.background = self.canvas.copy_from_bbox(self.axes.bbox)

        # Events
        self.canvas.mpl_connect('button_press_event', self.on_mouse_press)
        self.canvas.mpl_connect('button_release_event', self.on_mouse_release)
        self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
        #self.canvas.connect('configure-event', self.auto_adjust_axes)
        self.canvas.mpl_connect('resize_event', self.auto_adjust_axes)
        #self.canvas.add_events(Gdk.EventMask.SMOOTH_SCROLL_MASK)
        #self.canvas.connect("scroll-event", self.on_scroll)
        self.canvas.mpl_connect('scroll_event', self.on_scroll)
        self.canvas.mpl_connect('key_press_event', self.on_key_down)
        self.canvas.mpl_connect('key_release_event', self.on_key_up)
        self.canvas.mpl_connect('draw_event', self.on_draw)

        self.mouse = [0, 0]
        self.key = None

        self.pan_axes = []
        self.panning = False

    def on_key_down(self, event):
        """

        :param event:
        :return:
        """
        FlatCAMApp.App.log.debug('on_key_down(): ' + str(event.key))
        self.key = event.key

    def on_key_up(self, event):
        """

        :param event:
        :return:
        """
        self.key = None

    def mpl_connect(self, event_name, callback):
        """
        Attach an event handler to the canvas through the Matplotlib interface.

        :param event_name: Name of the event
        :type event_name: str
        :param callback: Function to call
        :type callback: func
        :return: Connection id
        :rtype: int
        """
        return self.canvas.mpl_connect(event_name, callback)

    def mpl_disconnect(self, cid):
        """
        Disconnect callback with the give id.
#.........这里部分代码省略.........
开发者ID:anwar-hegazy,项目名称:FlatCAM,代码行数:103,代码来源:PlotCanvas.py

示例7: Widget

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

        self._ind=None
        self.showVerts=True

        QVBoxLayout(self)

        self.figure=Figure()
        self.canvas=FigureCanvas(self.figure)
        self.canvas.setParent(self)

        codes, verts = zip(*pathdata)
        path = mpath.Path(verts, codes)
        self.patch = mpatches.PathPatch(path, facecolor='red', edgecolor='yellow', alpha=0.5)
        self.axes=self.figure.add_subplot(111)
        self.axes.add_patch(self.patch)
        self.patch.set_animated(True)

        x,y=zip(*path.vertices)
        self.line,=self.axes.plot(x, y, 'go-', animated=True)

        self.axes.grid()
        self.axes.set_xlim(-3,4)
        self.axes.set_ylim(-3,4)

        self.axes.set_title('spline paths')

        self.canvas.mpl_connect('draw_event', self.drawCallback)
        self.canvas.mpl_connect('button_press_event', self.buttonPressCallback)
        self.canvas.mpl_connect('button_release_event', self.buttonReleaseCallback)
        self.canvas.mpl_connect('motion_notify_event', self.motionNotifyCallback)

        self.layout().addWidget(self.canvas)

    # Callbacks
    def drawCallback(self, event):
        self.background = self.canvas.copy_from_bbox(self.axes.bbox)
        self.axes.draw_artist(self.patch)
        self.axes.draw_artist(self.line)
        self.canvas.blit(self.axes.bbox)

    def buttonPressCallback(self, event):
         if (not self.showVerts) or (event.inaxes==None) or (event.button!=1): return
         self._ind=self.getIndUnderPoint(event)

    def buttonReleaseCallback(self, event):
        if (not self.showVerts) or (event.button!=1): return
        self._ind=None

    def keyPressEvent(self, event):
        if event.key()==Qt.Key_T:
            self.showVerts=not self.showVerts
            self.line.set_visible(self.showVerts)
            if not self.showVerts: self._ind=None
            self.canvas.draw()
            event.accept()
        else: QWidget.keyPressEvent(self, event)     

    def motionNotifyCallback(self, event):
        if (not self.showVerts) or (self._ind==None) or (event.inaxes==None) or (event.button!=1): return

        x,y=event.xdata,event.ydata
        vertices=self.patch.get_path().vertices
        vertices[self._ind]=x,y
        self.line.set_data(zip(*vertices))

        self.canvas.restore_region(self.background)
        self.axes.draw_artist(self.patch)
        self.axes.draw_artist(self.line)
        self.canvas.blit(self.axes.bbox)

    # Other methods
    def getIndUnderPoint(self, event):
        xy=np.asarray(self.patch.get_path().vertices)
        xyt=self.patch.get_transform().transform(xy)
        xt,yt=xyt[:,0],xyt[:,1]
        d=np.sqrt((xt-event.x)**2 + (yt-event.y)**2)
        ind=d.argmin()

        if d[ind]>=epsilon: ind=None
        return ind
开发者ID:hftsai,项目名称:gulon-soft,代码行数:85,代码来源:mpl_path_editor_qt.py

示例8: InteractiveVelocityPlot

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

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

        # Set up grid layout:
        grid = QGridLayout()
        grid.setSpacing(10)

        # Add widgets:
        grid.addWidget(self.text_output, 1, 1, 4, 3)
        grid.addWidget(self.load_button, 1, 4)
        grid.addWidget(self.save_button, 2, 4)
        grid.addWidget(self.preview_button, 3, 4)
        grid.addWidget(self.clear_button, 4, 4)
        grid.addWidget(self.refresh_plot_button, 1, 5)
        grid.addWidget(self.plot_model_button, 2, 5)
        grid.addWidget(self.plot_all_models_button, 3, 5)
        grid.addWidget(self.clear_models_button, 4, 5)
        grid.addWidget(self.runvpfit_button, 1, 6)
        grid.addWidget(self.cos_fuv_checkbox, 2, 6)
        grid.addWidget(self.cos_nuv_checkbox, 3, 6)
        grid.addWidget(self.include_checkbox, 4, 6)
        grid.addWidget(self.set_resolution, 1, 7)
        grid.addWidget(self.help, 3, 7)
        grid.addWidget(self.quit, 4, 7)

        # Place plotting canvas above the options grid:
        vbox = QVBoxLayout()
        vbox.addWidget(self.canvas)
        vbox.addLayout(grid)

        # Set the layout to the host widget:
        self.main_frame.setLayout(vbox)

        # Store all static elements (can be very slow to re-draw these):
        self.canvas.draw()
        self.backgrounds = [self.canvas.copy_from_bbox(ax.bbox)
                            for ax in self.axes]

        # Plot the data:
        self.plot_data(wavelength, flux, error, continuum, redshift,
                       **self.options['DATA'])

        # Set the window title:
        self.window.setWindowTitle('vpguess z = {0:.3f}'.format(self.redshift))

        # Give keyboard focus to the figure:
        self.canvas.setFocusPolicy(Qt.StrongFocus)
        self.canvas.setFocus()

        # Variable defaults:
        self.cos_fuv = False
        self.cos_nuv = False
        self.include = False
        self.last_loaded = None
        self.resolution = None

        # Keypress variables:
        self.previous_keypress = None
        self.previous_wavelength = None

        # Set up the key-press events:
        self.canvas.mpl_connect('key_press_event', self.on_keypress)

        # Set the main frame as the central widget:
        self.window.setCentralWidget(self.main_frame)

        # Resize the window so it will display the canvas with the
        # requested size:
开发者ID:cwfinn,项目名称:igmtools,代码行数:70,代码来源:helpers.py

示例9: AnalysisEditor

# 需要导入模块: from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg import copy_from_bbox [as 别名]
class AnalysisEditor(QWidget):
    def __init__(self, ui):
        QWidget.__init__(self)
        self.ui = ui
        self.chooseAnalysis = QPushButton()
        self.chooseAnalysis.setText("Choose Analysis")
        self.chooseAnalysis.setFixedWidth(100)
        self.lineEdit = QLineEdit()
        self.chooseAnalysis.clicked.connect(self.selectAnalysis)
        self.analysisFig = plt.figure()
        self.analysisFig.patch.set_facecolor('white')
        self.analysisFig.clf()
        self.analysisCanvas = FigureCanvas(self.analysisFig)
        self.toolbar = NavigationToolbar(self.analysisCanvas, self)
        self.analysisOperationsLayout = self.createOperationsLayout()     
        self.analysisAx = self.analysisFig.add_subplot(1,1,1)
        #self.gridLayout.addLayout(analysisOperationsLayout,1,7)
    
    def initCanvas(self):
        self.lineEdit.clear()
        self.analysisAx.cla()
        self.analysisAx = self.analysisFig.add_subplot(1,1,1)  
        self.analysisCanvas.draw()    
        
    def analysisOptionHandler(self):
        sender = self.sender()
        if sender.isChecked():
            vec = sender.getVec()
            sender.line = self.plotAnalysis(vec)
            #sender.line, = self.analysisAx.plot(sender.getVec())
        else:
            sender.line.remove()
        self.analysisCanvas.draw()
    
    def prepareCheckBox(self, getVec, label):
        operationCheck = QCheckBox()
        operationCheck.setText(label)
        operationCheck.setFixedWidth(100)
        operationCheck.getVec = getVec
        operationCheck.clicked.connect(self.analysisOptionHandler) 
        return operationCheck
    
    def Original(self):
        self.analysisVec = self.original.vec
        return self.analysisVec 
    
    def Derivative(self):
        self.analysisVec = np.diff(self.analysisVec)
        return self.analysisVec
    
    def LPF(self):
        self.analysisVec =  ma.movingAverage(self.analysisVec, 30, 1.1)
        return self.analysisVec
    
    def cluster(self):
        pass
    
    def createOperationsLayout(self):
        analysisOptionsLayout = QVBoxLayout()
        self.original = self.prepareCheckBox(self.Original, 'Original') 
        analysisOptionsLayout.addWidget(self.original)
        analysisOptionsLayout.addWidget(self.prepareCheckBox(self.LPF, 'LPF'))
        analysisOptionsLayout.addWidget(self.prepareCheckBox(self.Derivative, 'Derivative'))
        analysisOptionsLayout.addWidget(self.prepareCheckBox(self.cluster, 'cluster'))
        return analysisOptionsLayout
        
    def selectAnalysis(self):
        dlg = QFileDialog()
        dlg.setDirectory('Laban/analysis')
        analysisFile= unicode(dlg.getOpenFileName(filter='*.py'))
        self.lineEdit.setText(analysisFile)
        if not os.path.isfile(analysisFile):
            return
        rel = os.path.relpath(analysisFile).split('.')[-2]
        rel = rel.replace('\\','.')#[1:]
        analayzer = importlib.import_module(rel)
        self.analysisVec = analayzer.analyze(self.ui.selectedFile)
        self.original.line = self.plotAnalysis(self.analysisVec)
        self.original.vec = self.analysisVec
        self.original.setChecked(True)
    
    def plotAnalysis(self, vec):
        max_height = np.max(vec)
        min_height = np.min(vec)
        ax = self.analysisAx
        ax.set_ylim(min_height, max_height)
        line, = ax.plot(vec)
        self.analysisCanvas.draw()
        return line
    
    def clearTimeMarker(self):
        self.syncSkeletonWithAnalysis = False
        self.analysisTimeLine.remove()
        self.analysisCanvas.draw()

    def initTimeMarker(self):
        ax = self.analysisAx
        self.analysisBackground = self.analysisCanvas.copy_from_bbox(ax.bbox)
        vec = self.analysisVec
        max_height = np.max(vec)
#.........这里部分代码省略.........
开发者ID:ranBernstein,项目名称:GaitKinect,代码行数:103,代码来源:analysisGUI.py

示例10: SignalViewerWidget

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

#.........这里部分代码省略.........
        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):
        artists = []
        for ax in self.fig.axes:
            artists.extend(ax.images)
            artists.extend(ax.lines)
            artists.append(ax.xaxis)
            artists.append(ax.yaxis)
            artists.extend(ax.patches)
            artists.extend(ax.spines.values())
        for artist in artists:
            yield artist

    def update_specgram_settings(self):
        # load specgram settings
        settings = QtCore.QSettings(_organization, _application_name)

        settings.beginGroup("specgram_settings")
        self.specgram_windowlen = int(settings.value('window_len', settingsdialog.SPECGRAM_WINDOW_LENGTHS[4]))
        self.specgram_noverlap = int(settings.value('noverlap', self.specgram_windowlen / 2))
        self.specgram_window = settings.value('window', plotting.SPECGRAM_WINDOWS[2])
        settings.endGroup()

        if self.data_loaded:
            # Plot espectrogram
            self.specgram_ax.images = []
            # Save x-axis limits
            limits = self.signal_ax.get_xlim()
            # Draw spectrogram
            plotting.plot_specgram(self.specgram_ax, self.signal, self.fs,
                                   nfft=self.specgram_windowlen,
                                   noverlap=self.specgram_noverlap,
                                   window=self.specgram_window)
            # Restore x-axis limits
            self.signal_ax.set_xlim(*limits)

    def paintEvent(self, paintEvent):
        super(SignalViewerWidget, self).paintEvent(paintEvent)

    def on_selector_right_clicked(self):
        xleft, xright = self.get_selector_limits()
        self.takanami_on_selection_action.setEnabled((xright - xleft) >=
                                                     (takanamidialog.MINIMUM_MARGIN_IN_SECS * 2))
        self.selection_context_menu.exec_(QtGui.QCursor.pos())
开发者ID:cageo,项目名称:Romero-2016,代码行数:104,代码来源:svwidget.py

示例11: MiniMap

# 需要导入模块: from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg import copy_from_bbox [as 别名]
class MiniMap(QtGui.QWidget):
    """Shows the entire signal and allows the user to navigate through it.

    Provides an scrollable selector over the entire signal.

    Attributes:
        xmin: Selector lower limit (measured in h-axis units).
        xmax: Selector upper limit (measured in h-axis units).
        step: Selector length (measured in h-axis units).
    """

    def __init__(self, parent, ax, record=None):
        super(MiniMap, self).__init__(parent)
        self.ax = ax

        self.xmin = 0.0
        self.xmax = 0.0
        self.step = 10.0
        self.xrange = np.array([])

        self.minimapFig = plt.figure()
        self.minimapFig.set_figheight(0.75)
        self.minimapFig.add_axes((0, 0, 1, 1))
        self.minimapCanvas = FigureCanvas(self.minimapFig)
        self.minimapCanvas.setFixedHeight(64)
        self.minimapSelector = self.minimapFig.axes[0].axvspan(0, self.step,
                                                               color='gray',
                                                               alpha=0.5,
                                                               animated=True)
        self.minimapSelection = self.minimapFig.axes[0].axvspan(0, self.step,
                                                                color='LightCoral',
                                                                alpha = 0.5,
                                                                animated=True)
        self.minimapSelection.set_visible(False)
        self.minimapBackground = []
        self.minimapSize = (self.minimapFig.bbox.width,
                            self.minimapFig.bbox.height)

        self.press_selector = None
        self.playback_marker = None
        self.minimapCanvas.mpl_connect('button_press_event', self.onpress)
        self.minimapCanvas.mpl_connect('button_release_event', self.onrelease)
        self.minimapCanvas.mpl_connect('motion_notify_event', self.onmove)

        # Animation related attrs.
        self.background = None
        self.animated = False

        # Set the layout
        self.layout = QtGui.QVBoxLayout(self)
        self.layout.addWidget(self.minimapCanvas)

        # Animation related attributes
        self.parentViewer = parent

        # Set Markers dict
        self.markers = {}

        self.record = None
        if record is not None:
            self.set_record(record)

    def set_record(self, record, step):
        self.record = record
        self.step = step
        self.xrange = np.linspace(0, len(self.record.signal) / self.record.fs,
                                  num=len(self.record.signal), endpoint=False)
        self.xmin = self.xrange[0]
        self.xmax = self.xrange[-1]
        self.markers = {}

        ax = self.minimapFig.axes[0]
        ax.lines = []
        formatter = FuncFormatter(lambda x, pos: str(datetime.timedelta(seconds=x)))
        ax.xaxis.set_major_formatter(formatter)
        ax.grid(True, which='both')
        # Set dataseries to plot
        xmin = self.xmin * self.record.fs
        xmax = self.xmax * self.record.fs
        pixel_width = np.ceil(self.minimapFig.get_figwidth() * self.minimapFig.get_dpi())
        x_data, y_data = plotting.reduce_data(self.xrange, self.record.signal, pixel_width, xmin, xmax)
        # self._plot_data.set_xdata(x_data)
        # self._plot_data.set_ydata(y_data)
        ax.plot(x_data, y_data, color='black', rasterized=True)
        ax.set_xlim(self.xmin, self.xmax)
        plotting.adjust_axes_height(ax)
        # Set the playback marker
        self.playback_marker = PlayBackMarker(self.minimapFig, self)
        self.playback_marker.markers[0].set_animated(True)
        # Draw canvas
        self.minimapCanvas.draw()
        self.minimapBackground = self.minimapCanvas.copy_from_bbox(self.minimapFig.bbox)
        self.draw_animate()

    def onpress(self, event):
        self.press_selector = event
        xdata = round(self.get_xdata(event), 2)
        xmin = round(xdata - (self.step / 2.0), 2)
        xmax = round(xdata + (self.step / 2.0), 2)
        self.parentViewer._set_animated(True)
#.........这里部分代码省略.........
开发者ID:cageo,项目名称:Romero-2016,代码行数:103,代码来源:svwidget.py

示例12: MainWindow

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

#.........这里部分代码省略.........
            self.device = device
            self.update_controls()
            self.validate()
        elif event.id == EVENT_ID_ONERROR:
            if self._ui.onDecodeErrorComboBox.currentIndex() == HALT:
                self.stop_recording()
                self.show_message("ERROR: %s" % event.data)
            else:
                if not self.in_error:
                    self.in_error = True
                    self.show_message("ERROR: %s" % event.data)
                else:
                    self.error_counts += 1
                    if self.error_counts > 5:
                        self.stop_recording()
                        self.show_message("Too many errors! %s" % event.data)
        elif event.id == EVENT_ID_ONDISCONNECT:
            self.recording_state = STATE_IDLE
            self.show_message("Device id %d disconnected." % device.get_id())
            self.shutdown()
        elif event.id == EVENT_ID_ONREADDATA:
            if analyzer is not None:
                if self.recording_state == STATE_WAITING_FOR_FRAME:
                    if self.device.get_analyzer().first_valid_frame_received():
                        self.show_message("Recording. Press 'Stop' to stop recording.")
                        self.recording_state = STATE_RECORDING
        elif event.id == EVENT_ID_ONANALYZERDATA:
            if self.recording_state == STATE_RECORDING and \
                    self.current_expected_pcm_clock_rate is not None:
                # Sanity check the sampling rate with the detected clock frequency
                if analyzer is not None:
                    clock_period_samples = self.device.get_analyzer().get_average_clock_period_in_samples()
                    meas_clock_freq = self.device.get_sampling_rate_hz() / clock_period_samples
                    if (1.2 * self.current_expected_pcm_clock_rate) <  meas_clock_freq or \
                        (0.8 * self.current_expected_pcm_clock_rate) > meas_clock_freq:
                        # The user's setup is probably wrong, so bail immediately
                        self.stop_recording()
                        self.show_message("Detected a PCM clock of ~%d Hz. Check your settings!" % meas_clock_freq)

            self.analyzed_data_received_event.emit(event.data)

    def update_plot(self, data):
        if self.plot_background is None:
            self.plot_background = self.plotCanvas.copy_from_bbox(self.fft_axis.bbox)

        channel = self._ui.comboPCMChannelToListenTo.currentIndex()
        channel_data = data[channel]
        numpoints = len(channel_data)
        if self.fft_line is None:
            self.fft_line, = self.fft_axis.plot(numpy.zeros(numpoints), animated=True)

        sampling_rate = int(self._ui.samplingRateLineEdit.text())
        freqs = numpy.fft.fftfreq(numpoints * 2, d=1.0 / float(sampling_rate))

        # Restore the clean slate background (this is the 'blit' method, which
        # is much faster to render)
        self.plotCanvas.restore_region(self.plot_background, bbox=self.fft_axis.bbox)

        self.fft_line.set_ydata(channel_data)
        self.fft_line.set_xdata(freqs[:numpoints])
        # Draw the line
        self.fft_axis.draw_artist(self.fft_line)
        # Blit the canvas
        self.plotCanvas.blit(self.fft_axis.bbox)

    def reset(self,):
        self.current_expected_pcm_clock_rate = None
        if self.device is not None:
            self.device.stop()
            self.analyzer = None
        self.realtime_timer.stop()
        self.plot_timer.stop()
        if self.play_sound_thread.isRunning():
            self.play_sound_thread.quit()
            self.play_sound_thread.wait()
            
        self._ui.messagesLabel.setStyleSheet("background-color: none;")
        self.error_ticks = 0
        self.error_counts = 0
        self.in_error = False

    def shutdown(self,):
        self.recording_state = STATE_IDLE
        self.reset()
        self.device = None
        try:
            self.figure.close()
        except:
            pass
    
    def closeEvent(self, event):
        """Intercepts the close event of the MainWindow."""
        self.show_message("Closing device...")
        try:
            self.shutdown()
            self.event_listener.quit()
            self.event_listener.wait()
            self.audio.terminate()
        finally:
            super(MainWindow, self).closeEvent(event)
开发者ID:markmelvin,项目名称:pySaleae,代码行数:104,代码来源:pcm2wav.py


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