本文整理汇总了Python中matplotlib.widgets.RectangleSelector.set_active方法的典型用法代码示例。如果您正苦于以下问题:Python RectangleSelector.set_active方法的具体用法?Python RectangleSelector.set_active怎么用?Python RectangleSelector.set_active使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.widgets.RectangleSelector
的用法示例。
在下文中一共展示了RectangleSelector.set_active方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: PeakFinder
# 需要导入模块: from matplotlib.widgets import RectangleSelector [as 别名]
# 或者: from matplotlib.widgets.RectangleSelector import set_active [as 别名]
class PeakFinder(object):
def __init__(self, ax, canvas):
self.rectProps = dict(facecolor='red', edgecolor = 'white',
alpha=0.5, fill=True)
self.indicatorProps = dict(facecolor='white', edgecolor='black', alpha=0.5, fill=True)
self.__selector = RectangleSelector(ax, self.onSelect, drawtype='box', rectprops=self.rectProps)
self.__axes = ax
self.__canvas = canvas
def onSelect(self, epress, erelease):
start = map(int, (epress.xdata, epress.ydata))
stop = map(int, (erelease.xdata, erelease.ydata))
###################
ax = self.__axes
dataMatrix = ax.get_axes().get_images()[0].get_array()
clipMatrix = dataMatrix[start[1]:(stop[1]+1), start[0]:(stop[0]+1)]
peakPos = nonzero(clipMatrix == clipMatrix.max())
peakPos = (peakPos[1][0] + start[0], peakPos[0][0] + start[1])
print peakPos
circle = Circle(peakPos, 4, **self.indicatorProps)
ax.add_patch(circle)
self.__canvas.show()
###################
def activate(self):
self.__selector.set_active(True)
def deactivate(self):
self.__selector.set_active(False)
@property
def isActivate(self):
return self.__selector.active
示例2: SeriesWidget
# 需要导入模块: from matplotlib.widgets import RectangleSelector [as 别名]
# 或者: from matplotlib.widgets.RectangleSelector import set_active [as 别名]
class SeriesWidget(MplWidget):
def __init__(self, parent=None):
MplWidget.__init__(self, parent)
def draw(self):
(self.coord, series, title, xlabel, ylabel, showLegend) = self.inputPorts
colors = pylab.cm.jet(np.linspace(0,1, series.values.shape[0]))
pylab.clf()
pylab.title(title)
ll = pylab.plot(series.values.T, linewidth=1)
for pos, _ids in enumerate(series.ids):
ll[pos].set_color(colors[pos])
if _ids in self.selectedIds:
ll[pos].set_linewidth(3)
pylab.xlabel(xlabel)
pylab.ylabel(ylabel)
if showLegend:
pylab.legend(pylab.gca().get_lines(),
series.labels,
numpoints=1, prop=dict(size='small'), loc='upper right')
self.figManager.canvas.draw()
self.rectSelector = RectangleSelector(pylab.gca(), self.onselect, drawtype='box',
rectprops=dict(alpha=0.4, facecolor='yellow'))
self.rectSelector.set_active(True)
def updateSelection(self, selectedIds):
self.selectedIds = selectedIds
self.updateContents();
def onselect(self, eclick, erelease):
pass
示例3: ROISelector
# 需要导入模块: from matplotlib.widgets import RectangleSelector [as 别名]
# 或者: from matplotlib.widgets.RectangleSelector import set_active [as 别名]
class ROISelector(object):
def __init__(self,artist):
self.artist = artist
self.selector = RectangleSelector(self.artist.axes,self.on_select,
button=3, minspanx=5, minspany=5, spancoords='pixels',
rectprops = dict(facecolor='red', edgecolor = 'red',
alpha=0.3, fill=True))
self.coords = []
def on_select(self,click,release):
x1,y1 = int(click.xdata),int(click.ydata)
x2,y2 = int(release.xdata),int(release.ydata)
self.coords =[(x1,y1),(x2,y2)]
def activate(self):
self.selector.set_active(True)
def deactivate(self):
self.selector.set_active(False)
示例4: __init__
# 需要导入模块: from matplotlib.widgets import RectangleSelector [as 别名]
# 或者: from matplotlib.widgets.RectangleSelector import set_active [as 别名]
class BlockingRectangleSelector:
"""
Blocking rectangle selector selects once then continues with script.
"""
def __init__(self, ax=None):
if ax is None: ax=gca()
self.ax = ax
# drawtype is 'box' or 'line' or 'none'
self.selector = RectangleSelector(self.ax, self._callback,
drawtype='box',useblit=True,
minspanx=5,minspany=5,spancoords='pixels')
self.selector.set_active(False)
self.block = BlockingInput(self.ax.figure)
def _callback(self, event1, event2):
"""
Selection callback. event1 and event2 are the press and release events
"""
x1, y1 = event1.xdata, event1.ydata
x2, y2 = event2.xdata, event2.ydata
if x1>x2: x1,x2 = x2,x1
if y1>y2: y1,y2 = y2,y1
self.x1,self.x2,self.y1,self.y2 = x1,x2,y1,y2
print 'stopping event loop'
self.ax.figure.canvas.stop_event_loop_default()
def select(self):
"""
Wait for box to be selected on the axes.
"""
# Wait for selector to complete
self.selector.set_active(True)
self.ax.figure.canvas.draw_idle()
self.block()
self.selector.set_active(False)
# Make sure the graph is redrawn next time the event loop is shown
self.ax.figure.canvas.draw_idle()
def remove(self):
"""
Remove the selector from the axes.
Note: this currently does nothing since matplotlib doesn't allow
widgets to be removed from axes.
"""
pylab.close('all')
示例5: GUIrocket
# 需要导入模块: from matplotlib.widgets import RectangleSelector [as 别名]
# 或者: from matplotlib.widgets.RectangleSelector import set_active [as 别名]
#.........这里部分代码省略.........
evKeyOff = self.fig.canvas.mpl_connect('key_release_event', self.key_off)
AngSlide = plt.axes([0.1, 0.055, 0.65, 0.03])
self.widgets['AngBar'] = Slider(AngSlide, 'Shoot Angle', -maxangle, maxangle,
valinit=self.ang, color='b',
dragging=False, valfmt='%2.3f')
self.widgets['AngBar'].on_changed(self.updateAng)
VelSlide = plt.axes([0.1, 0.02, 0.65, 0.03])
self.widgets['VelBar'] = Slider(VelSlide, 'Shoot Speed', 0.01, 2,
valinit=self.vel, color='b',
dragging=False, valfmt='%1.4f')
self.widgets['VelBar'].on_changed(self.updateVel)
# assume max of N-2 planetoid bodies + target + source
self.N = len(bodies)
self.gen_versioner = common.gen_versioner(os.path.abspath('.'),
self.name,
'simgen_N%i'%self.N,
gentype, 1)
# Make this more generic for ABC
self.setup_pars(bodies)
# --- END OF BOMBARDIER SPECIFICS
# Move these to a _recreate method than can be reused for un-pickling
GoButton = Button(plt.axes([0.005, 0.1, 0.045, 0.03]), 'Go!')
GoButton.on_clicked(self.go)
self.widgets['Go'] = GoButton
self.RS_line = RectangleSelector(self.ax, self.onselect_line, drawtype='line') #,
# minspanx=0.005, minspany=0.005)
self.RS_line.set_active(False)
# self.RS_box = RectangleSelector(self.ax, self.onselect_box, drawtype='box',
# minspanx=0.005, minspany=0.005)
# self.RS_box.set_active(False)
# context_changed flag set when new objects created using declare_in_context(),
# and unset when Generator is created with the new context code included
self.context_changed = False
self.setup_gen()
self.traj = None
self.pts = None
self.mouse_cid = None # event-connection ID
self.go(run=False)
# force call to graphics_refresh because run=False above
self.graphics_refresh(cla=False)
plt.show()
# next_fighandle for whenever a new model is put in a new figure (new game instance)
next_fighandle += 1
def graphics_refresh(self, cla=True):
if cla:
self.ax.cla()
self.plot_bodies()
self.plot_traj()
# plot additional stuff
self.plot_context()
self.ax.set_aspect('equal')
self.ax.set_xlim(-xdomain_halfwidth,xdomain_halfwidth)
self.ax.set_ylim(0,1)
self.fig.canvas.draw()
示例6: onselect
# 需要导入模块: from matplotlib.widgets import RectangleSelector [as 别名]
# 或者: from matplotlib.widgets.RectangleSelector import set_active [as 别名]
from matplotlib.widgets import RectangleSelector
from pylab import *
def onselect(eclick, erelease):
'eclick and erelease are matplotlib events at press and release'
print ' startposition : (%f, %f)' % (eclick.xdata, eclick.ydata)
print ' endposition : (%f, %f)' % (erelease.xdata, erelease.ydata)
print ' used button : ', eclick.button
def toggle_selector(event):
print ' Key pressed.'
if event.key in ['Q', 'q'] and toggle_selector.RS.active:
print ' RectangleSelector deactivated.'
toggle_selector.RS.set_active(False)
if event.key in ['A', 'a'] and not toggle_selector.RS.active:
print ' RectangleSelector activated.'
toggle_selector.RS.set_active(True)
x = arange(100)/(99.0)
y = sin(x)
fig = figure
ax = subplot(111)
ax.plot(x,y)
#toggle_selector.RS = RectangleSelector(ax, onselect, drawtype='line')
#connect('key_press_event', toggle_selector)
RS = RectangleSelector(ax, onselect, drawtype='box')
RS.set_active(True)
show()
print('done: put breakpoint here!')
示例7: ImageView
# 需要导入模块: from matplotlib.widgets import RectangleSelector [as 别名]
# 或者: from matplotlib.widgets.RectangleSelector import set_active [as 别名]
#.........这里部分代码省略.........
# Keyboard callback
self.cb_mouse = ImageViewMouseHandler(self)
self.cb_mouse.connect()
# Mouse callback
self.cb_keyboard = ImageViewKeyboardHandler(self)
self.cb_keyboard.connect()
# Class update event callback
def updater(*args, **kwargs):
if self.classes is None:
self.set_classes(args[0].classes)
self.refresh()
callback = MplCallback(registry=self.callbacks_common,
event='spy_classes_modified',
callback=updater)
callback.connect()
self.cb_classes_modified = callback
if settings.imshow_enable_rectangle_selector is False:
return
try:
from matplotlib.widgets import RectangleSelector
self.selector = RectangleSelector(self.axes,
self._select_rectangle,
button=1,
useblit=True,
spancoords='data',
drawtype='box',
rectprops = \
self.selector_rectprops)
self.selector.set_active(False)
except:
self.selector = None
msg = 'Failed to create RectangleSelector object. Interactive ' \
'pixel class labeling will be unavailable.'
warn(msg)
def label_region(self, rectangle, class_id):
'''Assigns all pixels in the rectangle to the specified class.
Arguments:
`rectangle` (4-tuple of integers):
Tuple or list defining the rectangle bounds. Should have the
form (row_start, row_stop, col_start, col_stop), where the
stop indices are not included (i.e., the effect is
`classes[row_start:row_stop, col_start:col_stop] = id`.
class_id (integer >= 0):
The class to which pixels will be assigned.
Returns the number of pixels reassigned (the number of pixels in the
rectangle whose class has *changed* to `class_id`.
'''
if self.classes is None:
self.classes = np.zeros(self.data_rgb.shape[:2], dtype=np.int16)
r = rectangle
n = np.sum(self.classes[r[0]:r[1], r[2]:r[3]] != class_id)
if n > 0:
self.classes[r[0]:r[1], r[2]:r[3]] = class_id
event = SpyMplEvent('spy_classes_modified')
示例8: TaylorDiagramWidget
# 需要导入模块: from matplotlib.widgets import RectangleSelector [as 别名]
# 或者: from matplotlib.widgets.RectangleSelector import set_active [as 别名]
class TaylorDiagramWidget(MplWidget):
def __init__(self, parent=None):
MplWidget.__init__(self, parent)
self.markers = ['o','x','*',',','+','.','s','v','<','>','^','D','h','H','_','8',
'd',3,0,1,2,7,4,5,6,'1','3','4','2','|','x']
def draw(self):
(self.coord, self.stats, title, showLegend) = self.inputPorts
stds, corrs = self.stats.values[:,0], self.stats.values[:,1]
self.Xs = stds*corrs
self.Ys = stds*np.sin(np.arccos(corrs))
colors = pylab.cm.jet(np.linspace(0,1,len(self.stats.ids)))
pylab.clf()
fig = pylab.figure(str(self))
dia = taylor_diagram.TaylorDiagram(stds[0], corrs[0], fig=fig, label=self.stats.labels[0])
dia.samplePoints[0].set_color(colors[0]) # Mark reference point as a red star
if self.stats.ids[0] in self.selectedIds: dia.samplePoints[0].set_markeredgewidth(3)
# add models to Taylor diagram
for i, (_id, stddev,corrcoef) in enumerate(zip(self.stats.ids[1:], stds[1:], corrs[1:])):
label = self.stats.labels[i+1]
size = 3 if _id in self.selectedIds else 1
dia.add_sample(stddev, corrcoef,
marker='o', #self.markers[i],
ls='',
mfc=colors[i+1],
mew = size,
label=label
)
# Add grid
dia.add_grid()
# Add RMS contours, and label them
contours = dia.add_contours(levels=5, colors='0.5') # 5 levels in grey
pylab.clabel(contours, inline=1, fontsize=10, fmt='%.1f')
# Add a figure legend and title
if showLegend:
fig.legend(dia.samplePoints,
[ p.get_label() for p in dia.samplePoints ],
numpoints=1, prop=dict(size='small'), loc='upper right')
fig.suptitle(title, size='x-large') # Figure title
self.figManager.canvas.draw()
self.rectSelector = RectangleSelector(pylab.gca(), self.onselect, drawtype='box',
rectprops=dict(alpha=0.4, facecolor='yellow'))
self.rectSelector.set_active(True)
def updateSelection(self, selectedIds):
self.selectedIds = selectedIds
self.updateContents();
def onselect(self, eclick, erelease):
if (self.coord is None): return
left, bottom = min(eclick.xdata, erelease.xdata), min(eclick.ydata, erelease.ydata)
right, top = max(eclick.xdata, erelease.xdata), max(eclick.ydata, erelease.ydata)
region = Bbox.from_extents(left, bottom, right, top)
selectedIds = []
for (x, y, idd) in zip(self.Xs, self.Ys, self.stats.ids):
if region.contains(x, y):
selectedIds.append(idd)
self.coord.notifyModules(selectedIds)
示例9: InteractiveCut
# 需要导入模块: from matplotlib.widgets import RectangleSelector [as 别名]
# 或者: from matplotlib.widgets.RectangleSelector import set_active [as 别名]
class InteractiveCut(object):
def __init__(self, slice_plot, canvas, ws_title):
self.slice_plot = slice_plot
self._canvas = canvas
self._ws_title = ws_title
self._en_unit = slice_plot.get_slice_cache().energy_axis.e_unit
self._en_from_meV = EnergyUnits(self._en_unit).factor_from_meV()
self.horizontal = None
self.connect_event = [None, None, None, None]
# We need to access the CutPlotterPresenter instance of the particular CutPlot (window) we are using
# But there is no way to get without changing the active category then calling the GlobalFigureManager.
# So we create a new temporary here. After the first time we plot a 1D plot, the correct category is set
# and we can get the correct CutPlot instance and its CutPlotterPresenter
self._cut_plotter_presenter = CutPlotterPresenter()
self._is_initial_cut_plotter_presenter = True
self._rect_pos_cache = [0, 0, 0, 0, 0, 0]
self.rect = RectangleSelector(self._canvas.figure.gca(), self.plot_from_mouse_event,
drawtype='box', useblit=True,
button=[1, 3], spancoords='pixels', interactive=True)
self.connect_event[3] = self._canvas.mpl_connect('draw_event', self.redraw_rectangle)
self._canvas.draw()
def plot_from_mouse_event(self, eclick, erelease):
# Make axis orientation sticky, until user selects entirely new rectangle.
rect_pos = [eclick.x, eclick.y, erelease.x, erelease.y,
abs(erelease.x - eclick.x), abs(erelease.y - eclick.y)]
rectangle_changed = all([abs(rect_pos[i] - self._rect_pos_cache[i]) > 0.1 for i in range(6)])
if rectangle_changed:
self.horizontal = abs(erelease.x - eclick.x) > abs(erelease.y - eclick.y)
self.plot_cut(eclick.xdata, erelease.xdata, eclick.ydata, erelease.ydata)
self.connect_event[2] = self._canvas.mpl_connect('button_press_event', self.clicked)
self._rect_pos_cache = rect_pos
def plot_cut(self, x1, x2, y1, y2, store=False):
if x2 > x1 and y2 > y1:
ax, integration_start, integration_end = self.get_cut_parameters((x1, y1), (x2, y2))
units = self._canvas.figure.gca().get_yaxis().units if self.horizontal else \
self._canvas.figure.gca().get_xaxis().units
integration_axis = Axis(units, integration_start, integration_end, 0, self._en_unit)
cut = Cut(ax, integration_axis, None, None)
self._cut_plotter_presenter.plot_interactive_cut(str(self._ws_title), cut, store)
self._cut_plotter_presenter.set_is_icut(True)
if self._is_initial_cut_plotter_presenter:
# First time we've plotted a 1D cut - get the true CutPlotterPresenter
from mslice.plotting.pyplot import GlobalFigureManager
self._cut_plotter_presenter = GlobalFigureManager.get_active_figure().plot_handler._cut_plotter_presenter
self._is_initial_cut_plotter_presenter = False
GlobalFigureManager.disable_make_current()
self._cut_plotter_presenter.store_icut(self)
def get_cut_parameters(self, pos1, pos2):
start = pos1[not self.horizontal]
end = pos2[not self.horizontal]
units = self._canvas.figure.gca().get_xaxis().units if self.horizontal else \
self._canvas.figure.gca().get_yaxis().units
step = get_limits(get_workspace_handle(self._ws_title), units)[2] * self._en_from_meV
ax = Axis(units, start, end, step, self._en_unit)
integration_start = pos1[self.horizontal]
integration_end = pos2[self.horizontal]
return ax, integration_start, integration_end
def clicked(self, event):
self.connect_event[0] = self._canvas.mpl_connect('motion_notify_event',
lambda x: self.plot_cut(*self.rect.extents))
self.connect_event[1] = self._canvas.mpl_connect('button_release_event', self.end_drag)
def end_drag(self, event):
self._canvas.mpl_disconnect(self.connect_event[0])
self._canvas.mpl_disconnect(self.connect_event[1])
def redraw_rectangle(self, event):
if self.rect.active:
self.rect.update()
def save_cut(self):
x1, x2, y1, y2 = self.rect.extents
self.plot_cut(x1, x2, y1, y2, store=True)
self.update_workspaces()
ax, integration_start, integration_end = self.get_cut_parameters((x1, y1), (x2, y2))
return output_workspace_name(str(self._ws_title), integration_start, integration_end)
def update_workspaces(self):
self.slice_plot.update_workspaces()
def clear(self):
self._cut_plotter_presenter.set_is_icut(False)
self.rect.set_active(False)
for event in self.connect_event:
self._canvas.mpl_disconnect(event)
self._canvas.draw()
def flip_axis(self):
self.horizontal = not self.horizontal
self.plot_cut(*self.rect.extents)
def window_closing(self):
self.slice_plot.toggle_interactive_cuts()
#.........这里部分代码省略.........
示例10: plot_2d_data
# 需要导入模块: from matplotlib.widgets import RectangleSelector [as 别名]
# 或者: from matplotlib.widgets.RectangleSelector import set_active [as 别名]
#.........这里部分代码省略.........
elif label == "sx":
scale = ax.get_xscale()
if scale == "log":
ax.set_xscale("linear")
ax.figure.canvas.draw_idle()
elif scale == "linear":
ax.set_xscale("log")
ax.figure.canvas.draw_idle()
def onmousemove(self, event):
# the cursor position is given in the wx status bar
# self.fig.gca()
if event.inaxes:
x, y = event.xdata, event.ydata
self.statusbar.SetStatusText("%s scale x = %.3g, y = %.3g" % (self.__scale, x, y), 1)
# self.statusbar.SetStatusText("y = %.3g" %y, 2)
def onselect(self, eclick, erelease):
x_range = [eclick.xdata, erelease.xdata]
y_range = [eclick.ydata, erelease.ydata]
ax = eclick.inaxes
self.sliceplot((x_range, y_range), ax)
print "sliceplot(([%f,%f],[%f,%f]))" % (x_range[0], x_range[1], y_range[0], y_range[1])
def sliceplots_off(self):
self.fig.ax.set_position([0.125, 0.1, 0.7, 0.8])
self.fig.cb.set_position([0.85, 0.1, 0.05, 0.8])
# self.fig.cb.set_visible(True)
self.fig.sx.set_visible(False)
self.fig.sz.set_visible(False)
if self.fig.slice_overlay:
self.fig.slice_overlay[0].set_visible(False)
self.RS.set_active(False)
self.show_sliceplots = False
self.fig.canvas.draw()
def sliceplots_on(self):
self.fig.ax.set_position([0.125, 0.53636364, 0.35227273, 0.36363636])
self.fig.cb.set_position([0.49, 0.53636364, 0.02, 0.36363636])
self.fig.sx.set_position([0.58, 0.53636364, 0.35227273, 0.36363636])
self.fig.sx.set_visible(True)
self.fig.sz.set_visible(True)
# self.fig.cb.set_visible(False)
if self.fig.slice_overlay:
self.fig.slice_overlay[0].set_visible(True)
self.RS.set_active(True)
self.show_sliceplots = True
self.fig.canvas.draw()
def toggle_sliceplots(self):
"""switch between views with and without slice plots"""
if self.show_sliceplots == True:
self.sliceplots_off()
else: # self.show_sliceplots == False
self.sliceplots_on()
def show_slice_overlay(self, x_range, y_range, x, slice_y_data, y, slice_x_data):
"""sum along x and z within the box defined by qX- and qZrange.
sum along qx is plotted to the right of the data,
sum along qz is plotted below the data.
Transparent white rectangle is overlaid on data to show summing region"""
from matplotlib.ticker import FormatStrFormatter, ScalarFormatter
if self.fig == None:
print ("No figure for this dataset is available")
示例11: RectChooser
# 需要导入模块: from matplotlib.widgets import RectangleSelector [as 别名]
# 或者: from matplotlib.widgets.RectangleSelector import set_active [as 别名]
class RectChooser(object):
MOUSEUP = ['Q', 'q']
MOUSEDOWN = ['A', 'a']
def __init__(self, fitsfile, ax, mags, frms, all_axes, buttons, use_hjd=False,
display_class=LightcurveDisplay):
self.fitsfile = fitsfile
self.ax = ax
self.mags = mags
self.frms = frms
self.all_axes = all_axes
self.buttons = buttons
self.use_hjd = use_hjd
self.display_class = display_class
self.selector = RectangleSelector(self.ax, self.on_event, drawtype='box')
self.l = None
def on_event(self, eclick, erelease):
logger.debug('startposition: ({}, {})'.format(eclick.xdata, eclick.ydata))
logger.debug('endposition: ({}, {})'.format(erelease.xdata, erelease.ydata))
mag_min, mag_max = eclick.xdata, erelease.xdata
frms_min, frms_max = eclick.ydata, erelease.ydata
if mag_min > mag_max:
mag_min, mag_max = mag_max, mag_min
if frms_min > frms_max:
frms_min, frms_max = frms_max, frms_min
logger.info('Using magnitude range {} to {}'.format(mag_min, mag_max))
logger.info('Using frms range {} to {}'.format(frms_min, frms_max))
indices = np.arange(self.mags.size)
chosen = ((self.mags >= mag_min) &
(self.mags < mag_max) &
(self.frms >= frms_min) &
(self.frms < frms_max))
if not chosen.any():
logger.error("No lightcurves chosen, please try again")
else:
if self.l is not None:
logger.debug('Lightcurve display present')
self.reset_buttons()
self.load_lightcurves(indices[chosen])
def reset_buttons(self):
self.buttons[0].disconnect(self.prev_cid)
self.buttons[1].disconnect(self.next_cid)
self.l.remove_frms_line()
del self.l
def load_lightcurves(self, indices):
self.l = self.display_class(self.fitsfile, self.all_axes).display_lightcurves(self.mags,
self.frms, indices, use_hjd=self.use_hjd)
self.prev_cid = self.buttons[0].on_clicked(self.l.previous)
self.next_cid = self.buttons[1].on_clicked(self.l.next)
def toggle_selector(self, event):
logger.debug(' Key pressed.')
if event.key in self.MOUSEUP and self.selector.active:
logger.debug('RectangleSelector deactivated')
self.selector.set_active(False)
if event.key in self.MOUSEDOWN and not self.selector.active:
logger.debug('RectangleSelector activated')
self.selector.set_active(True)
示例12: do_ui
# 需要导入模块: from matplotlib.widgets import RectangleSelector [as 别名]
# 或者: from matplotlib.widgets.RectangleSelector import set_active [as 别名]
#.........这里部分代码省略.........
#
# The zoom-out button
#
##################################
def on_zoom_out(event):
zoom_stack.pop()
if len(zoom_stack) == 0:
zoom_out_button.Disable()
draw()
dialog_box.Bind(wx.EVT_BUTTON, on_zoom_out, zoom_out_button)
##################################
#
# Zoom selector callback
#
##################################
def on_zoom_in(event_click, event_release):
xmin = min(event_click.xdata, event_release.xdata)
xmax = max(event_click.xdata, event_release.xdata)
ymin = min(event_click.ydata, event_release.ydata)
ymax = max(event_click.ydata, event_release.ydata)
zoom_stack.append(((xmin, ymin), (xmax, ymax)))
draw()
zoom_out_button.Enable()
zoom_selector = RectangleSelector(axes, on_zoom_in, drawtype='box',
rectprops = dict(edgecolor='red',
fill=False),
useblit=True,
minspanx=2, minspany=2,
spancoords='data')
zoom_selector.set_active(False)
##################################
#
# Lasso selector callback
#
##################################
current_lasso = []
def on_lasso(vertices):
lasso = current_lasso.pop()
figure.canvas.widgetlock.release(lasso)
mask = np.zeros(pixel_data.shape[:2], int)
new_label = np.max(labels) + 1
vertices = [x for x in vertices
if x[0] is not None and x[1] is not None]
for i in range(len(vertices)):
v0 = (int(vertices[i][1]), int(vertices[i][0]))
i_next = (i+1) % len(vertices)
v1 = (int(vertices[i_next][1]), int(vertices[i_next][0]))
draw_line(mask, v0, v1, new_label)
mask = fill_labeled_holes(mask)
labels[mask != 0] = new_label
draw()
if labels.max() > 0:
erase_all_button.Enable()
erase_last_button.Enable()
##################################
#
# Left mouse button down
#
##################################
示例13: ProjectionWidget
# 需要导入模块: from matplotlib.widgets import RectangleSelector [as 别名]
# 或者: from matplotlib.widgets.RectangleSelector import set_active [as 别名]
class ProjectionWidget(MplWidget):
""" ProjectionWidget is a widget to show 2D projections. It has some interactive
features like, show labels, selections, and synchronization.
"""
def __init__(self, parent=None):
MplWidget.__init__(self, parent)
self.showLabels = False
self.toolBarType = QProjectionToolBar
def draw(self):
"""draw(fig: Figure) ->None
code using matplotlib.
Use self.fig and self.figManager
"""
(self.coord, self.matrix, title) = self.inputPorts
# for faster access
id2pos = {idd: pos for (pos, idd) in enumerate(self.matrix.ids)}
circleSize = np.ones(len(self.matrix.ids))
for selId in self.selectedIds:
circleSize[id2pos[selId]] = 4
pylab.clf()
pylab.axis("off")
pylab.title(title)
pylab.scatter(
self.matrix.values[:, 0],
self.matrix.values[:, 1],
# c=colors, cmap=pylab.cm.Spectral,
s=40,
linewidth=circleSize,
marker="o",
)
# draw labels
if self.showLabels and self.matrix.labels is not None:
for label, xy in zip(self.matrix.labels, self.matrix.values):
pylab.annotate(
str(label),
xy=xy,
xytext=(5, 5),
textcoords="offset points",
bbox=dict(boxstyle="round,pad=0.2", fc="yellow", alpha=0.5),
)
self.figManager.canvas.draw()
# Set Selectors
self.rectSelector = RectangleSelector(
pylab.gca(), self.onselect, drawtype="box", rectprops=dict(alpha=0.4, facecolor="yellow")
)
self.rectSelector.set_active(True)
def updateSelection(self, selectedIds):
self.selectedIds = selectedIds
self.updateContents()
def onselect(self, eclick, erelease):
if self.coord is None:
return
left, bottom = min(eclick.xdata, erelease.xdata), min(eclick.ydata, erelease.ydata)
right, top = max(eclick.xdata, erelease.xdata), max(eclick.ydata, erelease.ydata)
region = Bbox.from_extents(left, bottom, right, top)
selectedIds = []
for (xy, idd) in zip(self.matrix.values, self.matrix.ids):
if region.contains(xy[0], xy[1]):
selectedIds.append(idd)
self.coord.notifyModules(selectedIds)
示例14: __init__
# 需要导入模块: from matplotlib.widgets import RectangleSelector [as 别名]
# 或者: from matplotlib.widgets.RectangleSelector import set_active [as 别名]
class RectSelector:
def __init__(self, ax, canvas):
self.rectProps = dict(facecolor='red', edgecolor = 'white',
alpha=0.5, fill=True)
self.indicatorProps = dict(facecolor='white', edgecolor='black', alpha=0.5, fill=True)
self.__selector = RectangleSelector(ax, self._on_select, drawtype='box', rectprops=self.rectProps)
self.__axes = ax
self.__canvas = canvas
self.mode = None
# mode:
# None or 'rect': get the selected rect region
# 'peak': get the peak point in the selected rect region
self.__rect = None
self.__peakpos = None
self.__callback = None
@property
def callback(self):
return self.__callback
@callback.setter
def callback(self, val):
if not callable(val):
raise ValueError
self.__callback = val
@property
def rect(self):
return self.__rect
@property
def peakpos(self):
return self.__peakpos
def _on_select(self, epress, erelease):
start = (int(epress.xdata), int(epress.ydata))
stop = (int(erelease.xdata), int(erelease.ydata))
self.__rect = start + (stop[0]-start[0], stop[1]-start[1])
if self.mode == 'peak':
ax = self.__axes
data_matrix = ax.axes.get_images()[0].get_array()
clip_matrix = data_matrix[start[1]:(stop[1]+1), start[0]:(stop[0]+1)]
peak_pos = nonzero(clip_matrix == clip_matrix.max())
peak_pos = (peak_pos[1][0] + start[0], peak_pos[0][0] + start[1])
self.__peakpos = peak_pos
circle = Circle(peak_pos, 4, **self.indicatorProps)
ax.add_patch(circle)
self.__canvas.draw()
self.callback(self.__rect, self.__peakpos)
def activate(self):
self.__selector.set_active(True)
def deactivate(self):
self.__selector.set_active(False)
@property
def is_active(self):
return self.__selector.active