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


Python FigureCanvasWxAgg.restore_region方法代码示例

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


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

示例1: PlotFigure

# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import restore_region [as 别名]
class PlotFigure(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, title="Sensor Monitor", size=(800, 600))
        #set window size
        self.fig = Figure((8, 6), 100)
        self.canvas = FigureCanvas(self, wx.ID_ANY, self.fig)
        self.ax = self.fig.add_subplot(111)
        self.ax.set_ylim([0, 100])
        self.ax.set_xlim([0, POINTS])
        self.ax.set_autoscale_on(False)
        self.ax.set_xticks([])
        self.ax.set_yticks(range(0, 101, 10))
        self.ax.grid(True)
        self.user = [None] * POINTS
        self.l_user,=self.ax.plot(range(POINTS),self.user,label='Light Sensors')
        self.ax.legend(loc='upper center',
                           ncol=4,
                           prop=font_manager.FontProperties(size=10))
        self.canvas.draw()
        self.bg = self.canvas.copy_from_bbox(self.ax.bbox)
        wx.EVT_TIMER(self, TIMER_ID, self.onTimer)

    def onTimer(self, evt):
        self.canvas.restore_region(self.bg)
        for i in range(0,240):
          index = int(i/40)*40
          per = (index-i)+20.0
          per =((math.sin((per/20.0)*math.pi/2))+1.0)/2.0
          self.user[i+30] = 100-(float(arr[i/40])*per+float(arr[(i+40)/40])*(1-per))*1
        self.l_user.set_ydata(self.user)
        self.ax.draw_artist(self.l_user)
        self.canvas.blit(self.ax.bbox)
开发者ID:xeecos,项目名称:LightMusic,代码行数:34,代码来源:show.py

示例2: PlotFigure

# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import restore_region [as 别名]
class PlotFigure(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, title="CPU Usage Monitor", size=(600, 400))
        # Matplotlib Figur
        self.fig = Figure((6, 4), 100)
        # bind the Figure to the backend specific canvas
        self.canvas = FigureCanvas(self, wx.ID_ANY, self.fig)
        # add a subplot  
        self.ax = self.fig.add_subplot(111)
         # limit the X and Y axes dimensions 
        self.ax.set_ylim([0, 100])
        self.ax.set_xlim([0, POINTS])
         
        self.ax.set_autoscale_on(False)
        self.ax.set_xticks([])
        # we want a tick every 10 point on Y (101 is to have 10  
        self.ax.set_yticks(range(0, 101, 10))


        # disable autoscale, since we don't want the Axes to ad  
        # draw a grid (it will be only for Y)  
        self.ax.grid(True)  
        # generates first "empty" plots  
        self.user = [None] * POINTS  
        self.l_user,=self.ax.plot(range(POINTS),self.user,label='User %')  
    
        # 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)  
        # bind events coming from timer with id = TIMER_ID  
        # to the onTimer callback function  
        wx.EVT_TIMER(self, TIMER_ID, self.onTimer)  
        self.Bind(wx.EVT_CLOSE,self.frame_close,self)
      
    def onTimer(self, evt):  
        self.canvas.restore_region(self.bg)  
                    # update the data  
        temp =np.random.randint(60,80)  
        self.user = self.user[1:] + [temp]  
            # update the plot  
        self.l_user.set_ydata(self.user)  
            # just draw the "animated" objects  
        self.ax.draw_artist(self.l_user)# It is used to efficiently update Axes data (axis ticks, labels, etc are not updated)  
        self.canvas.blit(self.ax.bbox) 
        print num
    
    def frame_close(self,event):
        self.Show(False)

    def __del__(self):
        exit()
开发者ID:NanguangChou,项目名称:numa_cpu,代码行数:60,代码来源:plottest.py

示例3: PlotFigure

# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import restore_region [as 别名]
class PlotFigure(wx.Frame):
    def __init__(self,data):
        wx.Frame.__init__(self, None, wx.ID_ANY, title="CPU Usage Monitor", size=(600, 400))
        # Matplotlib Figur
        self.fig = Figure((6, 4), 100)
        self.canvas = FigureCanvas(self, wx.ID_ANY, self.fig)
        # add a subplot  
        self.ax = self.fig.add_subplot(111)
        self.data=data;
        self.ax.set_ylim([0,100])
        self.ax.set_xlim([0, POINTS])
        
        self.ax.set_autoscale_on(False)
        self.ax.set_xticks([])
        self.ax.set_yticks(range(0,100, 5))


        # disable autoscale, since we don't want the Axes to ad  
        # draw a grid (it will be only for Y)  
        self.ax.grid(True)  
        # generates first "empty" plots  
        self.user = [None] * POINTS  
        self.l_user,=self.ax.plot(range(POINTS),self.user,label=u'CPU percentage')  
    
        # add the legend  
        self.ax.legend(loc='upper center',  
                           ncol=4,  
                           prop=font_manager.FontProperties(size=10))  
        self.canvas.draw()  
        self.bg = self.canvas.copy_from_bbox(self.ax.bbox)  
        wx.EVT_TIMER(self, TIMER_ID, self.onTimer)  
        self.Bind(wx.EVT_CLOSE,self.frame_close,self)
      
    def onTimer(self, evt):  
        self.canvas.restore_region(self.bg)
        temp = (math.log(self.data.recvive())/LOG_FREQUENCE)*100
        #temp =np.random.randint(60,80)  

        self.user = self.user[1:] + [temp]  
            # update the plot  
        self.l_user.set_ydata(self.user)  
            # just draw the "animated" objects  
        self.ax.draw_artist(self.l_user)# It is used to efficiently update Axes data (axis ticks, labels, etc are not updated)  
        self.canvas.blit(self.ax.bbox) 
        #print self.data.recvive()
    
    def frame_close(self,event):
        self.Show(False)

    def __del__(self):
        exit()
开发者ID:NanguangChou,项目名称:numa_cpu,代码行数:53,代码来源:my_cpu.py

示例4: PlotFigure

# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import restore_region [as 别名]
class PlotFigure (wx.Frame):
    
    def __init__ (self, groundTruth=None):
        wx.Frame.__init__ (self, None, wx.ID_ANY, title="Trajectory")
        
        self.fig = Figure ()
        self.canvas = FigureCanvas(self, wx.ID_ANY, self.fig)
        self.ax = self.fig.add_subplot (111)
        self.ax.set_xlim ([-600, 1000])
        self.ax.set_ylim ([-1500, 1500])
        self.ax.set_autoscale_on (False)
        self.orbPos1 = None
        self.orbPos2 = None
        self.ax.grid(True)
        
        if groundTruth != None:
            grnd = groundTruth.toArray(False)
            self.groundPlot, = self.ax.plot (grnd[:,0], grnd[:,1])

        # This must be done after all initial drawing
        self.canvas.draw()
        self.bg = self.canvas.copy_from_bbox (self.ax.bbox)
        
        # Bind events to timer function
        wx.EVT_TIMER (self, TIMER_ID, self.onTimer)

    def onTimer (self, event):
        self.canvas.restore_region(self.bg)
        
        orbPosition1 = orbProc1.getPose()
        if orbPosition1 is not None:
            if self.orbPos1 is None:
                self.orbPos1 = self.ax.scatter (orbPosition1.x, orbPosition1.y, color=[[1,0,0,0.5]], s=100, linewidths=0)
            else :
                self.orbPos1.set_offsets([orbPosition1.x, orbPosition1.y])

        orbPosition2 = orbProc2.getPose()
        if orbPosition2 is not None:
            if self.orbPos2 is None:
                self.orbPos2 = self.ax.scatter (orbPosition2.x, orbPosition2.y, color=[[0,1,0,0.5]], s=100, linewidths=0)
            else :
                self.orbPos2.set_offsets([orbPosition2.x, orbPosition2.y])


        self.canvas.draw()
        self.canvas.blit(self.ax.bbox)
开发者ID:Aand1,项目名称:Autoware,代码行数:48,代码来源:TfVisualizer.py

示例5: PlotFigure

# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import restore_region [as 别名]
class PlotFigure(wx.Frame):
    """Matplotlib wxFrame with animation effect"""
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, title="CPU Usage Monitor", size=(600, 400))
        self.fig = Figure((6, 4), 100)
        self.canvas = FigureCanvas(self, wx.ID_ANY, self.fig)
        self.ax = self.fig.add_subplot(111)
        # limit the X and Y axes dimensions
        self.ax.set_ylim(2140, 2150)
        self.ax.set_xlim([0, POINTS])
        self.ax.set_autoscale_on(False)
        self.ax.set_xticks([])
        # we want a tick every 10 point on Y (101 is to have 10
        #self.ax.set_yticks(range(0, 101, 10))
        self.ax.grid(True)
        self.user = [None] * POINTS
        self.l_user,=self.ax.plot(range(POINTS),self.user,label=u'IF1406')

        self.md = MdThread("127.0.0.1",12345)
        self.md.start()
        self.md.RegTick(self.OnTick)
        # add the legend
        self.ax.legend(loc='upper center',
                           ncol=4,
                           prop=font_manager.FontProperties(size=10))
        self.canvas.draw()
        self.bg = self.canvas.copy_from_bbox(self.ax.bbox)
        #wx.EVT_TIMER(self, TIMER_ID, self.onTimer)

    def OnTick(self,tick):
        self.canvas.restore_region(self.bg)
                # update the data
        if tick.InstrumentID != 'IF1404':
            return
        print tick.LastPrice
        temp =np.random.randint(10,80)
        self.user = self.user[1:] + [tick.LastPrice]
        # update the plot
        self.l_user.set_ydata(self.user)
        # just draw the "animated" objects
        self.ax.draw_artist(self.l_user)# It is used to efficiently update Axes data (axis ticks, labels, etc are not updated)
        self.canvas.blit(self.ax.bbox)
开发者ID:norsd,项目名称:Yggdrasil,代码行数:44,代码来源:Monitor0.py

示例6: PanelGraph

# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import restore_region [as 别名]

#.........这里部分代码省略.........
        event.Skip()

    def __on_draw(self, _event):
        axes = self.plot.get_axes()
        if axes is not None:
            self.background = self.canvas.copy_from_bbox(axes.bbox)
            self.__draw_overlay()

    def __on_idle(self, _event):
        if self.doDraw and self.plot.get_plot_thread() is None:
            self.__hide_overlay()
            self.doDraw = False
            if os.name == 'nt':
                threading.Thread(target=self.__draw_canvas, name='Draw').start()
            else:
                with self.lockDraw:
                    self.canvas.draw()
                self.status.set_busy(False)

    def __on_timer(self, _event):
        self.timer.Stop()
        self.set_plot(None, None, None, None, self.annotate)

    def __draw_canvas(self):
        with self.lockDraw:
            try:
                self.canvas.draw()
            except wx.PyDeadObjectError:
                pass
        wx.CallAfter(self.status.set_busy, False)

    def __draw_overlay(self):
        if self.background is not None:
            self.canvas.restore_region(self.background)
            self.__draw_select()
            self.draw_measure()
            axes = self.plot.get_axes()
            if axes is None:
                self.canvas.draw()
            else:
                self.canvas.blit(axes.bbox)

    def __draw_select(self):
        if self.selectStart is not None and self.selectEnd is not None:
            self.mouseSelect.draw(self.selectStart, self.selectEnd)

    def __hide_overlay(self):
        if self.plot is not None:
            self.plot.hide_measure()
        self.__hide_select()

    def __hide_select(self):
        if self.mouseSelect is not None:
            self.mouseSelect.hide()

    def create_plot(self):
        if self.plot is not None:
            self.plot.close()

        self.toolbar.set_auto(True)

        if self.settings.display == Display.PLOT:
            self.plot = Plotter(self.notify, self.figure, self.settings)
        elif self.settings.display == Display.SPECT:
            self.plot = Spectrogram(self.notify, self.figure, self.settings)
        elif self.settings.display == Display.SURFACE:
开发者ID:har5ha,项目名称:RTLSDR-Scanner,代码行数:70,代码来源:panels.py

示例7: PlotPanel

# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import restore_region [as 别名]
class PlotPanel(wx.Panel):
    
    def __init__(self,parent,data_window,yrange=(-3,3),**kwargs):
        from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
        from matplotlib.figure import Figure
                
        self.dw = data_window        
        
        # initialize Panel
        if 'style' not in kwargs.keys():
            kwargs['style'] = wx.NO_FULL_REPAINT_ON_RESIZE
        wx.Panel.__init__( self, parent, **kwargs )

        # initialize matplotlib stuff
        self.figure = Figure()
        self.canvas = FigureCanvasWxAgg(self, -1, self.figure )
        
        self.subplot_x = self.figure.add_subplot(311)
        self.subplot_x.set_ylim(yrange)   
        self.subplot_x.set_xticks([])     
        self.subplot_y = self.figure.add_subplot(312)
        self.subplot_y.set_ylim(yrange) 
        self.subplot_y.set_xticks([])
        self.subplot_z = self.figure.add_subplot(313)
        self.subplot_z.set_ylim(yrange)
        self.subplot_z.set_xticks([])
        
        self.dw.winlock.acquire()
        self.line_x, = self.subplot_x.plot(self.dw.win[:,0],color='r',lw=2,animated=True)
        self.line_y, = self.subplot_y.plot(self.dw.win[:,1],color='g',lw=2,animated=True)
        self.line_z, = self.subplot_z.plot(self.dw.win[:,2],color='b',lw=2,animated=True)
        self.dw.winlock.release()
        self.canvas.draw()
        self.draw()
        
        self.dw.start()
                
        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER,self.OnTimer,self.timer)
        self.timer.Start(1)

    def OnTimer(self,event):
        self.draw()

    def draw( self ):
        """Draw data."""
        if not hasattr(self, 'background' ):
            self.background = self.canvas.copy_from_bbox(self.figure.bbox)
            
        self.canvas.restore_region(self.background)
        self.dw.winlock.acquire()
        self.line_x.set_ydata(self.dw.win[:,0])
        self.line_y.set_ydata(self.dw.win[:,1])
        self.line_z.set_ydata(self.dw.win[:,2])
        self.dw.winlock.release()
        
        self.subplot_x.draw_artist(self.line_x)
        self.subplot_y.draw_artist(self.line_y)
        self.subplot_z.draw_artist(self.line_z)
        
        self.canvas.blit(self.subplot_x.bbox)
        self.canvas.blit(self.subplot_y.bbox)
        self.canvas.blit(self.subplot_z.bbox)
开发者ID:NickFoubert,项目名称:adxl-visualize,代码行数:65,代码来源:viz.py

示例8: CanvasFrame

# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import restore_region [as 别名]
class CanvasFrame(wx.Frame):

    def __init__(self, argv):
        wx.Frame.__init__(self,None,-1,
                         'Bottleneck Distance',size=(550,350))
        parser = argparse.ArgumentParser(description="Utility to plot Bottleneck Distance average of 'representative' segments for each label")
        parser.add_argument('-d','--distances')
        parser.add_argument('-l','--learning')
        parser.add_argument('-p','--partition')
        parser.add_argument('-t','--threshold', default=0.75, type=float)
        self.args = parser.parse_args(argv[1:])
        import traceback
        try :
            self.distances = \
              Distances.fromJSONDict(load_data(self.args.distances, 'distances', None, None, argv[0]+": "))
            self.learning = \
              Learning.fromJSONDict(load_data(self.args.learning, 'learning', None, None, argv[0]+": "))
            self.partitions = \
              TrainTestPartitions.fromJSONDict(load_data(self.args.partition, 'partition', None, None, argv[0]+": "))
        except :
            print "Could not parse input files: %s" % (traceback.format_exc(),)
            sys.exit(1)
        
        # Filter to only the segments that get above the threshold
        
        self.segments = []

        for i in range(len(self.distances.segment_info)) :
            c = segment_correctness(i, self.learning, self.partitions)
            if c == None or c > self.args.threshold :
                self.segments.append((i, self.distances.segment_info[i].max_label()))
        sort_format = "0" * int(math.ceil(math.log(len(self.distances.segment_info))))
        self.segments.sort(key=lambda x: str(x[1]+(("%"+sort_format+"d") % x[0])))

        self.label_index = 0
        self.labels = list(set([x[1] for x in self.segments]))
        self.labels.sort()

        self.segment_minimums = dict([(l, min([i for (i,x) in zip(range(len(self.segments)), self.segments) if x[1] == l])) \
                                       for l in self.labels])
        self.segment_maximums = dict([(l, max([i for (i,x) in zip(range(len(self.segments)), self.segments) if x[1] == l])) \
                                       for l in self.labels])

        self.segment_indices = dict([(l, min([i for (i,x) in zip(range(len(self.segments)), self.segments) if x[1] == l], key=lambda x:average_distance(x,l,self.distances))) \
                                       for l in self.labels])

        self.SetBackgroundColour(wx.NamedColour("WHITE"))
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
        
        self.canvas = FigureCanvas(self, -1, self.figure)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(NavigationToolbar2Wx(self.canvas), 1, wx.LEFT | wx.TOP | wx.GROW)
        self.sizer.Add(self.canvas, 8, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.background = self.axes.figure.canvas.copy_from_bbox(self.axes.bbox)
        self.colors = ['black', 'red', 'yellow', 'orange', 'blue', 'green', 'violet']
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_KEY_UP, self.KeyEvent)

        self.index = 0
        self.point_Refresh()
        self.Fit()
        self.figure.savefig(self.distances.config.out_directory + "/" + self.distances.config.out_directory.split('/')[-1] + '-win-' + str(self.distances.config.window_size) + '-best-distances.pdf')
        sys.exit(0)


    def point_Refresh(self) :
        self.canvas.restore_region(self.background)
        self.axes.cla()
        plots = []
        for (l,i) in zip(self.labels, range(len(self.labels))) :
            xs = [i + j * (len(self.labels) + 1) for j in range(len(self.labels))]
            ys = [average_distance(self.segments[self.segment_indices[l_]][0], l, self.distances) \
                  for l_ in self.labels]
            plots.append(self.axes.bar(xs, ys, color=self.colors[i % len(self.colors)]))
        self.axes.legend(plots, self.labels, loc='best').draggable()
        self.axes.set_xticks([0.5 * len(self.labels) + j * (len(self.labels) + 1) for j in range(len(self.labels))])
        self.axes.set_xticklabels(["Segment %s ('%s')" % (self.segment_indices[l], l) for l in self.labels])
        self.axes.set_ylabel("Bottleneck Distance")
        self.axes.set_title(self.distances.config.out_directory.split('/')[-1] + " Window Size " + str(self.distances.config.window_size))

    def KeyEvent(self, event):
        keycode = event.GetKeyCode()
        if keycode == wx.WXK_LEFT :
            self.segment_indices[self.labels[self.label_index]] = max(min(self.segment_indices[self.labels[self.label_index]] - 1,
                                                                          self.segment_maximums[self.labels[self.label_index]]),
                                                                      self.segment_minimums[self.labels[self.label_index]])
	    self.point_Refresh()
            wx.PostEvent(self,wx.PaintEvent())

        elif keycode == wx.WXK_RIGHT :
            self.segment_indices[self.labels[self.label_index]] = max(min(self.segment_indices[self.labels[self.label_index]] + 1,
                                                                          self.segment_maximums[self.labels[self.label_index]]),
                                                                      self.segment_minimums[self.labels[self.label_index]])
	    self.point_Refresh()
	    wx.PostEvent(self,wx.PaintEvent())

        elif keycode == wx.WXK_UP :
#.........这里部分代码省略.........
开发者ID:gpersistence,项目名称:tstop,代码行数:103,代码来源:plot_best_distances_segment.py

示例9: CanvasFrame

# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import restore_region [as 别名]
class CanvasFrame(wx.Frame):

    def __init__(self, args, data_1, data_2, points_1, points_2):
        wx.Frame.__init__(self,None,-1,
                          'Comparison of Zero Dimensional Persistence Diagrams',size=(1024,768))

        self.args = args
        self.data_1 = data_1
        self.data_2 = data_2
        self.points_1 = points_1
        self.points_2 = points_2
    

        # Set bot and top to the number of outliers you want to clip from your data
        hist = numpy.histogram(self.data_1, bins=50)
        size = len(self.data_1)
        bot = 0 # size / 100
        for i in range(len(hist[0])) :
            self.min_sig_1 = hist[1][i]
            if bot - hist[0][i] < 0: 
                break
            else :
                bot = bot - hist[0][i]
        top = 0 # size / 100
        for i in range(len(hist[0]), 0, -1) :
            self.max_sig_1 = hist[1][i]
            if top - hist[0][i-1] < 0: 
                break
            else :
                top = top - hist[0][i-1]
    
    
        self.min_sig_2 = min(self.data_2)
        self.max_sig_2 = max(self.data_2)
        hist = numpy.histogram(self.data_2, bins=50)
        size = len(self.data_2)
        bot = 0 # size / 100
        for i in range(len(hist[0])) :
            self.min_sig_2 = hist[1][i]
            if bot - hist[0][i] < 0: 
                break
            else :
                bot = bot - hist[0][i]
        top = 0 # size / 100
        for i in range(len(hist[0]), 0, -1) :
            self.max_sig_2 = hist[1][i]
            if top - hist[0][i-1] < 0: 
                break
            else :
                top = top - hist[0][i-1]
    
        self.SetBackgroundColour(wx.NamedColour("WHITE"))
        self.figure = Figure()
        self.persistence_axes_1 = self.figure.add_subplot(221)
        self.persistence_axes_2 = self.figure.add_subplot(222)
        self.signal_axes_1      = self.figure.add_subplot(223)
        self.signal_axes_2      = self.figure.add_subplot(224)

        self.canvas = FigureCanvas(self, -1, self.figure)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.title = self.figure.suptitle("Zero Dimensional Persistence")
        self.background = self.persistence_axes_1.figure.canvas.copy_from_bbox(self.persistence_axes_1.bbox)
        self.colors = ['black', 'red', 'yellow', 'orange', 'blue', 'green', 'violet']
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_KEY_UP, self.KeyEvent)
    
        self.step = 1
        self.frame_1 = 0
        self.frame_2 = 0
        self.cmap = plt.cm.get_cmap('hot')
    
    
        self.point_Refresh()

    def point_Refresh(self) :
        self.canvas.restore_region(self.background)
        self.persistence_axes_1.cla()
        self.persistence_axes_1.set_title("Zero Persistence at step %s" % self.frame_1)
        if self.frame_1 < len(self.points_1) :
            xs  = [p[0] for p in self.points_1[self.frame_1][0]]
            ys  = [p[1] for p in self.points_1[self.frame_1][0]]
            age = [p[2] for p in self.points_1[self.frame_1][0]]
            
            min_val = min(xs+ys) if xs != [] else 0.0
            max_val = max(xs+ys) if xs != [] else 1.0
            if age != [] :
                self.persistence_axes_1.scatter(xs, ys, marker='+', c=age, vmin=min(age), vmax=max(age), cmap=self.cmap)
            self.persistence_axes_1.plot([self.min_sig_1, self.max_sig_1], [self.min_sig_1, self.max_sig_1], color='r')
            for l in self.points_1[self.frame_1][1] :
                self.persistence_axes_1.plot(l[0],l[1], color='#dd2222')
                    
            self.persistence_axes_1.set_xlim([self.min_sig_1, self.max_sig_1])
            self.persistence_axes_1.set_ylim([self.min_sig_1, self.max_sig_1])

        self.persistence_axes_2.cla()
        self.persistence_axes_2.set_title("Zero Persistence at step %s" % self.frame_2)
        if self.frame_2 < len(self.points_2) :
#.........这里部分代码省略.........
开发者ID:gpersistence,项目名称:tstop,代码行数:103,代码来源:zero_persistence_graph.py

示例10: CanvasFrame

# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import restore_region [as 别名]
class CanvasFrame(wx.Frame):

    def __init__(self, argv):
        wx.Frame.__init__(self,None,-1,
                         'Segment Size',size=(550,350))
        parser = argparse.ArgumentParser(description="utility to graph success levels for learning vs configuration parameters")
        parser.add_argument('-d', '--directory', help='Directory where the learning results are stored', required=False)
        parser.add_argument('files', metavar='FILE', nargs='*')
        self.args = vars(parser.parse_args(argv[1:]))
        if self.args['directory'] != None and len(self.args['files']) != 0 :
            print "Ignoring files after the directory argument"
        elif self.args['directory'] == None and len(self.args['files']) == 0 :
            parser.print_help()
            sys.exit()
        
        if self.args['directory'] != None :
            if os.path.isdir(self.args['directory']) :
                self.files = ["%s/%s" % (self.args['directory'], f) for f in os.listdir(self.args['directory']) \
                              if f.endswith('learning.json')]
            else :
                parser.print_help()
                sys.exit()
        else :
            self.files = self.args['files']

        self.filedict = []

        # load in the data files
        for f in self.files :
            with open(f, 'r') as j_file :
                learning = json.load(j_file)
                correct = []
                for iteration in learning['learning'] :
                    # count the correct test results
                    num_correct = reduce((lambda s, (t0, t1) : s + 1 if t0 == t1 else s), zip(iteration['test'], iteration['truth']), 0)
                    correct.append(float(num_correct) / float(len(iteration['test'])))
                learning['config']['correct'] = correct
                if isinstance(learning['config']['data_file'], list) :
                    learning['config']['data_file'] = os.path.basename(learning['config']['data_file'][0]).split('_')[0]
                else :
                    learning['config']['data_file'] = os.path.basename(learning['config']['data_file'])
                del(learning['config']['segment_filename'])
                self.filedict.append(learning['config'])

        # Add a label for each varying parameter
        self.labels = []
        for key in self.filedict[0].keys() :
            if key != 'correct' and len(set([config[key] for config in self.filedict])) > 1 :
                self.labels.append(key)
        print self.labels

        self.frame = 0
        self.SetBackgroundColour(wx.NamedColour("WHITE"))
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
        
        self.canvas = FigureCanvas(self, -1, self.figure)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.title = self.figure.suptitle(self.labels[0])
        self.Fit()
        self.background = self.axes.figure.canvas.copy_from_bbox(self.axes.bbox)
        self.colors = ['black', 'red', 'yellow', 'orange', 'blue', 'green', 'violet']
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_KEY_UP, self.KeyEvent)
        self.point_Refresh()

    def point_Refresh(self) :
        labels = [ label for label in self.labels if label != self.labels[self.frame] ]
        plots = []
        for f_dict in self.filedict : 
            current = [f_dict[label] for label in labels] 
            found = False
            for plot in plots :
                found = found or reduce((lambda x, (y1, y2) : x and (y1 == y2)), zip(current, plot), True)
            if not found :
                plots.append(current)
        self.title.set_text(self.labels[self.frame])
        
        self.canvas.restore_region(self.background)
        self.axes.cla()
        color = 0
        lines = []
        plots = sorted(plots, key=(lambda x: reduce((lambda y,z: y + " " + str(z)), x, "")))
        for plot in plots :
            vals = sorted([ (f_dict[self.labels[self.frame]], f_dict['correct']) for f_dict in self.filedict if \
                            reduce((lambda x_, (x,y) : x_ and (f_dict[x] == y)), zip(labels, plot), True)], key=(lambda x: x[0]))
            
            label = ''
            for (key,index) in zip(labels, range(len(labels))):
                if key != self.labels[self.frame] :
                    label = label + " " + key + " " + str(plot[index])

            if (isinstance(vals[0][0], (str,unicode))) :
                line = self.axes.plot([x for x in range(len(vals))],[x[1] for x in vals],
                                      color=self.colors[color % len(self.colors)],
                                      label=label)
            else :
#.........这里部分代码省略.........
开发者ID:gpersistence,项目名称:tstop,代码行数:103,代码来源:plot_learning.py

示例11: CanvasFrame

# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import restore_region [as 别名]
class CanvasFrame(wx.Frame) :
    def __init__(self, full_data) :
        self.full_rips_persistences = [PD.fromJSONDict(entry[0]['full_diagram']) for entry in full_data]
        self.full_rips_runtimes = [format_runtime(entry[0]['runtime']) for entry in full_data]
        self.sparse_rips_persistences = [[PD.fromJSONDict(e['diagram']) for e in entry[1:]] for entry in full_data]
        self.sparse_rips_distances = [[(e['bottleneck_distance'],e['wasserstein_l1'],e['wasserstein_l2']) for e in entry[1:]] \
                                      for entry in full_data]
        self.sparse_rips_sparsity = [[[float(s)*100.0 for s in e['sparsity']] if 'sparsity' in e else None for e in entry[1:]] for entry in full_data]
        self.sparse_rips_runtimes = [[format_runtime(e['runtime']) for e in entry[1:]] for entry in full_data]
        self.simplices = [int(entry['max_simplices']) if 'max_simplices' in entry else None for entry in full_data[0][1:]]
        self.epsilons = [float(entry['epsilon']) if 'epsilon' in entry else None for entry in full_data[0][1:]]

        wx.Frame.__init__(self, None, -1, "Full vs. Sparse Rips Filtration", size=(550, 550))

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_KEY_UP, self.KeyEvent)

        self.segment_index = 0
        self.full_rips_figure = Figure()
        self.full_rips_axes = self.full_rips_figure.add_subplot(111)
        self.full_rips_canvas = FigureCanvas(self, -1, self.full_rips_figure)
        self.full_rips_title = self.full_rips_figure.suptitle("Persistence Diagram %s of %s runtime %s" % \
                                                              (self.segment_index + 1, len(self.full_rips_persistences), \
                                                               self.full_rips_runtimes[self.segment_index]))

        self.simplices_index = 0
        self.sparse_rips_figure = Figure()
        self.sparse_rips_axes = self.sparse_rips_figure.add_subplot(111)
        self.sparse_rips_canvas = FigureCanvas(self, -1, self.sparse_rips_figure)
        self.sparse_rips_title = self.sparse_rips_figure.suptitle("max simplices %s" % \
                                                                  (self.simplices[self.simplices_index],))

        self.sizer = wx.GridBagSizer(hgap=5, vgap=5)
        self.sizer.Add(NavigationToolbar2Wx(self.full_rips_canvas), pos=(0,0), span=(1,2), flag=wx.EXPAND)
        self.sizer.AddGrowableCol(1,0)
        self.sizer.Add(self.full_rips_canvas, pos=(1,0), span=(8,2), flag=wx.EXPAND)
        self.sizer.AddGrowableCol(9,0)
        self.sizer.Add(NavigationToolbar2Wx(self.sparse_rips_canvas), pos=(9,0), span=(1,2), flag=wx.EXPAND)
        self.sizer.Add(self.sparse_rips_canvas, pos=(10,0), span=(8,2), flag=wx.EXPAND)
        self.SetSizer(self.sizer)
        self.Fit()
        self.background = self.full_rips_axes.figure.canvas.copy_from_bbox(self.full_rips_axes.bbox)
        self.refresh()

    def refresh(self) :
        # Max of all the values so the different plots have the same scale
        max_val = max([max([d[0] for d in self.full_rips_persistences[self.segment_index].points]),
                       max([d[1] for d in self.full_rips_persistences[self.segment_index].points]),
                       max([d[0] for d in self.sparse_rips_persistences[self.segment_index][self.simplices_index].points]),
                       max([d[1] for d in self.sparse_rips_persistences[self.segment_index][self.simplices_index].points])])
                       
        self.full_rips_canvas.restore_region(self.background)
        self.full_rips_title.set_text("Persistence Diagram %s of %s runtime %s" % \
                                        (self.segment_index + 1, len(self.full_rips_persistences), \
                                         self.full_rips_runtimes[self.segment_index]))
        self.full_rips_axes.cla()

        data = self.full_rips_persistences[self.segment_index].points
        if data != None and len(data) > 0 :
            xs = [d[0] for d in data if d[2] == 1]
            ys = [d[1] for d in data if d[2] == 1]
            self.full_rips_axes.scatter(xs,ys, color="blue")
            xs = [d[0] for d in data if d[2] == 0]
            ys = [d[1] for d in data if d[2] == 0]
            self.full_rips_axes.scatter(xs,ys, color="grey")
            self.full_rips_axes.plot([0,max_val],[0,max_val],color="red")

        self.sparse_rips_canvas.restore_region(self.background)
        if self.simplices[self.simplices_index] != None :
            self.sparse_rips_title.set_text("max simplices %s runtime %s sparsity 0 %02.2f%% 1 %02.2f%% 2 %02.2f%%" % \
                                            (self.simplices[self.simplices_index], 
                                             self.sparse_rips_runtimes[self.segment_index][self.simplices_index],
                                             self.sparse_rips_sparsity[self.segment_index][self.simplices_index][0] if self.sparse_rips_sparsity[self.segment_index][self.simplices_index] != None else 0.0,
                                             self.sparse_rips_sparsity[self.segment_index][self.simplices_index][1] if self.sparse_rips_sparsity[self.segment_index][self.simplices_index] != None else 0.0,
                                             self.sparse_rips_sparsity[self.segment_index][self.simplices_index][2] if self.sparse_rips_sparsity[self.segment_index][self.simplices_index] != None else 0.0))
        else :
            self.sparse_rips_title.set_text("epsilon %g runtime %s sparsity 0 %02.2f%% 1 %02.2f%% 2 %02.2f%%" % \
                                            (self.epsilons[self.simplices_index], 
                                             self.sparse_rips_runtimes[self.segment_index][self.simplices_index],
                                             self.sparse_rips_sparsity[self.segment_index][self.simplices_index][0] if self.sparse_rips_sparsity[self.segment_index][self.simplices_index] != None else 0.0,
                                             self.sparse_rips_sparsity[self.segment_index][self.simplices_index][1] if self.sparse_rips_sparsity[self.segment_index][self.simplices_index] != None else 0.0,
                                             self.sparse_rips_sparsity[self.segment_index][self.simplices_index][2] if self.sparse_rips_sparsity[self.segment_index][self.simplices_index] != None else 0.0))
        
        self.sparse_rips_axes.cla()
        self.sparse_rips_axes.set_title("distance bottleneck %.3f wasserstein l1 %.3f l2 %.3f" % \
                                        (self.sparse_rips_distances[self.segment_index][self.simplices_index][0],
                                         self.sparse_rips_distances[self.segment_index][self.simplices_index][1],
                                         self.sparse_rips_distances[self.segment_index][self.simplices_index][2]),
                                        fontdict=dict([('fontsize',12)]))

        data = self.sparse_rips_persistences[self.segment_index][self.simplices_index].points
        if data != None and len(data) > 0 :
            xs = [d[0] for d in data if d[2] == 1]
            ys = [d[1] for d in data if d[2] == 1]
            self.sparse_rips_axes.scatter(xs,ys, color="blue")
            xs = [d[0] for d in data if d[2] == 0]
            ys = [d[1] for d in data if d[2] == 0]
            self.sparse_rips_axes.scatter(xs,ys, color="grey")
            self.sparse_rips_axes.plot([0,max_val],[0,max_val],color="red")
        
#.........这里部分代码省略.........
开发者ID:gpersistence,项目名称:tstop,代码行数:103,代码来源:rips_plotter.py

示例12: CanvasFrame

# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import restore_region [as 别名]
class CanvasFrame(wx.Frame):

    def __init__(self, argv):
        wx.Frame.__init__(self,None,-1,
                         'Segment Size',size=(550,350))
        parser = argparse.ArgumentParser(description="utility to graph success levels for learning over a single configuration parameter")
        parser.add_argument('--label', '-l')
        parser.add_argument('files', metavar='FILE', nargs='*')
        self.args = vars(parser.parse_args(argv[1:]))
        self.files = self.args['files']

        self.filedict = []
        # load in the data files
        for f in self.files :
            learning = Learning.fromJSONDict(load_data(f, 'learning', None, None, argv[0] + ": "))
            correct = []
            for result in learning.results : 
                num_correct = reduce((lambda s, (t0, t1) : s + 1 if t0 == t1 else s), 
                                     zip(result['test_labels'], result['test_results']), 0)
                correct.append(float(num_correct) / float(len(result['test_labels'])))
            print "file %s correct %0.2f%%" % (f, numpy.average(correct)*100.0)
            self.filedict.append(dict([('file', f), ('correct', numpy.average(correct)), ('config', learning.config)]))
            if "PersistenceKernelLearning" in f :
                self.filedict[-1]['label'] = "Persistence Kernel " + learning.config.data_index
                if learning.config.post_process != None :
                    self.filedict[-1]['label'] = self.filedict[-1]['label'] + " " + learning.config.post_process
            elif "AverageKernelLearning" in f :
                self.filedict[-1]['label'] = "Average Kernel"
                if learning.config.post_process != None :
                    self.filedict[-1]['label'] = self.filedict[-1]['label'] + " " + learning.config.post_process
            elif "ChaoticInvariantFeaturesLearning" in f :
                self.filedict[-1]['label'] = " Chaotic Invariant Features"
            elif "ScaleSpaceSimilarityLearning" in f :
                self.filedict[-1]['label'] = "Scale Space Similarity"
            elif "EuclideanDistancesLearning" in f :
                self.filedict[-1]['label'] = "Euclidean Distance"
            if (len(correct) > 1) :
                self.filedict[-1]['correct_std'] = numpy.std(correct)
                self.filedict[-1]['correct_top'] = numpy.percentile(correct, 0.75)
                self.filedict[-1]['correct_bot'] = numpy.percentile(correct, 0.25)
            else :
                self.filedict[-1]['correct_std'] = 0.0
                self.filedict[-1]['correct_top'] = 0.0
                self.filedict[-1]['correct_bot'] = 0.0
        
        self.SetBackgroundColour(wx.NamedColour("WHITE"))
        self.figure = Figure()
        self.axes = self.figure.add_subplot(211)
        
        self.canvas = FigureCanvas(self, -1, self.figure)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(NavigationToolbar2Wx(self.canvas), 1, wx.LEFT | wx.TOP | wx.GROW)
        self.sizer.Add(self.canvas, 8, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.title = self.figure.suptitle("")
        self.Fit()
        self.background = self.axes.figure.canvas.copy_from_bbox(self.axes.bbox)
        self.colors = ['#a6cee3', '#1f78b4', '#b2df8a', '#33a02c', '#b3de69', '#fb9a99', '#e31a1c', '#fb8072', '#ff7f00', '#a65628', '#fdb462', '#cab2d6']
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_KEY_UP, self.KeyEvent)
        self.point_Refresh()

    def point_Refresh(self) :
        self.title.set_text("")
        
        self.canvas.restore_region(self.background)
        self.axes.cla()
        color = 0
        lines = []
        plots = []
        for f_dict in self.filedict : 
            current = [f_dict['label']]
            found = False
            for plot in plots :
                found = found or reduce((lambda x, (y1, y2) : x and (y1 == y2)), zip(current, plot), True)
            if not found :
                plots.append(current)
        vals = sorted([ (f_dict['label'], float(numpy.average(f_dict['correct'])), \
                         f_dict['correct_top'] if 'correct_top' in f_dict else 0.0, \
                         f_dict['correct_bot'] if 'correct_bot' in f_dict else 0.0) \
                        for f_dict in self.filedict], key=(lambda x: x[0]))
            
        # if the iterated value is a string, plot vs. lexicographic sorting
        if (isinstance(vals[0][0], (str,unicode))) :
            xs = [] 
            x = 0
            for v in vals:
                if not ('ChaosPost' in v[0]) :
                    xs.append(x)
                    x = x + 1
        else :
            xs = [x[0] for x in vals]
        bottom = 0.75
        ys = [x[1] - bottom for x in vals if ('Chao' in x[0])]
        y_err = [[abs(v[3]-v[1]) for v in vals if ('Chao' in v[0])] , [abs(v[2]-v[1]) for v in vals if ('Chao' in v[0])]]
        colors = [self.colors[x % len(self.colors)] for x in range(len(xs))]
        rects0 = self.axes.bar([xs[0]], [ys[0]],
                               color=colors[2],
                               yerr=[[y_err[0][0]], [y_err[1][0]]],
#.........这里部分代码省略.........
开发者ID:gpersistence,项目名称:tstop,代码行数:103,代码来源:plot_learning_errorbars.py

示例13: VelocityPanel

# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import restore_region [as 别名]

#.........这里部分代码省略.........
        self.y_axes = self.fig.add_subplot(132)                 ## the y velocity
        self.m_axes = self.fig.add_subplot(133)                 ## the magnitude of the velocity
        #self.axes = self.fig.add_axes((0.1,0.1,0.85,0.8))        ##left,bottom,width,height
        
        self.x_plot = self.x_axes.plot([0,1],[0,1],'b', animated=True)
        self.y_plot = self.y_axes.plot([0,1],[0,1],'b', animated=True)
        self.m_plot = self.m_axes.plot([0,1],[0,1],'r', animated=True)
        
        self.x_axes.set_title('X', fontsize='10')
        self.y_axes.set_title('Y', fontsize='10')
        self.m_axes.set_title('M', fontsize='10')
        self.x_axes.set_ylabel('Velocity (cm/s)', fontsize='10')
        #self.axes.set_ylabel('x (cm)', fontsize='10')

        ##plot formatting
        self._formatAxes(self.x_axes)
        self._formatAxes(self.y_axes)
        self._formatAxes(self.m_axes)
        #self.axes.set_title('Velocity', fontsize='10')
        
        self.canvas.draw()
        self.canvas.gui_repaint()
        
        # save the clean slate background -- everything but the animated line
        # is drawn and saved in the pixel buffer background
        self.background = self.canvas.copy_from_bbox(self.fig.bbox)
        
    def _initFigure(self):
        ##Create a matplotlib figure/canvas in this panel
        ##the background colour will be the same as the panel
        ##the size will also be the same as the panel
        ##calculate size in inches
        pixels_width,pixels_height = self.GetSizeTuple()
        self.dpi = 96.0
        inches_width = pixels_width/self.dpi
        inches_height = pixels_height/self.dpi
        
        ##calculate colour in RGB 0 to 1
        colour = self.GetBackgroundColour()
        self.fig = Figure(figsize=(inches_width,inches_height), dpi = self.dpi\
            ,facecolor=(colour.Red()/255.0, colour.Green()/255.0, colour.Blue()/255.0)\
            ,edgecolor=(colour.Red()/255.0, colour.Green()/255.0, colour.Blue()/255.0))    

        self.canvas = FigureCanvasWxAgg(self, -1, self.fig)

        self.fig.subplots_adjust(left=0.05,right=0.95,wspace=0.08)

        ##now put everything in a sizer
        sizer = wx.BoxSizer(wx.VERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, wx.LEFT|wx.TOP|wx.GROW)
        self.SetSizer(sizer)
        self.Fit()
        
    def _formatAxes(self, axes):
        """ """
        ticks = numpy.arange(-25, 25+5, 5)
        labels = [str(tick) for tick in ticks]              # velocity
        axes.set_yticks(ticks)
        axes.set_yticklabels(labels, fontsize=8)
        ticks = numpy.arange(0, 10+1.0, 1.0)                # time
        labels = [str(tick) for tick in ticks]              
        axes.set_xticks(ticks)
        axes.set_xticklabels(labels,fontsize=8)
        
        #if axes == self.m_axes:
        #    self.axes.set_xlabel('time (s)', fontsize='10')
        #self.axes.set_ylabel(' (mm)', fontsize='10')
        
        
    
    def updateData(self, velx, vely, vel):
        """updateData. Updates the data that this panel is displaying.
        """
        self.VelocitiesX.append(velx)
        self.VelocitiesY.append(vely)
        self.Velocities.append(vel)
        timenow = time.time()
        self.Times.append(timenow)
        if timenow - self.Times[0] > 10:
            del self.Times[0]
            del self.VelocitiesX[0]
            del self.VelocitiesY[0]
            del self.Velocities[0]
        
        self.x_plot[0].set_data(numpy.array(self.Times) - self.Times[0], self.VelocitiesX)
        self.y_plot[0].set_data(numpy.array(self.Times) - self.Times[0], self.VelocitiesY)
        self.m_plot[0].set_data(numpy.array(self.Times) - self.Times[0], self.Velocities)
        
        # restore the clean slate background
        self.canvas.restore_region(self.background)
        # just draw the animated artist
        self.fig.draw_artist(self.x_plot[0])
        self.fig.draw_artist(self.y_plot[0])
        self.fig.draw_artist(self.m_plot[0])
        # just redraw the axes rectangle
        self.canvas.blit(self.fig.bbox)

    def OnPolarPanelPaint(self, event):
        pass
开发者ID:RJianCheng,项目名称:naowalkoptimiser,代码行数:104,代码来源:VelocityPanel.py

示例14: PlotFigure

# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import restore_region [as 别名]
class PlotFigure(wx.Frame):
    def __init__(self, portname, baudrate):###
        wx.Frame.__init__(self, None, wx.ID_ANY, title="Arduino Monitor", size=(800,600))

        self.fig = Figure((8,6), 100)
        self.canvas = FigureCanvas(self, wx.ID_ANY, self.fig)
        self.ax = self.fig.add_subplot(1,1,1)

        self.ax.set_ylim([-0.1, 1.15])
        self.ax.set_xlim([0,300])
        self.ax.set_autoscale_on(False)

        self.xleft = 0
        self.xright = 300
        self.ax.set_xticks([])
        self.ax.set_yticks([0.0,0.5,1.0])
        self.ax.grid(True)

        self.data = [None] * 300    
        
        self.l_data,=self.ax.plot(range(300), self.data, label='Arduino Output')
        #',' means iteration
        self.l_x1 = self.ax.text(0,-0.05,'') 
        self.l_x5 = self.ax.text(290,-0.05,'')

        self.ax.legend(loc='upper center', ncol=1)

        self.canvas.draw()
        self.bg = self.canvas.copy_from_bbox(self.ax.bbox)

        self.ser = serial.Serial(portname, baudrate)###open serial port and assign a baudrate
        time.sleep(5)#this command is very important since the arduino board needs a short while to settle. 
        #without this settling time, the programme would got stuck!
        self.ser.flushInput()
        self.ser.flushOutput()
        self.counter = 0.0

        wx.EVT_TIMER(self, TIMER_ID, self.onTimer)#binding

    def onTimer(self, evt):
        self.ser.write("?")#the py program might need to wait a bit till data arrives in buffer
        tmp = self.ser.read()#tmp is a string
        tmp = int(tmp)#tmp is an integer now
        self.canvas.restore_region(self.bg)
        self.data = self.data[1:] + [tmp]#keep self.data 300 elements long while forwarding the sequence
        
        self.xleft = self.xleft + 1
        self.xright = self.xright + 1
        #print self.xleft, self.xright

        self.l_data.set_ydata(self.data)
        self.counter = self.counter + 0.05
        tmp1 = str(int(self.counter + 0.5))
        tmp2 = str(int(self.counter + 0.5) - 15)# 15 = 300 pts / (1 sec / 50 msec)
        self.l_x1.set_text(tmp2)
        self.l_x5.set_text(tmp1)

        self.ax.draw_artist(self.l_data)
        
        self.ax.draw_artist(self.l_x1)##
        self.ax.draw_artist(self.l_x5)##

        self.canvas.blit(self.ax.bbox)
开发者ID:suncezhouyu,项目名称:arduino-based-oscilloscope-development,代码行数:65,代码来源:oscilloscope.py

示例15: NaoPanel

# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import restore_region [as 别名]

#.........这里部分代码省略.........
        self.naohistoryx = list()
        self.naohistoryy = list()
        
        self.positionmeasurementplot = self.axes.plot([0,0],[0,0], 'blue', marker='o', markersize=5, linewidth=0, markeredgewidth=0, animated=True)
        self.orientationmeasurementplot = self.axes.plot([0,0],[0,0], 'blue', linewidth=2, animated=True)
        self.shapeplot = self.axes.plot([0,0],[0,0], 'blue', marker='o', markersize=2, linewidth=0, markeredgewidth=0, animated=True)
        self.estimateplot = self.axes.plot([0,0],[0,0], 'red', linewidth=2, animated=True)
        self.particleplot = self.axes.quiver([0,0],[0,0], [1,1], [0.5, -0.5], [1, 1], cmap=pylab.gray(), animated=True)
        
        ##plot formatting
        self.axes.set_title('Nao Image', fontsize='10')
        self.axes.set_xlabel('y (cm)', fontsize='10')
        self.axes.set_ylabel('x (cm)', fontsize='10')
        ticks = numpy.arange(-25, 25 + 5, 5)
        labels = [str(tick) for tick in ticks]
        self.axes.set_yticks(ticks)
        self.axes.set_yticklabels(labels, fontsize=8)
        self.axes.set_ylim(ticks[0], ticks[-1])
        ticks = -numpy.arange(-50, 50+5, 5)
        labels = [str(tick) for tick in ticks]
        self.axes.set_xticks(ticks)
        self.axes.set_xticklabels(labels,fontsize=8)
        self.axes.set_xlim(ticks[0], ticks[-1])
        
        self.canvas.draw()
        self.canvas.gui_repaint()
        
        # save the clean slate background -- everything but the animated line
        # is drawn and saved in the pixel buffer background
        self.background = self.canvas.copy_from_bbox(self.axes.bbox)
        
        #self.leftedgeplot = self.axes.plot([0,0],[0,0], 'orange', marker='o', markersize=4, linewidth=0, animated=True) 
        #self.rightedgeplot = self.axes.plot([0,0],[0,0], 'purple', marker='o', markersize=4, linewidth=0, animated=True)
        
    def setNaoFinder(self, finder):
        """ """
        self.NAOFinder = finder
        
    def setLocalisation(self, localisation):
        """ """
        self.Localisation = localisation
    
    def updateData(self, data):
        """updateData. Updates the data that this panel is displaying.
        """
        # Note the x values are plotted on the y-axis, and the y values are plotted on the x-axis
        naox = self.Localisation.X
        naoy = self.Localisation.Y
        naoorientation = self.Localisation.Orientation
        
        measurednaox = self.NAOFinder.NaoX
        measurednaoy = self.NAOFinder.NaoY
        measurednaoorientation = self.NAOFinder.NaoOrientation
        
        self.positionmeasurementplot[0].set_data([measurednaoy, measurednaoy], [measurednaox, measurednaox])
        self.orientationmeasurementplot[0].set_data([measurednaoy + 10*numpy.sin(measurednaoorientation - numpy.pi), measurednaoy + 10*numpy.sin(measurednaoorientation)], [measurednaox + 10*numpy.cos(measurednaoorientation - numpy.pi), measurednaox + 10*numpy.cos(measurednaoorientation)])
        self.shapeplot[0].set_data(self.NAOFinder.ShapeY, self.NAOFinder.ShapeX)
        self.naohistoryx.append(naox)
        self.naohistoryy.append(naoy)
        if len(self.naohistoryx) > 20:
            del self.naohistoryx[0]
            del self.naohistoryy[0]
        self.naohistoryplot[0].set_data(self.naohistoryy, self.naohistoryx)

        self.estimateplot[0].set_data([naoy, naoy + 10*numpy.sin(self.Localisation.Orientation)], [naox, naox + 10*numpy.cos(self.Localisation.Orientation)])
        #self.particleplot = self.axes.quiver(numpy.array(self.Localisation.States[:,Localisation.Y]), numpy.array(self.Localisation.States[:,Localisation.X]), -numpy.sin(self.Localisation.States[:,Localisation.THETA]), numpy.cos(self.Localisation.States[:,Localisation.THETA]), 1.0 - self.Localisation.GUIWeights, headlength=10, headwidth=10, width=0.001, scale=50.0)

        self.axes.set_xlim(naoy + 50, naoy - 50)
        self.axes.set_ylim(naox - 25, naox + 25)
        # restore the clean slate background
        self.canvas.restore_region(self.background)
        # just draw the animated artist
        self.axes.draw_artist(self.shapeplot[0])
        #self.axes.draw_artist(self.particleplot)
        self.axes.draw_artist(self.naohistoryplot[0])
        self.axes.draw_artist(self.orientationmeasurementplot[0])
        self.axes.draw_artist(self.positionmeasurementplot[0]) 
        self.axes.draw_artist(self.estimateplot[0]) 

        # just redraw the axes rectangle
        self.canvas.blit(self.axes.bbox)
        
        
        #leftx = list()
        #lefty = list()
        #for leftedge in self.NAOFinder.LeftEdges:
        #    leftx.append(data[0][leftedge])
        #    lefty.append(data[1][leftedge])
        
        #rightx = list()
        #righty = list()
        #for rightedge in self.NAOFinder.RightEdges:
        #    rightx.append(data[0][rightedge])
        #    righty.append(data[1][rightedge])
        
        #self.leftedgeplot[0].set_data(lefty, leftx)
        #self.rightedgeplot[0].set_data(righty, rightx)

    def OnNaoPanelPaint(self, event):
        pass
开发者ID:RJianCheng,项目名称:naowalkoptimiser,代码行数:104,代码来源:NaoPanel.py


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