Hello everyone,
in my programs I need the RectangleSelector. It's quiet easy to use but I
discovered that there isn't a really easy way to switch it off once it is
activated. I thought about the following lines to matplotlib/widgets.py:
···
#--------------------------------------------------------------------------------------------
#at the beginning of RectangleSelector's __init__:
... docstring ...
self.ax = ax # like before
self.visible = True # like before
self.canvas = ax.figure.canvas # like before
self.connect_id = [] # will contain the connection id's
self.active = True # for activation / deactivation
self.is_active(True)
... snip ...
#and an additional method:
#--------------------------------------------------------------------------------------------
def is_active(self, active):
""" Use this to activate the RectangleSelector from your program.
"""
self.active = active
if active and len(self.connect_id) == 0: # you want to activate and it
# isn't already active
self.connect_id.append(self.canvas.mpl_connect(
'motion_notify_event', self.onmove))
self.connect_id.append(self.canvas.mpl_connect(
'button_press_event', self.press))
self.connect_id.append(self.canvas.mpl_connect(
'button_release_event', self.release))
self.connect_id.append(self.canvas.mpl_connect(
'draw_event', self.update_background))
if not active and len(self.connect_id) != 0: # you want to deactivate
for index in self.connect_id: # and it isn't already inactive
self.canvas.mpl_disconnect(index)
self.connect_id = []
#--------------------------------------------------------------------------------------------
With these changes you can check the following example:
#--------------------------------------------------------------------------------------------
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.is_active(False)
if event.key in ["A", "a"] and not toggle_Selector.RS.active:
print " RectangleSelector activated."
toggle_Selector.RS.is_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='box')
connect("key_press_event", toggle_Selector)
show()
#--------------------------------------------------------------------------------------------
I hope this is usefull to someone,
Martin
PS: Maybe the above example can replace the RectangleSelector's
docstring. I think it's easier to read and understand.