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


Python FigureCanvasGTKAgg.mpl_connect方法代码示例

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


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

示例1: __init__

# 需要导入模块: from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg [as 别名]
# 或者: from matplotlib.backends.backend_gtkagg.FigureCanvasGTKAgg import mpl_connect [as 别名]
  def __init__(self, x, y, title="Graph", parent=None):
    gtk.Window.__init__(self)
    try:
      self.set_screen(parent.get_screen())
    except:
      self.connect('destroy', lambda *w: self.destroy())

    self.set_title(title)
    self.set_default_size(800, 600)
    self.set_border_width(2)
    self.set_position(gtk.WIN_POS_CENTER)

    box = gtk.VBox()
    self.add(box)

    fig = Fig(figsize=(5,4), dpi=100)
    ax = fig.add_subplot(111)
    ax.plot(x, y)

    canvas = FigCan(fig)
    canvas.mpl_connect('key_press_event', self.on_key_event)
    box.pack_start(canvas)

    toolbar = NavBar(canvas, self)
    box.pack_start(toolbar, False, False)

    self.show_all()

    del box, fig, ax, canvas, toolbar
开发者ID:moyeah,项目名称:wp,代码行数:31,代码来源:wp_graph.py

示例2: PowerGraph

# 需要导入模块: from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg [as 别名]
# 或者: from matplotlib.backends.backend_gtkagg.FigureCanvasGTKAgg import mpl_connect [as 别名]
class PowerGraph(gtk.Window):
  def __init__(self, powers, step=0.5, title="Power Graph", parent=None):
    x = []
    y = []

    for power, next_power in itertools.izip(powers, powers[1:]):
      u = float(power[0])
      u1 = float(next_power[0])

      while u < u1:
        x.append(u)
        y.append(float(eval(power[1])))
        u += step*(u1-u)

    x.append(float(powers[-1][0]))
    y.append(float(eval(powers[-1][1])))

    gtk.Window.__init__(self)
 
    try:
      self.set_screen(parent.get_screen())
    except AttributeError:
      self.connect('destroy', lambda *w: self.destroy())

    if parent is not None:
      self.set_parent(parent)
    self.set_title(title)
    self.set_destroy_with_parent(True)
    self.set_default_size(600, 400)

    vbox = gtk.VBox()
    self.add(vbox)

    figure = Figure(figsize=(5,4), dpi=100)
    subplot = figure.add_subplot(111)
    subplot.plot(x, y)
    subplot.set_title("Power Graph")
    subplot.set_xlabel("Speed (u) [m/s]")
    subplot.set_ylabel("Power [kW]")
    subplot.grid(True)

    self.canvas = FigureCanvas(figure)
    self.canvas.mpl_connect('key_press_event', self.on_key_event)
    vbox.pack_start(self.canvas)

    self.toolbar = NavigationToolbar(self.canvas, self)
    vbox.pack_start(self.toolbar, False, False)

    self.show_all()

  def on_key_event(self, event):
    key_press_handler(event, self.canvas, self.toolbar)
开发者ID:moyeah,项目名称:wpc,代码行数:54,代码来源:powergraph.py

示例3: __init__

# 需要导入模块: from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg [as 别名]
# 或者: from matplotlib.backends.backend_gtkagg.FigureCanvasGTKAgg import mpl_connect [as 别名]
    def __init__(self, toolBoxWidgets=None, title="GTK Gui Plot", scaling=True, *args, **kwargs):
        if not toolBoxWidgets:
            toolBoxWidgets = []
        super(GuiWithCanvasAndToolbar, self).__init__(*args, **kwargs)
        self.connect("destroy", lambda x: gtk.main_quit())
        self.set_default_size(1100, 600)
        self.set_title(title)

        table = gtk.Table(1, 2, False)

        self.figures = []
        self.y_max = float("-inf")
        self.x_max = float("-inf")
        self.y_min = float("inf")
        self.x_min = float("inf")
        self.fig = Figure(figsize=(8, 6), dpi=100)
        self.ax = self.fig.add_subplot(111)
        canvas = FigureCanvas(self.fig)
        canvas.set_size_request(800, 600)
        canvas.mpl_connect('button_press_event', self.handle_click)

        table.attach(canvas, 0, 1, 0, 1)

        toolbox = gtk.Table(len(toolBoxWidgets) + 1, 1, False)
        i = 0
        for widget in toolBoxWidgets:
            toolbox.attach(widget, 0, 1, i, i + 1)
            i += 1

        label = gtk.Label("SimGUI")
        toolbox.attach(label, 0, 1, i, i + 1)

        table.attach(toolbox, 1, 2, 0, 1)

        self.canvas = canvas
        canvas.draw()
        self.update_figures()

        self.add(table)
        self.scaling = scaling
开发者ID:salceson,项目名称:geometria,代码行数:42,代码来源:gui_with_canvas_and_toolbar.py

示例4: __init__

# 需要导入模块: from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg [as 别名]
# 或者: from matplotlib.backends.backend_gtkagg.FigureCanvasGTKAgg import mpl_connect [as 别名]
 def __init__(self, wTree, widget):
     figure = Figure(figsize=(6,4), dpi=72)
     axes = figure.add_subplot(1,1,1)
     canvas = FigureCanvasGTKAgg(figure)
     canvas.show()
     canvas.mpl_connect('pick_event', self.pick_handler)
     canvas.mpl_connect('motion_notify_event', self.motion_handler)
     canvas.mpl_connect('button_release_event', self.release_handler)
     canvas.mpl_connect('button_press_event', self.press_handler)
     graphview = wTree.get_widget(widget)
     graphview.add_with_viewport(canvas)
     self.figure = figure
     self.canvas = canvas
     self.axes = axes
     self.plot_line = self.axes.plot([], [], 'b-', animated=True)[0]
     self.cursors = []
     self.picked = None
     self.data = []
开发者ID:phosphor,项目名称:phosphor,代码行数:20,代码来源:widgets.py

示例5: __init__

# 需要导入模块: from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg [as 别名]
# 或者: from matplotlib.backends.backend_gtkagg.FigureCanvasGTKAgg import mpl_connect [as 别名]

#.........这里部分代码省略.........
            "partAtomCount": array([550, 750, 500, 800]),
            "partLumCorr": array([550, 750, 800, 950]),
            "part": self.maxImageSize,
            "xylim": [(0, 6826), (9138, 0)],
            "Marker1Pos": (0, 0),
            "Marker2Pos": (0, 0),
            "imageAx": ax0,
            "linescanAx": ax2,
            "canvasObj": canvas_Li,
            "ODmaxAuto": builder.get_object("checkbuttonLiAutoOD"),
            "ODmaxLabel": builder.get_object("labelLiOD"),
            "ODmax": builder.get_object("hscaleLiOD"),
            "adwinID": builder.get_object("adwinIDLi"),
            "imageCategory": "opt. Dichte",
            "values2calc": LiValues2calc,
            "indexLst": LiIndexLst,
            "last10": pd.DataFrame(index=LiIndexLst),
        }

        # reload Parameters of last Session
        try:
            with open("restoreLastSession.pickle", "rb") as infile:
                parameterFromStorage = pickle.load(infile)
                self.RbParameters["part"] = parameterFromStorage[0]
                self.RbParameters["partAtomCount"] = parameterFromStorage[1]
                self.RbParameters["partLumCorr"] = parameterFromStorage[2]
                self.RbParameters["xylim"] = parameterFromStorage[3]
                self.RbParameters["Marker1Pos"] = parameterFromStorage[4]
                self.RbParameters["Marker2Pos"] = parameterFromStorage[5]
                self.LiParameters["part"] = parameterFromStorage[6]
                self.LiParameters["partAtomCount"] = parameterFromStorage[7]
                self.LiParameters["partLumCorr"] = parameterFromStorage[8]
                self.LiParameters["xylim"] = parameterFromStorage[9]
                self.LiParameters["Marker1Pos"] = parameterFromStorage[10]
                self.LiParameters["Marker2Pos"] = parameterFromStorage[11]
        except:
            print "Cannot load last Session!"

        # set working directory
        os.chdir(self.RbParameters["folder"])

        # draw matplotlib stuff
        self.initLines(self.RbParameters)
        self.initLines(self.LiParameters)
        self.updateFullFrameImage(self.RbParameters)
        self.updateFullFrameImage(self.LiParameters)
        self.last10Rb = self.drawImageArea(self.RbParameters)
        self.last10Li = self.drawImageArea(self.LiParameters)

        # show gtk-window
        self.window.set_default_size(1024, 800)
        self.window.set_size_request(600, 800)
        self.window.set_title("Panoptikum - LiRb-Lab Image Analyse")
        self.window.show_all()
        # self.statusbar1_text_pushed('Li image updated... waiting for images...')

        # GTK-event handlers
        self.window.connect("key_press_event", self.on_key_press)
        self.window.connect("key_release_event", self.on_key_released)

        # matplotlib-event handlers
        canvas_Rb.mpl_connect("button_press_event", self.mouse_press_callback_Rb)
        canvas_Rb.mpl_connect("button_release_event", self.mouse_release_callback_Rb)
        canvas_Rb.mpl_connect("scroll_event", self.mouse_scrolled_callback_Rb)
        canvas_Li.mpl_connect("button_press_event", self.mouse_press_callback_Li)
        canvas_Li.mpl_connect("button_release_event", self.mouse_release_callback_Li)
        canvas_Li.mpl_connect("scroll_event", self.mouse_scrolled_callback_Li)
        rectprops = dict(facecolor="black", edgecolor="black", alpha=0.1, fill=True)
        self.RS_Rb = RectangleSelector(
            ax1,
            self.RectangleSelector_callback_Rb,
            drawtype="box",
            useblit=True,
            button=[1, 3],
            minspanx=10,
            minspany=10,
            spancoords="pixels",
            rectprops=rectprops,
        )

        self.RS_Li = RectangleSelector(
            ax0,
            self.RectangleSelector_callback_Li,
            drawtype="box",
            useblit=True,
            button=[1, 3],
            minspanx=10,
            minspany=10,
            spancoords="pixels",
            rectprops=rectprops,
        )

        # GIO-event handlers
        fileRb = gio.File(self.RbParameters["filenames"][-1])
        self.monitorRb = fileRb.monitor_file()
        self.monitorRbID = self.monitorRb.connect("changed", self.file_changedRb)

        fileLi = gio.File("li_recentc.fit")
        self.monitorLi = fileLi.monitor_file()
        self.monitorLiID = self.monitorLi.connect("changed", self.file_changedLi)
开发者ID:rema-git,项目名称:panoptikum,代码行数:104,代码来源:panoptikum.py

示例6: __init__

# 需要导入模块: from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg [as 别名]
# 或者: from matplotlib.backends.backend_gtkagg.FigureCanvasGTKAgg import mpl_connect [as 别名]
    def __init__(self, cube, parent_window):
        """
        A Dendrogram Plot Widget. Designed as a companion to an 
        astrocube.cubeview.CubeViewWidget which should be passed as cube_view
        """
        gtk.VBox.__init__(self, False)

        # Main data structures:         
        self.cube = cube # The cube that this widget's dendrogram represents
        self._data = cube.data # Save a reference to the cube's original data, as we may replace it...
        self.dendrogram = None # The Dendrogram for the cube. To be built later

        # The plot:
        self.fig = matplotlib.figure.Figure()
        self.axes = self.fig.add_subplot(111)
        self.dendro_plot = None # Gets set to a DendrogramPlot object
        self.highlighter_clicked = None # a Highlighter object to color the clicked item
        self.highlighter_hover = None # a Highlighter object to color an item on mouseover
        
        # UI structure:
        canvas = FigureCanvasGTKAgg(self.fig)  # a gtk.DrawingArea
        self.pack_start(canvas)
        self.pack_start(gtk.HSeparator(), False,False)
        
        # # The matplotlib plot toolbar:
        self._plot_toolbar = self._NavigationToolbar(self.cube, canvas, parent_window) # parent_window is needed for the "Save image..." file chooser dialog
        self._plot_toolbar.remove(self._plot_toolbar.get_nth_item(6)) # Remove the "Configure subplots" button which causes rendering issues if used
        self.pack_start(self._plot_toolbar, False, False)
        
        self.pack_start(gtk.HSeparator(), False,False)
        
        # # the dendrogram parameters toolbar:
        self._dendro_toolbar = gtk.HBox()
        
        # # # Minimum flux:
        self._dendro_toolbar.pack_start(gtk.Label("Min flux: "))
        self._min_flux_widget = gtk.SpinButton(digits=1)
        self._min_flux_widget.set_range(np.nanmin(self._data)-0.1,np.nanmax(self._data))
        self._min_flux_widget.set_increments(0.1,1)
        self._min_flux_widget.set_value(np.nanmin(self._data))
        self._dendro_toolbar.pack_start(self._min_flux_widget)
        
        # # # Minimum npix:
        self._dendro_toolbar.pack_start(gtk.Label("Min # pix: "))
        self._min_npix_widget = gtk.SpinButton()
        self._min_npix_widget.set_range(0,999)
        self._min_npix_widget.set_increments(1,5)
        self._min_npix_widget.set_value(0)
        self._dendro_toolbar.pack_start(self._min_npix_widget)
        
        # # # Minimum delta:
        self._dendro_toolbar.pack_start(gtk.Label("Min delta: "))
        self._min_delta_widget = gtk.SpinButton(digits=2)
        self._min_delta_widget.set_range(0,np.nanmax(self._data))
        self._min_delta_widget.set_increments(0.05,0.3)
        self._min_delta_widget.set_value(0)
        self._dendro_toolbar.pack_start(self._min_delta_widget)
        
        # # # Compute button:
        self._compute_button = gtk.Button("Compute")
        self._compute_button.connect("button-press-event", self._compute_btn_clicked)
        self._dendro_toolbar.pack_start(self._compute_button)
        
        # # # Plot style:
        self._dendro_toolbar.pack_start(gtk.Label("Plot style: "))
        self._plot_style_widget = gtk.combo_box_new_text()
        plot_styles = ['rfmax', 'x_mean', 'y_mean', 'z_mean']
        for s in plot_styles:
            self._plot_style_widget.append_text(s)
        self._plot_style_widget.set_active(0)
        self._plot_style_widget.connect("changed", self.setup_plot)
        self._dendro_toolbar.pack_start(self._plot_style_widget)
        
        self.pack_start(self._dendro_toolbar, False, False)
        
        
        # Set up event handling:
        self._is_mouse_down = False # is the mouse button currently pressed?
        self._redraw_all = False # Set this to True to trigger a complete re-draw of the canvas when idle
        self._redraw_highlights = False # Set this True to  re-draw only the highlighted (clicked or hovered) leaves
        canvas.mpl_connect('button_press_event', self._figure_mousedown)
        canvas.mpl_connect('button_release_event', self._figure_mouseup)
        canvas.mpl_connect('motion_notify_event', self._figure_mousemoved)
        canvas.mpl_connect('resize_event', self._figure_resized)
        gtk.idle_add(DendrogramViewWidget._check_redraw, self) # we only want to re re-drawing when the GUI is idle, for maximum interactivity
        
        self._click_notify = []
        self._compute_notify = []
开发者ID:bradenmacdonald,项目名称:astrodendro,代码行数:90,代码来源:dendrowidget.py

示例7: PopUpImage

# 需要导入模块: from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg [as 别名]
# 或者: from matplotlib.backends.backend_gtkagg.FigureCanvasGTKAgg import mpl_connect [as 别名]
class PopUpImage(object):
	def __init__(self, xdata, ydata, xlabel, ylabel, title):
		self.popupwin=gtk.Window()
		self.popupwin.set_size_request(600,550)
		self.popupwin.set_position(gtk.WIN_POS_CENTER)
		self.popupwin.set_border_width(10)
		self.xdata = xdata
		self.ydata = ydata
		vbox = gtk.VBox()
		self.fig=Figure(dpi=100)
		self.ax  = self.fig.add_subplot(111)
		self.canvas  = FigureCanvas(self.fig)
		self.main_figure_navBar = NavigationToolbar(self.canvas, self)
		self.cursor = Cursor(self.ax, color='k', linewidth=1, useblit=True)
		self.canvas.mpl_connect("button_press_event",self.on_press)
		self.ax.set_xlabel(xlabel, fontsize = 18)
		self.ax.set_ylabel(ylabel, fontsize = 18)
		self.ax.set_title(title, fontsize = 18)
		self.ax.plot(self.xdata, self.ydata, 'b-', lw=2)
		
		self.textes = []
		self.plots  = []
		vbox.pack_start(self.main_figure_navBar, False, False, 0)
		vbox.pack_start(self.canvas, True, True, 2)
		self.popupwin.add(vbox)
		self.popupwin.connect("destroy", self.dest)
		self.popupwin.show_all()
	
	def dest(self,widget):
		self.popupwin.destroy()
	
	def on_press(self, event):
		if event.inaxes == self.ax and event.button==3:
			self.clear_notes()
			xc = event.xdata
			#***** Find the closest x value *****
			residuel = self.xdata - xc
			residuel = N.abs(residuel)
			j = N.argmin(residuel)
			#y = self.ydata[i-1:i+1]
			#yc= y.max()
			#j = N.where(self.ydata == yc)
			#j = j[0][0]
			xc= self.xdata[j]
			x_fit = self.xdata[j-3:j+3]
			y_fit = self.ydata[j-3:j+3]
			fitted_param, fitted_data = fit(x_fit, y_fit, xc, True)
			x_fit = N.linspace(x_fit.min(), x_fit.max(), 200)
			y_fit = psdVoigt(fitted_param, x_fit)
			period = fitted_param['xc'].value
			std_err= fitted_param['xc'].stderr
			
			p = self.ax.plot(x_fit, y_fit,'r-')
			p2 = self.ax.axvline(period,color='green',lw=2)
			
			txt=self.ax.text(0.05, 0.9, 'Period = %.4f +- %.4f (nm)'%(period, std_err), transform = self.ax.transAxes, color='red')
			self.textes.append(txt)
			self.plots.append(p[0])
			self.plots.append(p2)
		elif event.inaxes == self.ax and event.button==2:
			dif = N.diff(self.ydata)
			dif = dif/dif.max()
			p3  = self.ax.plot(dif,'r-')
			self.plots.append(p3[0])
		self.canvas.draw()
	
	def clear_notes(self):
		if len(self.textes)>0:
			for t in self.textes:
				t.remove()
		if len(self.plots)>0:
			for p in self.plots:
				p.remove()
		self.textes = []
		self.plots  = []
开发者ID:santoshpanda15,项目名称:DEVA,代码行数:77,代码来源:PopUpWindows.py

示例8: __init__

# 需要导入模块: from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg [as 别名]
# 或者: from matplotlib.backends.backend_gtkagg.FigureCanvasGTKAgg import mpl_connect [as 别名]

#.........这里部分代码省略.........
                    cv2.drawContours(mask,[cont2],0,255,-1)

                    temp2=temp.copy()
                    temp2[mask==0]=0

                    temp3=temp2[br2[1]:br2[1]+br2[3], br2[0]:br2[0]+br2[2]]
                    #dlist.append((charray, br[0]+br2[0], br[1]))

                    if br2[2]>3 and br2[3]>3:
                        #cv2.rectangle(b, (br[0]+br2[0],br[1]+br2[1]), (br[0]+br2[0]+br2[2],br[1]+br2[1]+br2[3]), 100)
                        #dlist.append((charray, br[0]+br2[0], br[1]))
                        rlist2.append(((br[0]+br2[0], br[1]+br2[1]), br2[2], br2[3]))


        return (b,rlist1, rlist2)


    def drawMonitor(self, allconts=False, clearunsaved=False):
        try:
            self.builder.get_object("monitorconfigspace").remove(self.canvasmc)
            self.axismc.clear()
            #self.builder.get_object("mctoolbar").remove(self.mctoolbar)	
        except:
            pass

        #Add cropping
        self.axismc.imshow(self.monimage, cmap=cm.gray) #set scale to 0,255 somehow

        #Maybe this needn't be redefined for every draw - only need draw() but not drawn often anyway
        self.canvasmc=FigureCanvasGTKAgg(self.figuremc)

        self.canvasmc.draw()
        self.canvasmc.show()
        self.canvasmc.mpl_connect('motion_notify_event', self.mcHoverOnImage)
        self.canvasmc.mpl_connect('button_release_event', self.mcCaptureClick)

        self.builder.get_object("monitorconfigspace").pack_start(self.canvasmc, True, True)

        #TODO stop this getting so complicated
        if clearunsaved==False:
            if allconts==False:
                for item in self.rlist:
                    #Structure of rlist:
                    #rlist.append(((br[0]+br2[0], br[1]+br2[1]), br2[2], br2[3]))
                    r=Rectangle(item[0], item[1], item[2], fill=False, color="red")
                    #Rectangle has (lowerleft, width, height)
                    self.axismc.add_patch(r)               
            elif allconts==True:
                #allcontours
                for item in self.rlist1:
                    #Structure of rlist:
                    #rlist.append(((br[0]+br2[0], br[1]+br2[1]), br2[2], br2[3]))
                    r=Rectangle(item[0], item[1], item[2], fill=False, color="blue")
                    #Rectangle has (lowerleft, width, height)
                    self.axismc.add_patch(r)
                for item in self.rlist2:
                    #Structure of rlist:
                    #rlist.append(((br[0]+br2[0], br[1]+br2[1]), br2[2], br2[3]))
                    r=Rectangle(item[0], item[1], item[2], fill=False, color="green")
                    #Rectangle has (lowerleft, width, height)
                    self.axismc.add_patch(r)

        #Always draw saved contours in blue
        for ditem in self.contours:
            item=ditem.ritem
            r=Rectangle(item[0], item[1], item[2], fill=False, color="blue")
开发者ID:jamesmcm,项目名称:MLTest,代码行数:70,代码来源:gui.py

示例9: __init__

# 需要导入模块: from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg [as 别名]
# 或者: from matplotlib.backends.backend_gtkagg.FigureCanvasGTKAgg import mpl_connect [as 别名]
class spectrum_plotter:
	def __init__(self, xs, ys):
		self.xs=xs
		self.ys=ys
		
		self.win = gtk.Window()
		self.win.connect("destroy", lambda x: gtk.main_quit())
		self.win.set_default_size(800,600)
		self.win.set_title("openSpectrometer")

		self.vbox = gtk.VBox()
		self.win.add(self.vbox)
		
		self.fig = Figure(figsize=(5,4), dpi=100)
		self.canvas = FigureCanvas(self.fig)  # a gtk.DrawingArea
		
		self.ax = self.fig.add_subplot(111)
		
		self.canvas.mpl_connect('pick_event', self.onpick)
		
		self.vbox.pack_start(self.canvas)
		self.toolbar = NavigationToolbar(self.canvas, self.win)
		self.hbox = gtk.HBox()
		self.button=gtk.Button('Select this point as lambda max')
		self.button.connect("clicked", self.buttonClick)
		self.hbox.pack_start(self.toolbar)
		self.hbox.pack_start(self.button)
		self.vbox.pack_start(self.hbox, False, False)
		
		self.lastind = 0

		self.text = self.ax.text(0.05, 0.95, 'Datapoint index selected: none',
                            transform=self.ax.transAxes, va='top')
	def plot(self, *args, **kwargs):
		self.ax.plot(*args, **kwargs)
	def plotSelectable(self, *args, **kwargs):
		self.line=self.ax.plot(*args, **kwargs)
	def selectPoint(self, x, y):
		self.selected = self.ax.plot([x],[y], 'o', ms=20, alpha=0.4, 
									   color='yellow', visible=False)
	def show(self):
		self.win.show_all()
		gtk.main()
		return self.lastind
	def buttonClick(self, event):
		self.win.hide_all()
		gtk.main_quit()
	def onpick(self, event):
		if event.artist!=self.line[0]: return True
		
		N = len(event.ind)
		if not N: return True

		if N > 1:
			print '%i points found!' % N

		# the click locations
		x = event.mouseevent.xdata
		y = event.mouseevent.ydata

		dx = numpy.array(x-self.xs[event.ind],dtype=float)
		dy = numpy.array(y-self.ys[event.ind],dtype=float)

		distances = numpy.hypot(dx,dy)
		indmin = distances.argmin()
		dataind = event.ind[indmin]

		self.lastind = dataind
		self.update()

	def update(self):
		if self.lastind is None: return

		dataind = self.lastind
		
		self.selected[0].set_visible(True)
		self.selected[0].set_data(self.xs[dataind], self.ys[dataind])

		# put a user function in here!        
		self.userfunc(dataind)

		self.fig.canvas.draw()

	def userfunc(self,dataind):
		self.text.set_text('datapoint index selected: %d'%dataind)
		print 'No userfunc defined'
		pass
		
开发者ID:nmz787,项目名称:python-spectrometers,代码行数:89,代码来源:helpers.py

示例10: __init__

# 需要导入模块: from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg [as 别名]
# 或者: from matplotlib.backends.backend_gtkagg.FigureCanvasGTKAgg import mpl_connect [as 别名]

#.........这里部分代码省略.........
    def set_focus_cb(self,window,data):
        print "Hej!"

    def window_focus_cb(self,window,data):
        print self.plot.window_size, self.plot.window_pos
        print "window_focus_cb:", self.plot.title
        if window.get_property('is-active'):
            #self.plot.parent.notebook.set_current_page(1)
            print "is-active"
            if self.plot.parent.plt_combo.get_selected_data() != self.plot:
                print "selecting item..."
                self.plot.parent.plt_combo.select_item_by_data(self.plot)
            self.plot.window_size=self.window.get_size()
            self.plot.window_pos=self.window.get_position()

            self.plot.figwidth=self.figure.get_figwidth()
            self.plot.figheight=self.figure.get_figheight()

    def draw(self, items=None, sources=None):
        legend=[]
        print "drawing "+self.plot.title
        def myfmt(x,y): return 'x=%1.6g\ny=%1.6g'%(x,y)
        self.figure.clf()
        self.axes = self.figure.add_subplot(111)
        #self.axes = self.figure.add_axes([0.10,0.10,0.85,0.85])
        #self.figure.subplots_adjust(bottom=0.15, left=0.15)
        self.axes.set_autoscale_on(False)
        self.axes.format_coord = myfmt

    #        self.btn_axes=self.figure.add_axes([0,0,0.1,0.05], frameon=True)
    #        self.cursor_a_btn=Button(self.btn_axes,"A")

        #self.selector=RectangleSelector(self.axes, self.rectangle_cb, useblit=True)
        self.canvas.mpl_connect('button_release_event', self.button_up_cb)

        #self.axes.callbacks.connect("xlim_changed",self.xlim_cb)
        #self.axes.callbacks.connect("ylim_changed",self.ylim_cb)
        self.figure.canvas.mpl_connect('pick_event',self.pick_cb)

        # xaxis=self.axes.get_xaxis()
        # yaxis=self.axes.get_yaxis()

        # xaxis.set_picker(axis_picker)
        # yaxis.set_picker(axis_picker)


        legend=[]

        for line in self.plot.lines:
            self.draw_line(line, draw_canvas=False)
            #source=line.source
            # if line.source is not None:
                # x_data, y_data=line.get_data()

                # line.handle, = self.axes.plot(x_data, y_data,
                                           # color=line.color, ls=line.style,
                                           # linewidth=line.width, picker=5.0)
                                           # #data_clipping=True)
                # line.handle.parent=line
                # legend.append(line.label)
                # #line.handle.set_label(line.label)

        #self.update()


        self.update_legend(draw_canvas=False)
开发者ID:nurbldoff,项目名称:plothole,代码行数:70,代码来源:plot.py

示例11: float

# 需要导入模块: from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg [as 别名]
# 或者: from matplotlib.backends.backend_gtkagg.FigureCanvasGTKAgg import mpl_connect [as 别名]
		new_y = 0
	if new_y > 100:
		new_y = 100
	y_data.append(new_y)
	global frames, start_time
	frames += 1
	if frames % 50 == 0:
		print frames / float(time.time() - start_time)
	return True

pressed = False
def press(event):
	global pressed, y_val
	pressed = True
	y_val = event.ydata
canvas.mpl_connect('button_press_event', press)

def release(event):
	global pressed, y_val
	pressed = False
	y_val = event.ydata
canvas.mpl_connect('button_release_event', release)

def motion(event):
	if pressed and event.inaxes == ax:
		global y_val
		y_val = event.ydata
canvas.mpl_connect('motion_notify_event', motion)

win.add(canvas)
win.show_all()
开发者ID:thetomcraig,项目名称:redwood,代码行数:33,代码来源:client.py

示例12: Figure

# 需要导入模块: from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg [as 别名]
# 或者: from matplotlib.backends.backend_gtkagg.FigureCanvasGTKAgg import mpl_connect [as 别名]
class Figure(gtk.VBox):
    def __init__(self):
        print "Starting up SamFigure!"
        gtk.VBox.__init__(self)
        self.figure = MPLFigure()
        self.canvas = FigureCanvas(self.figure)
        self.canvas.mpl_connect("button_press_event", self.on_click)
        self.ax = self.figure.add_subplot(111)
        self.ax2 = None
        self.mode = TWODPLOT
        self.new_data()
        self.xlabel = ''
        self.y1label = ''
        self.y2label = ''
        self.xsize = 0
        self.ysize = 0
        self.packed = False
        self.count_since_replot=0

        self.set_colors()


    def on_click(self,event):
        # If left button, 
        if event.button==1:
                # screen coordinates of click
                xclick,yclick= event.x, event.y
                top_ax=event.inaxes
                if top_ax is None: return

                # display coordinates of nearest point in ax
                data1=self.ax.transData.transform(\
                    zip(self.listing.getX(),self.listing.getY(1)))
                distances1=\
                    [(x-xclick)**2+(y-yclick)**2 \
                    for (x,y) in data1]
                ind_sel1=numpy.argmin(distances1)
                dist1 = distances1[ind_sel1]
                xsel,ysel= data1[ind_sel1]
                label_ax=self.ax
                label_color='b'

                # if DUAL, then also check ax2 for nearer points
                if self.mode==DUALTWODPLOT:
                    data2=self.ax2.transData.transform(\
                        zip(self.listing.getX(),self.listing.getY(2)))
                    distances2=\
                        [(x-xclick)**2+(y-yclick)**2 \
                        for (x,y) in data2]
                    ind_sel2=numpy.argmin(distances2)
                    dist2 = distances2[ind_sel2]
                    if dist2<dist1:
                        xsel,ysel= data2[ind_sel2]
                        label_color='g'
                        label_ax=self.ax2

                # Clear off old labels
                if hasattr(self,"label_text"):
                    self.label_text.remove()
                    self.label_point.remove()
                    del(self.label_text)
                
                # Coordinates to show ( data coordinates of the selected axes)
                xlabel,ylabel=label_ax.transData.inverted().transform((xsel,ysel))

                # Coordinates to place label (on top set of axes)
                xloc,yloc=top_ax.transData.inverted().transform((xsel,ysel))

                # Label the point
                if (xloc > sum(self.ax.get_xlim())/2): h_align='right'
                else: h_align='left'
                self.label_text=\
                    top_ax.text(xloc,yloc,'({0:.3g},{1:.3g})'\
                        .format(xlabel,ylabel),\
                        backgroundcolor='white', color=label_color,\
                        verticalalignment='bottom', horizontalalignment=h_align,\
                        bbox={'facecolor': 'white', 'boxstyle':
                              'round'},zorder=100 )
                self.label_point,=\
                        top_ax.plot(xloc,yloc,'ro',\
                        zorder=self.label_text.get_zorder()+1)
                self.repaint()

        # Otherwise, just clear off old labels
        else:
            self.label_text.remove()
            self.label_point.remove()
            del(self.label_text)
            self.repaint()

    def replot(self):
        if self.mode == TWODPLOT:
                self.ax.clear()
                self.ax.plot(self.listing.getX(),self.listing.getY(1),self.color1+'.-')
                self.count_since_replot=0
        elif self.mode == DUALTWODPLOT:
                self.ax.clear()
                self.ax2.clear()
                self.ax.plot(self.listing.getX(),self.listing.getY(1),self.color1+'.-')
                self.ax2.plot(self.listing.getX(),self.listing.getY(2),self.color2+'.-')
#.........这里部分代码省略.........
开发者ID:shimolu523,项目名称:lab-quanta,代码行数:103,代码来源:samfigure.py

示例13: on_imagemenuitem_file_save_as_activate

# 需要导入模块: from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg [as 别名]
# 或者: from matplotlib.backends.backend_gtkagg.FigureCanvasGTKAgg import mpl_connect [as 别名]

#.........这里部分代码省略.........
            builder.get_object('checkmenuitem_legend')
        self.menuitem_legend_upper_left = \
            builder.get_object('menuitem_legend_upper_left')
        self.menuitem_legend_upper_right = \
            builder.get_object('menuitem_legend_upper_right')
        self.menuitem_legend_lower_left = \
            builder.get_object('menuitem_legend_lower_left')
        self.menuitem_legend_lower_right = \
            builder.get_object('menuitem_legend_lower_right')
        self.checkmenuitem_logscale = \
            builder.get_object('checkmenuitem_logscale')

        # main toolbar
        self.btn_auto = builder.get_object('btn_auto')

        # restore state of GUI widgets
        self._restore_state()

        # graph in main window
        self.table = builder.get_object('table_graph')
        self.fig = Figure(facecolor='w', tight_layout=True)
        self.ax = self.fig.add_subplot(111)
        self.canvas = FigureCanvas(self.fig)
        self.table.attach(self.canvas, 0, 1, 0, 1)
        # function list
        self.ls_functions = \
            builder.get_object('liststore_functions')
        self.ls_functions.clear()
        self.treeview_functions = \
            builder.get_object('treeview_functions')
        self.cr_toggle_visible = \
            builder.get_object('cr_toggle_visible')
        # catch mouse wheel scroll
        self.canvas.mpl_connect('scroll_event', self.wheel_zoom)
        # catch click and pan
        self.canvas.mpl_connect('button_press_event',
                                self.pan_press)
        self.canvas.mpl_connect('button_release_event',
                                self.pan_release)
        self.canvas.mpl_connect('motion_notify_event',
                                self.pan_motion)
        self.graph_update()

        #
        # file open/save dialogs
        #
        self.fcdialog_open = \
            builder.get_object('filechooserdialog_open')
        self.fcdialog_save = \
            builder.get_object('filechooserdialog_save')
        filefilter = gtk.FileFilter()
        filefilter.set_name(_('FunctionPlot files'))
        filefilter.add_pattern('*.functionplot')
        filefilter.add_pattern('*.FUNCTIONPLOT')
        self.fcdialog_open.add_filter(filefilter)
        self.fcdialog_save.add_filter(filefilter)
        self.dialog_file_open_error = \
            builder.get_object('dialog_file_open_error')
        self.label_open_error = \
            builder.get_object('label_open_error')
        self.dialog_file_save_error = \
            builder.get_object('dialog_file_save_error')
        # use the "My documents" dir in windows
        if win32:
            self.folder = winshell.my_documents()
        else:
开发者ID:gapan,项目名称:functionplot,代码行数:70,代码来源:functionplot.py

示例14: _get_canvas

# 需要导入模块: from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg [as 别名]
# 或者: from matplotlib.backends.backend_gtkagg.FigureCanvasGTKAgg import mpl_connect [as 别名]
 def _get_canvas(self):
     canvas = FigureCanvas(self.figure)
     canvas.mpl_connect("pick_event", self.on_pick)
     return canvas
开发者ID:hon92,项目名称:Algorithm-simulator,代码行数:6,代码来源:plot.py

示例15: XratersWindow

# 需要导入模块: from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg [as 别名]
# 或者: from matplotlib.backends.backend_gtkagg.FigureCanvasGTKAgg import mpl_connect [as 别名]

#.........这里部分代码省略.........
        
        """ 
        return self.builder.get_object(name)

    def finish_initializing(self, builder):
        """finish_initalizing should be called after parsing the ui definition
        and creating a XratersWindow object with it in order to finish
        initializing the start of the new XratersWindow instance.

        """
        #get a reference to the builder and set up the signals
        self.builder = builder
        self.builder.connect_signals(self)
        
        #uncomment the following code to read in preferences at start up
        dlg = PreferencesXratersDialog.NewPreferencesXratersDialog()
        self.preferences = dlg.get_preferences()

        #code for other initialization actions should be added here
        self._accFigure = Figure(figsize=(8,6), dpi=72)
        self._accAxis = self._accFigure.add_subplot(111)
        self._accAxis.set_xlabel("time (s)")
        self._accAxis.set_ylabel("acceleration (g)")
        self._lines = self._accAxis.plot(self._time, self._accData[X],
                                         self._time, self._accData[Y],
                                         self._time, self._accData[Z], 
                                         animated=True)
        self._accFigure.legend(self._lines, ("X", "Y", "Z"), 
                             'upper center', 
                             ncol=3)
        self._accAxis.set_xlim(0, 2)
        self._accAxis.set_ylim(-3, 3)
        self._accCanvas = FigureCanvas(self._accFigure)
        self._accCanvas.mpl_connect("draw_event", self._upd_background)
        self.__background = self._accCanvas.copy_from_bbox(self._accAxis.bbox)
        self._accCanvas.show()
        self._accCanvas.set_size_request(600, 400)
        vbMain = self.widget("vboxMain")
        vbMain.pack_start(self._accCanvas, True, True)
        vbMain.show()
        vbMain.reorder_child(self._accCanvas, 2)
        self._setBatteryIndicator(0)
        
    def about(self, widget, data=None):
        """about - display the about box for xraters """
        about = AboutXratersDialog.NewAboutXratersDialog()
        response = about.run()
        about.destroy()

    def preferences(self, widget, data=None):
        """preferences - display the preferences window for xraters """
        prefs = PreferencesXratersDialog.NewPreferencesXratersDialog()
        response = prefs.run()
        if response == gtk.RESPONSE_OK:
            #make any updates based on changed preferences here
            self.preferences = prefs.get_preferences()
        prefs.destroy()

    def quit(self, widget, data=None):
        """quit - signal handler for closing the XratersWindow"""
        self.destroy()

    def on_destroy(self, widget, data=None):
        """on_destroy - called when the XratersWindow is close. """
        #clean up code for saving application state should be added here
        if self.isConnected:
开发者ID:cperezpenichet,项目名称:xraters,代码行数:70,代码来源:xraters.py


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