def setup_mpl_events(self): self.image_axeswidget = AxesWidget(self.image_axes) self.image_axeswidget.connect_event('motion_notify_event', self.image_on_motion) #self.image_axeswidget.connect_event('figure_leave_event', self.on_cursor_leave) #self.image_axeswidget.connect_event('figure_enter_event', self.on_cursor_enter) wx.EVT_RIGHT_DOWN(self.image_figure.canvas, self.on_right_down)
def __init__(self, ax, label, image=None, color='0.85', hovercolor='0.95'): AxesWidget.__init__(self, ax) if image is not None: ax.imshow(image) self.label = ax.text(0.5, 0.5, label, verticalalignment='center', horizontalalignment='center', transform=ax.transAxes) self.cnt = 0 self.observers = {} self.connect_event('button_press_event', self._click) self.connect_event('button_release_event', self._release) self.connect_event('motion_notify_event', self._motion) ax.set_navigate(False) ax.set_axis_bgcolor(color) ax.set_xticks([]) ax.set_yticks([]) # self.ax.spines['top'].set_visible(False) # self.ax.spines['right'].set_visible(False) # self.ax.spines['bottom'].set_visible(False) # self.ax.spines['left'].set_visible(False) self.color = color self.hovercolor = hovercolor self._lastcolor = color
def __init__(self, ax, name, data, wdlength, min_wdlength): """ Create a slider from *valmin* to *valmax* in axes *ax* """ AxesWidget.__init__(self, ax) self.wdlength = wdlength self.min_wdlength = min_wdlength self.voffset = 0 self.xmax = len(data) self.xmin = max(0, self.xmax-self.wdlength) self.ymax = np.max(data.high[self.xmin : self.xmax].values) + self.voffset self.ymin = np.min(data.low[self.xmin : self.xmax].values) - self.voffset self.ax = ax self.cnt = 0 self.observers = {} self.data = data self.name = name ax.set_xlim((self.xmin, self.xmax)) ax.set_ylim((self.ymin, self.ymax)) self.a1, self.a2 = candlestick2(ax, data.open.tolist()[:self.xmax], data.close.tolist()[:self.xmax], data.high.tolist()[:self.xmax], data.low.tolist()[:self.xmax], 0.6, 'r', 'g') self.connect_event('key_release_event', self.keyrelease)
def __init__(self, ax, s='', allowed_chars=None, type=str, **text_kwargs): AxesWidget.__init__(self, ax) self.ax.set_navigate(False) self.ax.set_yticks([]) self.ax.set_xticks([]) self.type = type self.allowed_chars = allowed_chars self.value = self.type(s) self.text = self.ax.text(0.025, 0.2, s, transform=self.ax.transAxes, **text_kwargs) self._cid = None self._cursor = None self._cursorpos = len(self.text.get_text()) self.old_callbacks = {} self.cnt = 0 self.observers = {} self.exit_cnt = 0 self.exit_observers = {} self.connect_event('button_press_event', self._mouse_activate)
def __init__(self, ax, name, data, wdlength, min_wdlength): """ Create a slider from *valmin* to *valmax* in axes *ax* """ AxesWidget.__init__(self, ax) self.wdlength = wdlength self.min_wdlength = min_wdlength self.voffset = 0 self.xmax = len(data) self.xmin = max(0, self.xmax - self.wdlength) self.ymax = np.max( data.high[self.xmin:self.xmax].values) + self.voffset self.ymin = np.min(data.low[self.xmin:self.xmax].values) - self.voffset self.ax = ax self.cnt = 0 self.observers = {} self.data = data self.name = name ax.set_xlim((self.xmin, self.xmax)) ax.set_ylim((self.ymin, self.ymax)) self.a1, self.a2 = candlestick2(ax, data.open.tolist()[:self.xmax], data.close.tolist()[:self.xmax], data.high.tolist()[:self.xmax], data.low.tolist()[:self.xmax], 0.6, 'r', 'g') self.connect_event('key_release_event', self.keyrelease)
class PlotPlotPanel(wx.Panel): def __init__(self, parent, dpi=None, **kwargs): wx.Panel.__init__(self, parent, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, **kwargs) self.ztv_frame = self.GetTopLevelParent() self.figure = Figure(dpi=None, figsize=(1.,1.)) self.axes = self.figure.add_subplot(111) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.Bind(wx.EVT_SIZE, self._onSize) self.axes_widget = AxesWidget(self.figure.gca()) self.axes_widget.connect_event('motion_notify_event', self.on_motion) self.plot_point = None def on_motion(self, evt): if evt.xdata is not None: xarg = np.abs(self.ztv_frame.plot_panel.plot_positions - evt.xdata).argmin() ydata = self.ztv_frame.plot_panel.plot_im_values[xarg] self.ztv_frame.plot_panel.cursor_position_textctrl.SetValue('{0:.6g},{1:.6g}'.format(evt.xdata, ydata)) if self.plot_point is None: self.plot_point, = self.axes.plot([evt.xdata], [ydata], 'xm') else: self.plot_point.set_data([[evt.xdata], [ydata]]) self.figure.canvas.draw() def _onSize(self, event): self._SetSize() def _SetSize(self): pixels = tuple(self.GetClientSize()) self.SetSize(pixels) self.canvas.SetSize(pixels) self.figure.set_size_inches(float(pixels[0])/self.figure.get_dpi(), float(pixels[1])/self.figure.get_dpi())
def __init__(self, ax, is_closed=False, max_points=None, line_kw=None, circle_kw=None): AxesWidget.__init__(self, ax) self.visible = True self.observers = {} self.release_observers = {} self.cid = 0 self.xs = [] self.ys = [] kw = line_kw if line_kw is not None else {} self.line = Line2D(self.xs, self.ys, **kw) self.ax.add_artist(self.line) self.circle_kw = dict(radius=5, alpha=0.5) if circle_kw: self.circle_kw.update(circle_kw) self.circles = [] self.is_closed = is_closed self.max_points = max_points self.moving_ci = None self.connect_event('button_press_event', self._press) self.connect_event('button_release_event', self._release) self.connect_event('motion_notify_event', self._motion)
def __init__(self, ax, horizOn=True, vertOn=True, useblit=False, **lineprops): """ Add a cursor to *ax*. If ``useblit=True``, use the backend- dependent blitting features for faster updates (GTKAgg only for now). *lineprops* is a dictionary of line properties. .. plot :: mpl_examples/widgets/cursor.py """ # TODO: Is the GTKAgg limitation still true? AxesWidget.__init__(self, ax) self.connect_event('motion_notify_event', self.onmove) self.connect_event('draw_event', self.clear) self.visible = True self.horizOn = horizOn self.vertOn = vertOn self.useblit = useblit and self.canvas.supports_blit self.moved = False if self.useblit: lineprops['animated'] = True self.lineh = ax.axhline(ax.get_ybound()[0], visible=False, **lineprops) self.linev = ax.axvline(ax.get_xbound()[0], visible=False, **lineprops) self.background = None self.needclear = False
def __init__(self, ax, onselect, useblit=False, button=None, state_modifier_keys=None): AxesWidget.__init__(self, ax) self.visible = True self.onselect = onselect self.useblit = useblit and self.canvas.supports_blit self.connect_default_events() self.state_modifier_keys = dict(move=' ', clear='escape', square='shift', center='control') self.state_modifier_keys.update(state_modifier_keys or {}) self.background = None self.artists = [] if isinstance(button, int): self.validButtons = [button] else: self.validButtons = button # will save the data (position at mouseclick) self.eventpress = None # will save the data (pos. at mouserelease) self.eventrelease = None self._prev_event = None self.state = set()
def __init__(self, ax, scrollbarSize=1.0, thumbSize=0.3, position=0.0, callback=None): AxesWidget.__init__(self, ax) self.ax = ax self.ax.get_xaxis().set_visible(False) self.ax.get_yaxis().set_visible(False) self.ax.set_ylim((0, scrollbarSize + thumbSize)) self.scrollbarSize = scrollbarSize self.scrollPage = (self.scrollbarSize / 20) self.thumbSize = thumbSize self.position = position self.callback = callback xx = self.ax.get_xlim() width = xx[1]-xx[0] height = self.thumbSize self.thumb = patches.Rectangle((xx[0], self.position), width, height, alpha=1.0, color='gray') self.ax.add_patch(self.thumb) self.bbox = self.thumb.get_bbox() self.drag_active = False self.drag_startY = 0 self.ax.edgecolor = 'blue' self.ax.set_facecolor('0.90') self.connect_event('button_press_event', self.onPress) self.connect_event('button_release_event', self.onRelease) self.connect_event('motion_notify_event', self.onMotion)
def __init__( self, parent, useblit=False, snapDist=5, snapType={ 'Segments': False, 'SegmentEnds': False, 'Origin': True, 'Grid': True, 'Centers': True }): self.parent = parent self.doc = self.parent.doc self.ax = self.parent.plt self.canvas = self.parent.canvas self.snapDist = snapDist self.snapType = self.setSnapType(snapType) SnaptoCursor.snapping = False AxesWidget.__init__(self, self.ax) self.connect_event('motion_notify_event', self.onmove) self.connect_event('draw_event', self.clear) self.useblit = useblit and self.canvas.supports_blit self.cursor, = self.ax.plot(0, 0, 'rx', animated=self.useblit) self.cursor.set_visible(False) self.visible = True self.background = None self.needclear = False
def __init__(self, ax, is_closed=False, max_points=None, grows=True, shrinks=True, line_kw=None, circle_kw=None): AxesWidget.__init__(self, ax) Actionable.__init__(self) self.visible = True self.observers = {} self.release_observers = {} self.cid = 0 self.xs = [] self.ys = [] kw = line_kw if line_kw is not None else {} self.line, = self.ax.plot(self.xs, self.ys, **kw) self.circle_kw = circle_kw if circle_kw is not None else {} self.circles = [] self.moving_ci = None self.is_closed = is_closed self.max_points = max_points self._lclick_cids = None self.grows = grows self._rclick_cids = None self._can_shrink = False self.shrinks = shrinks self.connect_event('button_press_event', self._left_press), self.connect_event('button_release_event', self._release), self.connect_event('motion_notify_event', self._motion),
def __init__(self, ax, labels, active=0, activecolor='blue'): """ Add radio buttons to :class:`matplotlib.axes.Axes` instance *ax* *labels* A len(buttons) list of labels as strings *active* The index into labels for the button that is active *activecolor* The color of the button when clicked """ AxesWidget.__init__(self, ax) self.activecolor = activecolor self.value_selected = None ax.set_xticks([]) ax.set_yticks([]) ax.set_navigate(False) dy = 1. / (len(labels) + 1) ys = np.linspace(1 - dy, dy, len(labels)) cnt = 0 axcolor = ax.get_facecolor() # scale the radius of the circle with the spacing between each one circle_radius = (dy / 2) - 0.01 # defaul to hard-coded value if the radius becomes too large if (circle_radius > 0.05): circle_radius = 0.05 self.labels = [] self.circles = [] for y, label in zip(ys, labels): t = ax.text(0.25, y, label, transform=ax.transAxes, horizontalalignment='left', verticalalignment='center') if cnt == active: self.value_selected = label facecolor = activecolor else: facecolor = axcolor p = Circle(xy=(0.15, y), radius=circle_radius, edgecolor='black', facecolor=facecolor, transform=ax.transAxes) self.labels.append(t) self.circles.append(p) ax.add_patch(p) cnt += 1 self.connect_event('button_press_event', self._clicked) self.cnt = 0 self.observers = {}
def __init__(self, ax, labels, active=0, activecolor='blue', size=49, orientation="vertical", **kwargs): """ Add radio buttons to an `~.axes.Axes`. Parameters ---------- ax : `~matplotlib.axes.Axes` The axes to add the buttons to. labels : list of str The button labels. active : int The index of the initially selected button. activecolor : color The color of the selected button. size : float Size of the radio buttons orientation : str The orientation of the buttons: 'vertical' (default), or 'horizontal'. Further parameters are passed on to `Legend`. """ AxesWidget.__init__(self, ax) self.activecolor = activecolor axcolor = ax.get_facecolor() self.value_selected = None ax.set_xticks([]) ax.set_yticks([]) ax.set_navigate(False) circles = [] for i, label in enumerate(labels): if i == active: self.value_selected = label facecolor = activecolor else: facecolor = axcolor p = ax.scatter([], [], s=size, marker="o", edgecolor='black', facecolor=facecolor) circles.append(p) if orientation == "horizontal": kwargs.update(ncol=len(labels), mode="expand") kwargs.setdefault("frameon", False) self.box = ax.legend(circles, labels, loc="center", **kwargs) self.labels = self.box.texts self.circles = self.box.legendHandles for c in self.circles: c.set_picker(5) self.cnt = 0 self.observers = {} self.connect_event('pick_event', self._clicked)
def __init__(self, ax, labels, marker='$-$', keep_color=False, size=49, orientation="vertical", **kwargs): """ Add radio buttons to an `~.axes.Axes`. Parameters ---------- ax : `~matplotlib.axes.Axes` The axes to add the buttons to. labels : list of str The button labels... marker : str Changes can be made according to matplotlib.markers selection keep_color : Bool if True button press does nothing else button color turns on/off size : float Size of the radio buttons orientation : str The orientation of the buttons: 'vertical' (default), or 'horizontal'. Further parameters are passed on to `Legend`. """ AxesWidget.__init__(self, ax) self.value_selected = None self.keep_color = keep_color ax.set_xticks([]) ax.set_yticks([]) ax.set_navigate(False) self.circles = [] for i, label in enumerate(labels): if i: self.value_selected = label facecolor = 'C' + str(i % 10) else: facecolor = 'C' + str(i % 10) p = ax.scatter([], [], s=size, marker=marker, edgecolor='black', facecolor=facecolor) self.circles.append(p) if orientation == "horizontal": kwargs.update(ncol=len(labels), mode="expand") kwargs.setdefault("frameon", False) self.box = ax.legend(self.circles, labels, loc="center", **kwargs) self.labels = self.box.texts self.circles = self.box.legendHandles for c in self.circles: c.set_picker(5) self.cnt = 0 self.observers = {} self.connect_event('pick_event', self._clicked)
def __init__(self, ax, txt): AxesWidget.__init__(self, ax) self.t = txt self.connect_event('button_press_event', self._clicked) self._prev_color = '' self.cnt = 0 self.observers = {} ax.set_navigate(False)
def setup_mpl_events(self): self.image_axeswidget = AxesWidget(self.image_axes) self.image_axeswidget.connect_event('motion_notify_event', self.image_on_motion) self.image_axeswidget.connect_event('figure_leave_event', self.on_cursor_leave) self.image_axeswidget.connect_event('figure_enter_event', self.on_cursor_enter) self.image_axeswidget.connect_event('button_press_event', self.image_on_click)
def __init__(self, parent, dpi=None, **kwargs): wx.Panel.__init__(self, parent, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, **kwargs) self.ztv_frame = self.GetTopLevelParent() self.figure = Figure(dpi=None, figsize=(1., 1.)) self.axes = self.figure.add_subplot(111) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.Bind(wx.EVT_SIZE, self._onSize) self.axes_widget = AxesWidget(self.figure.gca()) self.axes_widget.connect_event('motion_notify_event', self.on_motion) self.plot_point = None
def __init__(self, vertex_list, ax, channels, name=None): AxesWidget.__init__(self, ax) self.channels = channels self.name = name self.region = '?' self.gate_type = self.__class__.__name__ self._spawned_vertex_list = [vert.spawn(self.ax, channels) for vert in vertex_list] [svertex.add_callback(self.handle_vertex_event) for svertex in self._spawned_vertex_list] self.create_artist() self.activate()
def __init__(self, ax, callback=None, useblit=True): AxesWidget.__init__(self, ax) self.useblit = useblit and self.canvas.supports_blit self.verts = [] self.drawing = False self.line = None self.callback = callback self.last_click_time = time.time() self.connect_event('button_press_event', self.onpress) self.connect_event('motion_notify_event', self.onmove)
def __init__(self, ax, pos, **kwargs): AxesWidget.__init__(self, ax) self.cursor = Cursor(ax, useblit=True, **kwargs) self.connect_event('button_press_event', self._update) self.connect_event('button_release_event', self._update) self.cnt = 0 self.observers = {} self.drag_active = False self.pos = pos
def __init__(self, ax, lineprops=None, **kwargs): """ Add a bar to *ax*. *lineprops* is a dictionary of line properties. """ AxesWidget.__init__(self, ax) if lineprops is None: lineprops = dict(color='#e66101', lw=2) self.linev = ax.axvline(0, 0, 1, visible=False, **lineprops) self.background = None self.needclear = False self.connect_event('draw_event', self.clear)
def __init__(self, ax, x, y, horizOn=True, vertOn=True, useblit=False, **lineprops): AxesWidget.__init__(self, ax) self.connect_event('motion_notify_event', self.onmove) self.connect_event('button_press_event', self.onclick) self.connect_event('draw_event', self.clear) self.visible = True self.horizOn = horizOn self.vertOn = vertOn self.useblit = useblit and self.canvas.supports_blit if self.useblit: lineprops['animated'] = True self.lineh = ax.axhline(ax.get_ybound()[0], visible=False, **lineprops) self.linev = ax.axvline(ax.get_xbound()[0], visible=False, **lineprops) self.marker, = ax.plot(0, 0, marker='o', visible=False, color='red', markersize=4) self.background = None self.needclear = False self.x = x self.y = y # text location in axes coords self.txt = ax.text(0.25, 0.95, '', transform=ax.transAxes, bbox=dict(boxstyle="round", ec=(1., 0.5, 0.5), fc=(1., 0.8, 0.8))) self.gradtxt = ax.text(0.25, 0.8, '', transform=ax.transAxes, bbox=dict(boxstyle="round", ec=(1., 0.5, 0.5), fc=(1., 0.8, 0.8))) self.positions = [] self.lines = []
def __init__(self, ax, pixels): AxesWidget.__init__(self, ax) self.pixels = pixels self.image = self.ax.imshow(self.pixels, aspect='auto', interpolation='none', vmin=0, vmax=1) self.l = None self.observers = {} self.cid = 0
def __init__(self, ax, radius, **circprops): AxesWidget.__init__(self, ax) self.connect_event('motion_notify_event', self.onmove) self.connect_event('draw_event', self.storebg) circprops['animated'] = True circprops['radius'] = radius self.circ = plt.Circle((0,0), **circprops) self.ax.add_artist(self.circ) self.background = None
def __init__(self, ax, pixels): AxesWidget.__init__(self, ax) Actionable.__init__(self) self.pixels = pixels self.image = self.ax.imshow(self.pixels, aspect='auto', interpolation='none', vmin=0, vmax=1) self.l = None self.observers = {} self.cid = 0
def __init__(self, ax, radius, **circprops): AxesWidget.__init__(self, ax) self.connect_event('motion_notify_event', self.onmove) self.connect_event('draw_event', self.storebg) circprops['animated'] = True circprops['radius'] = radius self.circ = plt.Circle((0, 0), **circprops) self.ax.add_artist(self.circ) self.background = None
def __init__(self, ax, track_x=True, track_y=True, show_coord=True, text_format="(%.2f, %.2f)", col='green', useblit=True, show_drag=False, **lineprops): AxesWidget.__init__(self, ax) self.connect_event('motion_notify_event', self.onmove) self.connect_event('draw_event', self.clear) if show_drag: self.connect_event('button_press_event', self.on_press) self.connect_event('button_release_event', self.on_release) self.visible = True self.horizOn = track_y self.vertOn = track_x self.drag_on = show_drag self.show_coord = show_coord self.text_format = text_format self.useblit = useblit and self.canvas.supports_blit if self.useblit: lineprops['animated'] = True if 'color' not in lineprops: lineprops['color'] = col self.lineh = ax.axhline(ax.get_ybound()[0], visible=False, **lineprops) self.linev = ax.axvline(ax.get_xbound()[0], visible=False, **lineprops) self.text = ax.text(ax.get_xbound()[0], ax.get_ybound()[0], '', fontsize=8, color=col, visible=False) self.area = patches.Rectangle((0, 0), 0, 0, fc=col, ec=None, alpha=0.2, visible=False) self.ax.add_patch(self.area) self._press = None self.background = None self.needclear = False
def __init__(self, ax, label, image=None, color='0.85', hovercolor='0.95'): """ Parameters ---------- ax : matplotlib.axes.Axes The :class:`matplotlib.axes.Axes` instance the button will be placed into. label : str The button text. Accepts string. image : array, mpl image, Pillow Image The image to place in the button, if not *None*. Can be any legal arg to imshow (numpy array, matplotlib Image instance, or Pillow Image). color : color The color of the button when not activated hovercolor : color The color of the button when the mouse is over it """ AxesWidget.__init__(self, ax) if image is not None: ax.imshow(image) self.label = ax.text(0.5, 0.5, label, verticalalignment='center', horizontalalignment='center', transform=ax.transAxes, fontsize=13) self.cnt = 0 self.observers = {} self.connect_event('button_press_event', self._click) self.connect_event('button_release_event', self._release) #self.connect_event('motion_notify_event', self._motion) ax.set_navigate(False) ax.set_facecolor(color) ax.set_xticks([]) ax.set_yticks([]) self.isIterating = False self.deleteFunc = None self.color = color self.hovercolor = hovercolor self._lastcolor = color
def __init__(self, ax, name, label, valmin, valmax, valinit=0.5, width=1, valfmt='%1.2f', time_index = None, closedmin=True, closedmax=True, slidermin=None, slidermax=None, drag_enabled=True, **kwargs): """ Create a slider from *valmin* to *valmax* in axes *ax* *valinit* The slider initial position *label* The slider label *valfmt* Used to format the slider value *closedmin* and *closedmax* Indicate whether the slider interval is closed *slidermin* and *slidermax* Used to constrain the value of this slider to the values of other sliders. additional kwargs are passed on to ``self.poly`` which is the :class:`matplotlib.patches.Rectangle` which draws the slider knob. See the :class:`matplotlib.patches.Rectangle` documentation valid property names (e.g., *facecolor*, *edgecolor*, *alpha*, ...) """ AxesWidget.__init__(self, ax) self.label = ax.text(-0.02, 0.5, label, transform=ax.transAxes, verticalalignment='center', horizontalalignment='right') self.valtext = None self.poly = None self.reinit(valmin, valmax, valinit, width, valfmt, time_index, **kwargs) self.name = name self.cnt = 0 self.closedmin = closedmin self.closedmax = closedmax self.slidermin = slidermin self.slidermax = slidermax self.drag_active = False self.drag_enabled = drag_enabled self.observers = {} ax.set_yticks([]) #ax.set_xticks([]) # disable ticks ax.set_navigate(False) self._connect()
def __init__(self, ax, oncreated=None, lineprops=None): AxesWidget.__init__(self, ax) self.oncreated = oncreated self.verts = None if lineprops is None: lineprops = dict() self.line = pl.Line2D([], [], **lineprops) self.line.set_visible(False) self.ax.add_line(self.line) self.connect_event('button_press_event', self.onpress) # self.connect_event('button_release_event', self.onrelease) self.connect_event('motion_notify_event', self.onmove)
def link_ngl_wdgt_to_ax_pos(ax, pos, ngl_widget): from matplotlib.widgets import AxesWidget from scipy.spatial import cKDTree r""" Initial idea for this function comes from @arose, the rest is @gph82 and @clonker """ kdtree = cKDTree(pos) #assert ngl_widget.trajectory_0.n_frames == pos.shape[0] x, y = pos.T lineh = ax.axhline(ax.get_ybound()[0], c="black", ls='--') linev = ax.axvline(ax.get_xbound()[0], c="black", ls='--') dot, = ax.plot(pos[0, 0], pos[0, 1], 'o', c='red', ms=7) ngl_widget.isClick = False def onclick(event): linev.set_xdata((event.xdata, event.xdata)) lineh.set_ydata((event.ydata, event.ydata)) data = [event.xdata, event.ydata] _, index = kdtree.query(x=data, k=1) dot.set_xdata((x[index])) dot.set_ydata((y[index])) ngl_widget.isClick = True ngl_widget.frame = index def my_observer(change): r"""Here comes the code that you want to execute """ ngl_widget.isClick = False _idx = change["new"] try: dot.set_xdata((x[_idx])) dot.set_ydata((y[_idx])) except IndexError as e: dot.set_xdata((x[0])) dot.set_ydata((y[0])) print("caught index error with index %s (new=%s, old=%s)" % (_idx, change["new"], change["old"])) # Connect axes to widget axes_widget = AxesWidget(ax) axes_widget.connect_event('button_release_event', onclick) # Connect widget to axes ngl_widget.observe(my_observer, "frame", "change")
class MPLFigureEditor(BasicEditorFactory): klass = _MPLFigureEditor def setup_mpl_events(self): self.image_axeswidget = AxesWidget(self.image_axes) self.image_axeswidget.connect_event('motion_notify_event', self.image_on_motion) #self.image_axeswidget.connect_event('figure_leave_event', self.on_cursor_leave) #self.image_axeswidget.connect_event('figure_enter_event', self.on_cursor_enter) wx.EVT_RIGHT_DOWN(self.image_figure.canvas, self.on_right_down) def on_right_down(self, event): if self.image_popup_menu is None: menu = wx.Menu() def image_on_motion(self, event): if event.xdata is None or event.ydata is None: return
def __init__(self, parent, dpi=None, **kwargs): wx.Panel.__init__(self, parent, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, **kwargs) self.ztv_frame = self.GetTopLevelParent() self.figure = Figure(dpi=None, figsize=(1.,1.)) self.axes = self.figure.add_subplot(111) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.Bind(wx.EVT_SIZE, self._onSize) self.axes_widget = AxesWidget(self.figure.gca()) self.axes_widget.connect_event('motion_notify_event', self.on_motion) self.plot_point = None
def __init__(self, coordinates, ax, callback_list=None): AxesWidget.__init__(self, ax) self.add_callback(callback_list) self.selected = False self.coordinates = tuple([c if c is not None else 0.5 for c in coordinates]) # Replaces all Nones with 0.5 self.trackx = coordinates[0] is not None self.tracky = coordinates[1] is not None if not self.trackx and not self.tracky: raise Exception('Mode not supported') self.artist = None self.create_artist() self.connect_event('pick_event', lambda event: self.pick(event)) self.connect_event('motion_notify_event', lambda event: self.motion_notify_event(event)) # self.connect_event('button_press_event', lambda event : self.mouse_button_press(event)) self.connect_event('button_release_event', lambda event: self.mouse_button_release(event))
def __init__(self, ax, label, valmin, valmax, valinit=0.5, valfmt='%1.2f', closedmin=True, closedmax=True, slidermin=None, slidermax=None, dragging=True, **kwargs): AxesWidget.__init__(self, ax) self.valmin = valmin self.valmax = valmax self.val = valinit self.valinit = valinit self.poly = ax.axhspan(valmin, valinit, 0, 1, **kwargs) self.hline = ax.axhline(valinit, 0, 1, color='r', lw=1) self.valfmt = valfmt ax.set_xticks([]) ax.set_ylim((valmin, valmax)) ax.set_yticks([]) ax.set_navigate(False) self.connect_event('button_press_event', self._update) self.connect_event('button_release_event', self._update) if dragging: self.connect_event('motion_notify_event', self._update) self.label = ax.text(0.5, 1.03, label, transform=ax.transAxes, verticalalignment='center', horizontalalignment='center') self.valtext = ax.text(0.5, -0.03, valfmt % valinit, transform=ax.transAxes, verticalalignment='center', horizontalalignment='center') self.cnt = 0 self.observers = {} self.closedmin = closedmin self.closedmax = closedmax self.slidermin = slidermin self.slidermax = slidermax self.drag_active = False
def __init__(self, ax, name, wdlength, min_wdlength): """ Create a slider from *valmin* to *valmax* in axes *ax* """ AxesWidget.__init__(self, ax) self.name = name self.wdlength = wdlength self.min_wdlength = min_wdlength self.voffset = 0 self.connect() self.plotters = { } # 当前显示的范围。 #self.xmax = len(data) #self.xmin = max(0, self.xmax-self.wdlength) #self.ymax = np.max(data.high[self.xmin : self.xmax].values) + self.voffset #self.ymin = np.min(data.low[self.xmin : self.xmax].values) - self.voffset self.cnt = 0 self.observers = {}
def test_just_runs_and_exits_gracefully(self): from matplotlib.widgets import AxesWidget from ipywidgets.widgets import HBox ifig = plt.figure() iax = plt.gca() nglwdg = nglview.demo() mplw = AxesWidget(iax) box_out = visualize._box_me((ifig, iax, nglwdg, mplw)) assert isinstance(box_out, HBox) assert None is visualize._box_me((ifig, iax, nglwdg, mplw, 1))
def __init__(self, ax, dx_frac=0.05, **rect_kw): self.rects = {} # AxesWidget sets active=True, so rects needs to exist AxesWidget.__init__(self, ax) self.visible = True self.observers = {} self.cid = 0 self.active_pick = None kw = dict( facecolor='gray', edgecolor='none', alpha=0.5, picker=5, ) kw.update(rect_kw) self._make_rects(dx_frac, kw) self.connect_event('pick_event', self._pick), self.connect_event('button_release_event', self._release), self.connect_event('motion_notify_event', self._motion),
def __init__(self, ax, label, image=None, color="0.85", hovercolor="0.95"): AxesWidget.__init__(self, ax) if image is not None: ax.imshow(image) self.label = ax.text( 0.5, 0.5, label, verticalalignment="center", horizontalalignment="center", transform=ax.transAxes ) self.cnt = 0 self.observers = {} self.connect_event("button_press_event", self._click) self.connect_event("button_release_event", self._release) self.connect_event("motion_notify_event", self._motion) ax.set_navigate(False) ax.set_axis_bgcolor(color) ax.set_xticks([]) ax.set_yticks([]) self.color = color self.hovercolor = hovercolor self._lastcolor = color
def mpl_setup(self): self.axes_widget = AxesWidget(self.figure.gca()) self.axes_widget.connect_event('button_press_event', self.on_click) self.axes_widget.connect_event('scroll_event', self.on_scroll)
def __init__(self, ax, label, valmin, valmax, valinit=0.5, valfmt='%1.2f', closedmin=True, closedmax=True, slidermin=None, slidermax=None, dragging=True, **kwargs): """ Create a slider from *valmin* to *valmax* in axes *ax* *valinit* The slider initial position *label* The slider label *valfmt* Used to format the slider value *closedmin* and *closedmax* Indicate whether the slider interval is closed *slidermin* and *slidermax* Used to constrain the value of this slider to the values of other sliders. additional kwargs are passed on to ``self.poly`` which is the :class:`matplotlib.patches.Rectangle` which draws the slider knob. See the :class:`matplotlib.patches.Rectangle` documentation valid property names (e.g., *facecolor*, *edgecolor*, *alpha*, ...) """ AxesWidget.__init__(self, ax) self.valmin = valmin self.valmax = valmax self.val = valinit self.valinit = valinit self.poly = ax.axhspan(valmin,valinit,0,1, **kwargs) self.hline = ax.axhline(valinit,0,1, color='r', lw=1) self.valfmt=valfmt ax.set_yticks([]) ax.set_ylim((valmin, valmax)) ax.set_xticks([]) ax.set_navigate(False) self.connect_event('button_press_event', self._update) self.connect_event('button_release_event', self._update) if dragging: self.connect_event('motion_notify_event', self._update) self.label = ax.text(0.5, 1.02, label, transform=ax.transAxes, verticalalignment='bottom', horizontalalignment='center') self.valtext = ax.text(0.5, -0.02, valfmt%valinit, transform=ax.transAxes, verticalalignment='top', horizontalalignment='center') self.cnt = 0 self.observers = {} self.closedmin = closedmin self.closedmax = closedmax self.slidermin = slidermin self.slidermax = slidermax self.drag_active = False
def __init__(self, ax, s='', allowed_chars=None, type=str, enter_callback=None, **text_kwargs): """ Editable text box Creates a mouse-click callback such that clicking on the text box will activate the cursor. *WARNING* Activating a textbox will remove all other key-press bindings! They'll be stored in TextBox.old_callbacks and restored when TextBox.end_text_entry() is called. The default widget assumes only numerical data and will not allow text entry besides numerical characters and ('e','-','.') Parameters ---------- *ax* : :class:`matplotlib.axes.Axes` The parent axes for the widget *s* : str The initial text of the TextBox. *allowed_chars* : seq TextBox will only respond if event.key in allowed_chars. Defaults to None, which accepts anything. *type* : type Construct self.value using this type. self.value is only updated if self.type(<text>) succeeds. *enter_callback* : function A function of one argument that will be called with TextBox.value passed in as the only argument when enter is pressed *text_kwargs* : Additional keywork arguments are passed on to self.ax.text() Call :meth:`on_onchanged` to connect to TextBox updates """ AxesWidget.__init__(self, ax) self.ax.set_navigate(False) self.ax.set_yticks([]) self.ax.set_xticks([]) self.type = type self.allowed_chars = allowed_chars self.value = self.type(s) self.text = self.ax.text(0.025, 0.2, s, transform=self.ax.transAxes, **text_kwargs) self.enter_callback = enter_callback self._cid = None self._cursor = None self._cursorpos = len(self.text.get_text()) self.old_callbacks = {} self.cnt = 0 self.observers = {} self.connect_event('button_press_event', self._mouse_activate)
class AtmosViewer(HasTraits): central_wavenumber = CFloat(1000) bandwidth = CFloat(10) selected_line_wavenumber = Float(-1.) figure = Instance(Figure, ()) all_on = Button() all_off = Button() selected_molecules = List(editor=CheckListEditor(values=molecules.keys(), cols=2, format_str = '%s')) mplFigureEditor = MPLFigureEditor() trait_view = View(VGroup(Item('figure', editor=mplFigureEditor, show_label=False), HGroup('10', VGroup('40', Item(name='central_wavenumber', editor=TextEditor(auto_set=False, enter_set=True)), Item(name='bandwidth', editor=TextEditor(auto_set=False, enter_set=True)), HGroup(Item(name='selected_line_wavenumber'), show_border=True), show_border=True), HGroup( VGroup('20', Heading("Molecules"), Item(name='all_on', show_label=False), Item(name='all_off', show_label=False)), Item(name='selected_molecules', style='custom', show_label=False), show_border=True), '10'), '10'), handler=MPLInitHandler, resizable=True, title=title, width=size[0], height=size[1]) def __init__(self): super(AtmosViewer, self).__init__() self.colors = {'telluric':'black', 'orders':'black'} self.molecules = molecules self.selected_molecules = [] orders_filename = resource_filename(__name__, 'orders.txt') self.texes_orders = pandas.io.parsers.read_csv(orders_filename, sep='\t', header=None, skiprows=3) atmos_filename = resource_filename(__name__, 'atmos.txt.gz') self.atmos = pandas.io.parsers.read_csv(gzip.open(atmos_filename, 'r'), sep='\t', skiprows=7, index_col='# wn') self.molecule_lookup_points = {} # keys are e.g. 'O3', with a dict of {'wn':..., 'y':...} self.axes = self.figure.add_subplot(111) self.axes.plot(self.atmos.index, self.atmos['trans1mm'], color=self.colors['telluric']) self.axes.plot(self.atmos.index, self.atmos['trans4mm'], color=self.colors['telluric']) for i in self.texes_orders.index: self.axes.plot(self.texes_orders.ix[i].values, [0.05, 0.07], color=self.colors['orders']) self.axes.set_xlim(self.central_wavenumber - self.bandwidth / 2., self.central_wavenumber + self.bandwidth / 2.) self.axes.set_ylim(0, 1.0) self.axes.set_xlabel('Wavenumber (cm-1)') self.axes.xaxis.set_major_formatter(FormatStrFormatter('%6.1f')) self.onclick_connected = False # I don't understand why I can't do the connection here. self.selected_line = None self.selected_line_text = None def on_click(self, event): if event.xdata is None or event.ydata is None: return if self.selected_line in self.axes.lines: self.axes.lines.pop(self.axes.lines.index(self.selected_line)) if self.selected_line_text in self.axes.texts: self.axes.texts.remove(self.selected_line_text) self.selected_line = None self.selected_line_text = None self.selected_line_wavenumber = -1 if len(self.molecule_lookup_points) == 0: return closest = {'name':None, 'wn':-1., 'dist':9e9} for cur_molecule in self.molecule_lookup_points: wn = self.molecule_lookup_points[cur_molecule]['wn'] ys = self.molecule_lookup_points[cur_molecule]['y'] dist_x2 = (wn - event.xdata)**2 xlim = self.axes.get_xlim() scale = ((xlim[1] - xlim[0]) / # this is like wavenumbers/inch (self.axes.figure.get_figwidth() * self.axes.get_position().bounds[2])) dist_y2 = ((ys - event.ydata)*(self.axes.figure.get_figheight() * self.axes.get_position().bounds[3]) * scale)**2 dist = np.sqrt(dist_x2 + dist_y2) if dist.min() < closest['dist']: closest = {'name':cur_molecule, 'wn':wn[dist.argmin()], 'dist':dist.min()} self.selected_line_wavenumber = closest['wn'] self.selected_line = self.axes.plot([closest['wn'], closest['wn']], [0, 1], '-.', color='black')[0] self.selected_line_text = self.axes.annotate(closest['name'] + ('%11.5f' % closest['wn']), (closest['wn'], 1.03), ha='center', annotation_clip=False) self.redraw() def on_scroll(self, event): self.central_wavenumber += self.bandwidth * event.step def _all_on_fired(self): self.selected_molecules = self.molecules.keys() def _all_off_fired(self): self.selected_molecules = [] def mpl_setup(self): self.axes_widget = AxesWidget(self.figure.gca()) self.axes_widget.connect_event('button_press_event', self.on_click) self.axes_widget.connect_event('scroll_event', self.on_scroll) @on_trait_change("central_wavenumber, bandwidth") def replot_molecular_overplots(self): for i, cur_molecule in enumerate(self.selected_molecules): if self.molecules[cur_molecule]['hitran'] is None: self.molecules[cur_molecule]['hitran'] = pandas.io.parsers.read_csv( gzip.open( self.molecules[cur_molecule]['hitran_filename'], 'r'), skiprows=2) wn = self.molecules[cur_molecule]['hitran']['wavenumber'] intensity = self.molecules[cur_molecule]['hitran']['intensity'] w = ( (wn >= self.central_wavenumber - self.bandwidth / 2.) & (wn <= self.central_wavenumber + self.bandwidth / 2.) ) wn = wn[w] intensity = intensity[w] plot_orders_of_magnitude = 2. max_line_intensity = intensity.max() min_line_intensity = max_line_intensity / 10**plot_orders_of_magnitude wn = wn[intensity >= min_line_intensity] intensity = intensity[intensity >= min_line_intensity] intensity = ((np.log10(intensity) - np.log10(min_line_intensity)) / (np.log10(max_line_intensity) - np.log10(min_line_intensity))) intensity = intensity * 0.1 self.molecule_lookup_points[cur_molecule] = {'wn':wn, 'y':intensity + (i * 0.1) + 0.05} wn = wn.repeat(3) intensity = np.column_stack((np.zeros(len(intensity)), intensity, np.zeros(len(intensity)))).flatten() + (i * 0.1) + 0.05 newplot = self.axes.plot(wn, intensity, self.molecules[cur_molecule]['color']) newtext = self.axes.annotate(cur_molecule, (self.central_wavenumber + self.bandwidth * 0.51, i * 0.1 + 0.065), ha='left', va='center', annotation_clip=False, color=self.molecules[cur_molecule]['color']) if self.molecules[cur_molecule]['plot_lines'] in self.axes.lines: self.axes.lines.pop(self.axes.lines.index(self.molecules[cur_molecule]['plot_lines'])) self.molecules[cur_molecule]['plot_lines'] = None if self.molecules[cur_molecule]['plot_text'] in self.axes.texts: self.axes.texts.remove(self.molecules[cur_molecule]['plot_text']) self.molecules[cur_molecule]['plot_text'] = None self.molecules[cur_molecule]['plot_lines'] = newplot[0] self.molecules[cur_molecule]['plot_text'] = newtext self.redraw() def _selected_molecules_changed(self, old, new): self.replot_molecular_overplots() for cur_molecule in old: if cur_molecule not in new: if self.molecules[cur_molecule]['plot_lines'] in self.axes.lines: self.axes.lines.pop(self.axes.lines.index(self.molecules[cur_molecule]['plot_lines'])) if self.molecules[cur_molecule]['plot_text'] in self.axes.texts: self.axes.texts.remove(self.molecules[cur_molecule]['plot_text']) self.molecules[cur_molecule]['plot_lines'] = None self.molecules[cur_molecule]['plot_text'] = None self.molecule_lookup_points.pop(cur_molecule, None) self.redraw() @on_trait_change("central_wavenumber, bandwidth") def redraw(self): self.axes.set_xlim(self.central_wavenumber - self.bandwidth / 2., self.central_wavenumber + self.bandwidth / 2.) self.axes.set_ylim(0, 1.0) self.figure.canvas.draw()
def set_active(self, active): AxesWidget.set_active(self, active) if active: self.update_background(None)
def __init__(self, ax, orig_line, cropper, **opts): AxesWidget.__init__(self, ax) self.orig_line = orig_line self.cropper = cropper self.line, = ax.plot([], [], transform=self.ax.transAxes, **opts) self.orig_line.on_release(self.update)
def __init__(self, ax, im): AxesWidget.__init__(self, ax) self.cbar = colorbar_factory(ax, im) self.fmt = self.cbar.formatter = OffsetFormatter() self.ax.yaxis.set_visible(True)
class PhotPlotPanel(wx.Panel): def __init__(self, parent, dpi=None, **kwargs): wx.Panel.__init__(self, parent, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, **kwargs) self.ztv_frame = self.GetTopLevelParent() self.figure = Figure(dpi=None, figsize=(1.,1.)) self.axes = self.figure.add_subplot(111) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.Bind(wx.EVT_SIZE, self._onSize) self.axes_widget = AxesWidget(self.figure.gca()) self.axes_widget.connect_event('motion_notify_event', self.on_motion) self.axes_widget.connect_event('button_press_event', self.on_button_press) self.axes_widget.connect_event('button_release_event', self.on_button_release) self.axes_widget.connect_event('figure_leave_event', self.on_cursor_leave) self.button_down = False def on_button_press(self, event): self.aper_names = ['aprad', 'skyradin', 'skyradout'] self.aper_last_radii = np.array([self.ztv_frame.phot_panel.aprad, self.ztv_frame.phot_panel.skyradin, self.ztv_frame.phot_panel.skyradout]) self.button_press_xdata = event.xdata self.cur_aper_index = np.abs(self.aper_last_radii - event.xdata).argmin() self.cur_aper_name = self.aper_names[self.cur_aper_index] # but, click must be within +-N pix to be valid if np.abs(event.xdata - self.aper_last_radii[self.cur_aper_index]) <= 20: self.button_down = True def on_motion(self, event): if self.button_down: if event.xdata is not None: if self.cur_aper_name == 'aprad': self.ztv_frame.phot_panel.aprad = (self.aper_last_radii[self.cur_aper_index] + (event.xdata - self.button_press_xdata)) self.ztv_frame.phot_panel.aprad_textctrl.SetValue('{0:.2f}'.format(self.ztv_frame.phot_panel.aprad)) set_textctrl_background_color(self.ztv_frame.phot_panel.aprad_textctrl, 'ok') elif self.cur_aper_name == 'skyradin': self.ztv_frame.phot_panel.skyradin = (self.aper_last_radii[self.cur_aper_index] + (event.xdata - self.button_press_xdata)) self.ztv_frame.phot_panel.skyradin_textctrl.SetValue('{0:.2f}'.format( self.ztv_frame.phot_panel.skyradin)) set_textctrl_background_color(self.ztv_frame.phot_panel.skyradin_textctrl, 'ok') elif self.cur_aper_name == 'skyradout': self.ztv_frame.phot_panel.skyradout = (self.aper_last_radii[self.cur_aper_index] + (event.xdata - self.button_press_xdata)) self.ztv_frame.phot_panel.skyradout_textctrl.SetValue('{0:.2f}'.format( self.ztv_frame.phot_panel.skyradout)) set_textctrl_background_color(self.ztv_frame.phot_panel.skyradout_textctrl, 'ok') self.ztv_frame.phot_panel.recalc_phot() def on_button_release(self, event): if self.button_down: if event.xdata is not None: if self.cur_aper_name == 'aprad': self.ztv_frame.phot_panel.aprad = (self.aper_last_radii[self.cur_aper_index] + (event.xdata - self.button_press_xdata)) self.ztv_frame.phot_panel.aprad_textctrl.SetValue('{0:.2f}'.format(self.ztv_frame.phot_panel.aprad)) set_textctrl_background_color(self.ztv_frame.phot_panel.aprad_textctrl, 'ok') elif self.cur_aper_name == 'skyradin': self.ztv_frame.phot_panel.skyradin = (self.aper_last_radii[self.cur_aper_index] + (event.xdata - self.button_press_xdata)) self.ztv_frame.phot_panel.skyradin_textctrl.SetValue('{0:.2f}'.format( self.ztv_frame.phot_panel.skyradin)) set_textctrl_background_color(self.ztv_frame.phot_panel.skyradin_textctrl, 'ok') elif self.cur_aper_name == 'skyradout': self.ztv_frame.phot_panel.skyradout = (self.aper_last_radii[self.cur_aper_index] + (event.xdata - self.button_press_xdata)) self.ztv_frame.phot_panel.skyradout_textctrl.SetValue('{0:.2f}'.format( self.ztv_frame.phot_panel.skyradout)) set_textctrl_background_color(self.ztv_frame.phot_panel.skyradout_textctrl, 'ok') self.ztv_frame.phot_panel.recalc_phot() self.button_down = False def on_cursor_leave(self, event): if self.button_down: if self.cur_aper_name == 'aprad': self.ztv_frame.phot_panel.aprad = self.aper_last_radii[self.cur_aper_index] self.ztv_frame.phot_panel.aprad_textctrl.SetValue('{0:.2f}'.format(self.ztv_frame.phot_panel.aprad)) set_textctrl_background_color(self.ztv_frame.phot_panel.aprad_textctrl, 'ok') elif self.cur_aper_name == 'skyradin': self.ztv_frame.phot_panel.skyradin = self.aper_last_radii[self.cur_aper_index] self.ztv_frame.phot_panel.skyradin_textctrl.SetValue('{0:.2f}'.format( self.ztv_frame.phot_panel.skyradin)) set_textctrl_background_color(self.ztv_frame.phot_panel.skyradin_textctrl, 'ok') elif self.cur_aper_name == 'skyradout': self.ztv_frame.phot_panel.skyradout = self.aper_last_radii[self.cur_aper_index] self.ztv_frame.phot_panel.skyradout_textctrl.SetValue('{0:.2f}'.format( self.ztv_frame.phot_panel.skyradout)) set_textctrl_background_color(self.ztv_frame.phot_panel.skyradout_textctrl, 'ok') self.ztv_frame.phot_panel.recalc_phot() self.button_down=False def _onSize(self, event): self._SetSize() def _SetSize(self): pixels = tuple(self.GetClientSize()) self.SetSize(pixels) self.canvas.SetSize(pixels) self.figure.set_size_inches(float(pixels[0])/self.figure.get_dpi(), float(pixels[1])/self.figure.get_dpi())