widgets.py 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768
  1. """
  2. GUI neutral widgets
  3. ===================
  4. Widgets that are designed to work for any of the GUI backends.
  5. All of these widgets require you to predefine a `matplotlib.axes.Axes`
  6. instance and pass that as the first parameter. Matplotlib doesn't try to
  7. be too smart with respect to layout -- you will have to figure out how
  8. wide and tall you want your Axes to be to accommodate your widget.
  9. """
  10. from contextlib import ExitStack
  11. import copy
  12. from numbers import Integral
  13. import numpy as np
  14. from . import cbook, rcParams
  15. from .lines import Line2D
  16. from .patches import Circle, Rectangle, Ellipse
  17. from .transforms import blended_transform_factory
  18. class LockDraw:
  19. """
  20. Some widgets, like the cursor, draw onto the canvas, and this is not
  21. desirable under all circumstances, like when the toolbar is in zoom-to-rect
  22. mode and drawing a rectangle. To avoid this, a widget can acquire a
  23. canvas' lock with ``canvas.widgetlock(widget)`` before drawing on the
  24. canvas; this will prevent other widgets from doing so at the same time (if
  25. they also try to acquire the lock first).
  26. """
  27. def __init__(self):
  28. self._owner = None
  29. def __call__(self, o):
  30. """Reserve the lock for *o*."""
  31. if not self.available(o):
  32. raise ValueError('already locked')
  33. self._owner = o
  34. def release(self, o):
  35. """Release the lock from *o*."""
  36. if not self.available(o):
  37. raise ValueError('you do not own this lock')
  38. self._owner = None
  39. def available(self, o):
  40. """Return whether drawing is available to *o*."""
  41. return not self.locked() or self.isowner(o)
  42. def isowner(self, o):
  43. """Return whether *o* owns this lock."""
  44. return self._owner is o
  45. def locked(self):
  46. """Return whether the lock is currently held by an owner."""
  47. return self._owner is not None
  48. class Widget:
  49. """
  50. Abstract base class for GUI neutral widgets
  51. """
  52. drawon = True
  53. eventson = True
  54. _active = True
  55. def set_active(self, active):
  56. """Set whether the widget is active.
  57. """
  58. self._active = active
  59. def get_active(self):
  60. """Get whether the widget is active.
  61. """
  62. return self._active
  63. # set_active is overridden by SelectorWidgets.
  64. active = property(get_active, set_active, doc="Is the widget active?")
  65. def ignore(self, event):
  66. """
  67. Return whether *event* should be ignored.
  68. This method should be called at the beginning of any event callback.
  69. """
  70. return not self.active
  71. class AxesWidget(Widget):
  72. """
  73. Widget that is connected to a single `~matplotlib.axes.Axes`.
  74. To guarantee that the widget remains responsive and not garbage-collected,
  75. a reference to the object should be maintained by the user.
  76. This is necessary because the callback registry
  77. maintains only weak-refs to the functions, which are member
  78. functions of the widget. If there are no references to the widget
  79. object it may be garbage collected which will disconnect the callbacks.
  80. Attributes
  81. ----------
  82. ax : `~matplotlib.axes.Axes`
  83. The parent axes for the widget.
  84. canvas : `~matplotlib.backend_bases.FigureCanvasBase` subclass
  85. The parent figure canvas for the widget.
  86. active : bool
  87. If False, the widget does not respond to events.
  88. """
  89. def __init__(self, ax):
  90. self.ax = ax
  91. self.canvas = ax.figure.canvas
  92. self.cids = []
  93. def connect_event(self, event, callback):
  94. """
  95. Connect callback with an event.
  96. This should be used in lieu of `figure.canvas.mpl_connect` since this
  97. function stores callback ids for later clean up.
  98. """
  99. cid = self.canvas.mpl_connect(event, callback)
  100. self.cids.append(cid)
  101. def disconnect_events(self):
  102. """Disconnect all events created by this widget."""
  103. for c in self.cids:
  104. self.canvas.mpl_disconnect(c)
  105. class Button(AxesWidget):
  106. """
  107. A GUI neutral button.
  108. For the button to remain responsive you must keep a reference to it.
  109. Call `.on_clicked` to connect to the button.
  110. Attributes
  111. ----------
  112. ax
  113. The `matplotlib.axes.Axes` the button renders into.
  114. label
  115. A `matplotlib.text.Text` instance.
  116. color
  117. The color of the button when not hovering.
  118. hovercolor
  119. The color of the button when hovering.
  120. """
  121. def __init__(self, ax, label, image=None,
  122. color='0.85', hovercolor='0.95'):
  123. """
  124. Parameters
  125. ----------
  126. ax : `~matplotlib.axes.Axes`
  127. The `~.axes.Axes` instance the button will be placed into.
  128. label : str
  129. The button text. Accepts string.
  130. image : array-like or PIL image
  131. The image to place in the button, if not *None*.
  132. Supported inputs are the same as for `.Axes.imshow`.
  133. color : color
  134. The color of the button when not activated.
  135. hovercolor : color
  136. The color of the button when the mouse is over it.
  137. """
  138. AxesWidget.__init__(self, ax)
  139. if image is not None:
  140. ax.imshow(image)
  141. self.label = ax.text(0.5, 0.5, label,
  142. verticalalignment='center',
  143. horizontalalignment='center',
  144. transform=ax.transAxes)
  145. self.cnt = 0
  146. self.observers = {}
  147. self.connect_event('button_press_event', self._click)
  148. self.connect_event('button_release_event', self._release)
  149. self.connect_event('motion_notify_event', self._motion)
  150. ax.set_navigate(False)
  151. ax.set_facecolor(color)
  152. ax.set_xticks([])
  153. ax.set_yticks([])
  154. self.color = color
  155. self.hovercolor = hovercolor
  156. self._lastcolor = color
  157. def _click(self, event):
  158. if (self.ignore(event)
  159. or event.inaxes != self.ax
  160. or not self.eventson):
  161. return
  162. if event.canvas.mouse_grabber != self.ax:
  163. event.canvas.grab_mouse(self.ax)
  164. def _release(self, event):
  165. if (self.ignore(event)
  166. or event.canvas.mouse_grabber != self.ax):
  167. return
  168. event.canvas.release_mouse(self.ax)
  169. if (not self.eventson
  170. or event.inaxes != self.ax):
  171. return
  172. for cid, func in self.observers.items():
  173. func(event)
  174. def _motion(self, event):
  175. if self.ignore(event):
  176. return
  177. if event.inaxes == self.ax:
  178. c = self.hovercolor
  179. else:
  180. c = self.color
  181. if c != self._lastcolor:
  182. self.ax.set_facecolor(c)
  183. self._lastcolor = c
  184. if self.drawon:
  185. self.ax.figure.canvas.draw()
  186. def on_clicked(self, func):
  187. """
  188. Connect the callback function *func* to button click events.
  189. Returns a connection id, which can be used to disconnect the callback.
  190. """
  191. cid = self.cnt
  192. self.observers[cid] = func
  193. self.cnt += 1
  194. return cid
  195. def disconnect(self, cid):
  196. """Remove the callback function with connection id *cid*."""
  197. try:
  198. del self.observers[cid]
  199. except KeyError:
  200. pass
  201. class Slider(AxesWidget):
  202. """
  203. A slider representing a floating point range.
  204. Create a slider from *valmin* to *valmax* in axes *ax*. For the slider to
  205. remain responsive you must maintain a reference to it. Call
  206. :meth:`on_changed` to connect to the slider event.
  207. Attributes
  208. ----------
  209. val : float
  210. Slider value.
  211. """
  212. def __init__(self, ax, label, valmin, valmax, valinit=0.5, valfmt='%1.2f',
  213. closedmin=True, closedmax=True, slidermin=None,
  214. slidermax=None, dragging=True, valstep=None,
  215. orientation='horizontal', **kwargs):
  216. """
  217. Parameters
  218. ----------
  219. ax : Axes
  220. The Axes to put the slider in.
  221. label : str
  222. Slider label.
  223. valmin : float
  224. The minimum value of the slider.
  225. valmax : float
  226. The maximum value of the slider.
  227. valinit : float, optional, default: 0.5
  228. The slider initial position.
  229. valfmt : str, optional, default: "%1.2f"
  230. Used to format the slider value, fprint format string.
  231. closedmin : bool, optional, default: True
  232. Whether the slider interval is closed on the bottom.
  233. closedmax : bool, optional, default: True
  234. Whether the slider interval is closed on the top.
  235. slidermin : Slider, optional, default: None
  236. Do not allow the current slider to have a value less than
  237. the value of the Slider `slidermin`.
  238. slidermax : Slider, optional, default: None
  239. Do not allow the current slider to have a value greater than
  240. the value of the Slider `slidermax`.
  241. dragging : bool, optional, default: True
  242. If True the slider can be dragged by the mouse.
  243. valstep : float, optional, default: None
  244. If given, the slider will snap to multiples of `valstep`.
  245. orientation : {'horizontal', 'vertical'}, default: 'horizontal'
  246. The orientation of the slider.
  247. Notes
  248. -----
  249. Additional kwargs are passed on to ``self.poly`` which is the
  250. `~matplotlib.patches.Rectangle` that draws the slider knob. See the
  251. `.Rectangle` documentation for valid property names (``facecolor``,
  252. ``edgecolor``, ``alpha``, etc.).
  253. """
  254. if ax.name == '3d':
  255. raise ValueError('Sliders cannot be added to 3D Axes')
  256. AxesWidget.__init__(self, ax)
  257. if slidermin is not None and not hasattr(slidermin, 'val'):
  258. raise ValueError("Argument slidermin ({}) has no 'val'"
  259. .format(type(slidermin)))
  260. if slidermax is not None and not hasattr(slidermax, 'val'):
  261. raise ValueError("Argument slidermax ({}) has no 'val'"
  262. .format(type(slidermax)))
  263. if orientation not in ['horizontal', 'vertical']:
  264. raise ValueError("Argument orientation ({}) must be either"
  265. "'horizontal' or 'vertical'".format(orientation))
  266. self.orientation = orientation
  267. self.closedmin = closedmin
  268. self.closedmax = closedmax
  269. self.slidermin = slidermin
  270. self.slidermax = slidermax
  271. self.drag_active = False
  272. self.valmin = valmin
  273. self.valmax = valmax
  274. self.valstep = valstep
  275. valinit = self._value_in_bounds(valinit)
  276. if valinit is None:
  277. valinit = valmin
  278. self.val = valinit
  279. self.valinit = valinit
  280. if orientation == 'vertical':
  281. self.poly = ax.axhspan(valmin, valinit, 0, 1, **kwargs)
  282. self.hline = ax.axhline(valinit, 0, 1, color='r', lw=1)
  283. else:
  284. self.poly = ax.axvspan(valmin, valinit, 0, 1, **kwargs)
  285. self.vline = ax.axvline(valinit, 0, 1, color='r', lw=1)
  286. self.valfmt = valfmt
  287. ax.set_yticks([])
  288. if orientation == 'vertical':
  289. ax.set_ylim((valmin, valmax))
  290. else:
  291. ax.set_xlim((valmin, valmax))
  292. ax.set_xticks([])
  293. ax.set_navigate(False)
  294. self.connect_event('button_press_event', self._update)
  295. self.connect_event('button_release_event', self._update)
  296. if dragging:
  297. self.connect_event('motion_notify_event', self._update)
  298. if orientation == 'vertical':
  299. self.label = ax.text(0.5, 1.02, label, transform=ax.transAxes,
  300. verticalalignment='bottom',
  301. horizontalalignment='center')
  302. self.valtext = ax.text(0.5, -0.02, valfmt % valinit,
  303. transform=ax.transAxes,
  304. verticalalignment='top',
  305. horizontalalignment='center')
  306. else:
  307. self.label = ax.text(-0.02, 0.5, label, transform=ax.transAxes,
  308. verticalalignment='center',
  309. horizontalalignment='right')
  310. self.valtext = ax.text(1.02, 0.5, valfmt % valinit,
  311. transform=ax.transAxes,
  312. verticalalignment='center',
  313. horizontalalignment='left')
  314. self.cnt = 0
  315. self.observers = {}
  316. self.set_val(valinit)
  317. def _value_in_bounds(self, val):
  318. """Makes sure *val* is with given bounds."""
  319. if self.valstep:
  320. val = (self.valmin
  321. + round((val - self.valmin) / self.valstep) * self.valstep)
  322. if val <= self.valmin:
  323. if not self.closedmin:
  324. return
  325. val = self.valmin
  326. elif val >= self.valmax:
  327. if not self.closedmax:
  328. return
  329. val = self.valmax
  330. if self.slidermin is not None and val <= self.slidermin.val:
  331. if not self.closedmin:
  332. return
  333. val = self.slidermin.val
  334. if self.slidermax is not None and val >= self.slidermax.val:
  335. if not self.closedmax:
  336. return
  337. val = self.slidermax.val
  338. return val
  339. def _update(self, event):
  340. """Update the slider position."""
  341. if self.ignore(event) or event.button != 1:
  342. return
  343. if event.name == 'button_press_event' and event.inaxes == self.ax:
  344. self.drag_active = True
  345. event.canvas.grab_mouse(self.ax)
  346. if not self.drag_active:
  347. return
  348. elif ((event.name == 'button_release_event') or
  349. (event.name == 'button_press_event' and
  350. event.inaxes != self.ax)):
  351. self.drag_active = False
  352. event.canvas.release_mouse(self.ax)
  353. return
  354. if self.orientation == 'vertical':
  355. val = self._value_in_bounds(event.ydata)
  356. else:
  357. val = self._value_in_bounds(event.xdata)
  358. if val not in [None, self.val]:
  359. self.set_val(val)
  360. def set_val(self, val):
  361. """
  362. Set slider value to *val*
  363. Parameters
  364. ----------
  365. val : float
  366. """
  367. xy = self.poly.xy
  368. if self.orientation == 'vertical':
  369. xy[1] = 0, val
  370. xy[2] = 1, val
  371. else:
  372. xy[2] = val, 1
  373. xy[3] = val, 0
  374. self.poly.xy = xy
  375. self.valtext.set_text(self.valfmt % val)
  376. if self.drawon:
  377. self.ax.figure.canvas.draw_idle()
  378. self.val = val
  379. if not self.eventson:
  380. return
  381. for cid, func in self.observers.items():
  382. func(val)
  383. def on_changed(self, func):
  384. """
  385. When the slider value is changed call *func* with the new
  386. slider value
  387. Parameters
  388. ----------
  389. func : callable
  390. Function to call when slider is changed.
  391. The function must accept a single float as its arguments.
  392. Returns
  393. -------
  394. cid : int
  395. Connection id (which can be used to disconnect *func*)
  396. """
  397. cid = self.cnt
  398. self.observers[cid] = func
  399. self.cnt += 1
  400. return cid
  401. def disconnect(self, cid):
  402. """
  403. Remove the observer with connection id *cid*
  404. Parameters
  405. ----------
  406. cid : int
  407. Connection id of the observer to be removed
  408. """
  409. try:
  410. del self.observers[cid]
  411. except KeyError:
  412. pass
  413. def reset(self):
  414. """Reset the slider to the initial value"""
  415. if self.val != self.valinit:
  416. self.set_val(self.valinit)
  417. class CheckButtons(AxesWidget):
  418. r"""
  419. A GUI neutral set of check buttons.
  420. For the check buttons to remain responsive you must keep a
  421. reference to this object.
  422. Connect to the CheckButtons with the :meth:`on_clicked` method
  423. Attributes
  424. ----------
  425. ax
  426. The `matplotlib.axes.Axes` the button are located in.
  427. labels
  428. A list of `matplotlib.text.Text`\ s.
  429. lines
  430. List of (line1, line2) tuples for the x's in the check boxes.
  431. These lines exist for each box, but have ``set_visible(False)``
  432. when its box is not checked.
  433. rectangles
  434. A list of `matplotlib.patches.Rectangle`\ s.
  435. """
  436. def __init__(self, ax, labels, actives=None):
  437. """
  438. Add check buttons to `matplotlib.axes.Axes` instance *ax*
  439. Parameters
  440. ----------
  441. ax : `~matplotlib.axes.Axes`
  442. The parent axes for the widget.
  443. labels : list of str
  444. The labels of the check buttons.
  445. actives : list of bool, optional
  446. The initial check states of the buttons. The list must have the
  447. same length as *labels*. If not given, all buttons are unchecked.
  448. """
  449. AxesWidget.__init__(self, ax)
  450. ax.set_xticks([])
  451. ax.set_yticks([])
  452. ax.set_navigate(False)
  453. if actives is None:
  454. actives = [False] * len(labels)
  455. if len(labels) > 1:
  456. dy = 1. / (len(labels) + 1)
  457. ys = np.linspace(1 - dy, dy, len(labels))
  458. else:
  459. dy = 0.25
  460. ys = [0.5]
  461. axcolor = ax.get_facecolor()
  462. self.labels = []
  463. self.lines = []
  464. self.rectangles = []
  465. lineparams = {'color': 'k', 'linewidth': 1.25,
  466. 'transform': ax.transAxes, 'solid_capstyle': 'butt'}
  467. for y, label, active in zip(ys, labels, actives):
  468. t = ax.text(0.25, y, label, transform=ax.transAxes,
  469. horizontalalignment='left',
  470. verticalalignment='center')
  471. w, h = dy / 2, dy / 2
  472. x, y = 0.05, y - h / 2
  473. p = Rectangle(xy=(x, y), width=w, height=h, edgecolor='black',
  474. facecolor=axcolor, transform=ax.transAxes)
  475. l1 = Line2D([x, x + w], [y + h, y], **lineparams)
  476. l2 = Line2D([x, x + w], [y, y + h], **lineparams)
  477. l1.set_visible(active)
  478. l2.set_visible(active)
  479. self.labels.append(t)
  480. self.rectangles.append(p)
  481. self.lines.append((l1, l2))
  482. ax.add_patch(p)
  483. ax.add_line(l1)
  484. ax.add_line(l2)
  485. self.connect_event('button_press_event', self._clicked)
  486. self.cnt = 0
  487. self.observers = {}
  488. def _clicked(self, event):
  489. if self.ignore(event) or event.button != 1 or event.inaxes != self.ax:
  490. return
  491. for i, (p, t) in enumerate(zip(self.rectangles, self.labels)):
  492. if (t.get_window_extent().contains(event.x, event.y) or
  493. p.get_window_extent().contains(event.x, event.y)):
  494. self.set_active(i)
  495. break
  496. def set_active(self, index):
  497. """
  498. Directly (de)activate a check button by index.
  499. *index* is an index into the original label list
  500. that this object was constructed with.
  501. Raises ValueError if *index* is invalid.
  502. Callbacks will be triggered if :attr:`eventson` is True.
  503. """
  504. if not 0 <= index < len(self.labels):
  505. raise ValueError("Invalid CheckButton index: %d" % index)
  506. l1, l2 = self.lines[index]
  507. l1.set_visible(not l1.get_visible())
  508. l2.set_visible(not l2.get_visible())
  509. if self.drawon:
  510. self.ax.figure.canvas.draw()
  511. if not self.eventson:
  512. return
  513. for cid, func in self.observers.items():
  514. func(self.labels[index].get_text())
  515. def get_status(self):
  516. """
  517. Return a tuple of the status (True/False) of all of the check buttons.
  518. """
  519. return [l1.get_visible() for (l1, l2) in self.lines]
  520. def on_clicked(self, func):
  521. """
  522. Connect the callback function *func* to button click events.
  523. Returns a connection id, which can be used to disconnect the callback.
  524. """
  525. cid = self.cnt
  526. self.observers[cid] = func
  527. self.cnt += 1
  528. return cid
  529. def disconnect(self, cid):
  530. """remove the observer with connection id *cid*"""
  531. try:
  532. del self.observers[cid]
  533. except KeyError:
  534. pass
  535. class TextBox(AxesWidget):
  536. """
  537. A GUI neutral text input box.
  538. For the text box to remain responsive you must keep a reference to it.
  539. Call :meth:`on_text_change` to be updated whenever the text changes.
  540. Call :meth:`on_submit` to be updated whenever the user hits enter or
  541. leaves the text entry field.
  542. Attributes
  543. ----------
  544. ax
  545. The `matplotlib.axes.Axes` the button renders into.
  546. label
  547. A `matplotlib.text.Text` instance.
  548. color
  549. The color of the button when not hovering.
  550. hovercolor
  551. The color of the button when hovering.
  552. """
  553. def __init__(self, ax, label, initial='',
  554. color='.95', hovercolor='1', label_pad=.01):
  555. """
  556. Parameters
  557. ----------
  558. ax : `~matplotlib.axes.Axes`
  559. The `~.axes.Axes` instance the button will be placed into.
  560. label : str
  561. Label for this text box.
  562. initial : str
  563. Initial value in the text box.
  564. color : color
  565. The color of the box.
  566. hovercolor : color
  567. The color of the box when the mouse is over it.
  568. label_pad : float
  569. The distance between the label and the right side of the textbox.
  570. """
  571. AxesWidget.__init__(self, ax)
  572. self.DIST_FROM_LEFT = .05
  573. self.params_to_disable = [key for key in rcParams if 'keymap' in key]
  574. self.text = initial
  575. self.label = ax.text(-label_pad, 0.5, label,
  576. verticalalignment='center',
  577. horizontalalignment='right',
  578. transform=ax.transAxes)
  579. self.text_disp = self._make_text_disp(self.text)
  580. self.cnt = 0
  581. self.change_observers = {}
  582. self.submit_observers = {}
  583. # If these lines are removed, the cursor won't appear the first
  584. # time the box is clicked:
  585. self.ax.set_xlim(0, 1)
  586. self.ax.set_ylim(0, 1)
  587. self.cursor_index = 0
  588. # Because this is initialized, _render_cursor
  589. # can assume that cursor exists.
  590. self.cursor = self.ax.vlines(0, 0, 0)
  591. self.cursor.set_visible(False)
  592. self.connect_event('button_press_event', self._click)
  593. self.connect_event('button_release_event', self._release)
  594. self.connect_event('motion_notify_event', self._motion)
  595. self.connect_event('key_press_event', self._keypress)
  596. self.connect_event('resize_event', self._resize)
  597. ax.set_navigate(False)
  598. ax.set_facecolor(color)
  599. ax.set_xticks([])
  600. ax.set_yticks([])
  601. self.color = color
  602. self.hovercolor = hovercolor
  603. self._lastcolor = color
  604. self.capturekeystrokes = False
  605. def _make_text_disp(self, string):
  606. return self.ax.text(self.DIST_FROM_LEFT, 0.5, string,
  607. verticalalignment='center',
  608. horizontalalignment='left',
  609. transform=self.ax.transAxes)
  610. def _rendercursor(self):
  611. # this is a hack to figure out where the cursor should go.
  612. # we draw the text up to where the cursor should go, measure
  613. # and save its dimensions, draw the real text, then put the cursor
  614. # at the saved dimensions
  615. widthtext = self.text[:self.cursor_index]
  616. no_text = False
  617. if widthtext in ["", " ", " "]:
  618. no_text = widthtext == ""
  619. widthtext = ","
  620. wt_disp = self._make_text_disp(widthtext)
  621. self.ax.figure.canvas.draw()
  622. bb = wt_disp.get_window_extent()
  623. inv = self.ax.transData.inverted()
  624. bb = inv.transform(bb)
  625. wt_disp.set_visible(False)
  626. if no_text:
  627. bb[1, 0] = bb[0, 0]
  628. # hack done
  629. self.cursor.set_visible(False)
  630. self.cursor = self.ax.vlines(bb[1, 0], bb[0, 1], bb[1, 1])
  631. self.ax.figure.canvas.draw()
  632. def _notify_submit_observers(self):
  633. if self.eventson:
  634. for cid, func in self.submit_observers.items():
  635. func(self.text)
  636. def _release(self, event):
  637. if self.ignore(event):
  638. return
  639. if event.canvas.mouse_grabber != self.ax:
  640. return
  641. event.canvas.release_mouse(self.ax)
  642. def _keypress(self, event):
  643. if self.ignore(event):
  644. return
  645. if self.capturekeystrokes:
  646. key = event.key
  647. if len(key) == 1:
  648. self.text = (self.text[:self.cursor_index] + key +
  649. self.text[self.cursor_index:])
  650. self.cursor_index += 1
  651. elif key == "right":
  652. if self.cursor_index != len(self.text):
  653. self.cursor_index += 1
  654. elif key == "left":
  655. if self.cursor_index != 0:
  656. self.cursor_index -= 1
  657. elif key == "home":
  658. self.cursor_index = 0
  659. elif key == "end":
  660. self.cursor_index = len(self.text)
  661. elif key == "backspace":
  662. if self.cursor_index != 0:
  663. self.text = (self.text[:self.cursor_index - 1] +
  664. self.text[self.cursor_index:])
  665. self.cursor_index -= 1
  666. elif key == "delete":
  667. if self.cursor_index != len(self.text):
  668. self.text = (self.text[:self.cursor_index] +
  669. self.text[self.cursor_index + 1:])
  670. self.text_disp.remove()
  671. self.text_disp = self._make_text_disp(self.text)
  672. self._rendercursor()
  673. self._notify_change_observers()
  674. if key == "enter":
  675. self._notify_submit_observers()
  676. def set_val(self, val):
  677. newval = str(val)
  678. if self.text == newval:
  679. return
  680. self.text = newval
  681. self.text_disp.remove()
  682. self.text_disp = self._make_text_disp(self.text)
  683. self._rendercursor()
  684. self._notify_change_observers()
  685. self._notify_submit_observers()
  686. def _notify_change_observers(self):
  687. if self.eventson:
  688. for cid, func in self.change_observers.items():
  689. func(self.text)
  690. def begin_typing(self, x):
  691. self.capturekeystrokes = True
  692. # Check for toolmanager handling the keypress
  693. if self.ax.figure.canvas.manager.key_press_handler_id is not None:
  694. # disable command keys so that the user can type without
  695. # command keys causing figure to be saved, etc
  696. self.reset_params = {}
  697. for key in self.params_to_disable:
  698. self.reset_params[key] = rcParams[key]
  699. rcParams[key] = []
  700. else:
  701. self.ax.figure.canvas.manager.toolmanager.keypresslock(self)
  702. def stop_typing(self):
  703. notifysubmit = False
  704. # Because _notify_submit_users might throw an error in the user's code,
  705. # we only want to call it once we've already done our cleanup.
  706. if self.capturekeystrokes:
  707. # Check for toolmanager handling the keypress
  708. if self.ax.figure.canvas.manager.key_press_handler_id is not None:
  709. # since the user is no longer typing,
  710. # reactivate the standard command keys
  711. for key in self.params_to_disable:
  712. rcParams[key] = self.reset_params[key]
  713. else:
  714. toolmanager = self.ax.figure.canvas.manager.toolmanager
  715. toolmanager.keypresslock.release(self)
  716. notifysubmit = True
  717. self.capturekeystrokes = False
  718. self.cursor.set_visible(False)
  719. self.ax.figure.canvas.draw()
  720. if notifysubmit:
  721. self._notify_submit_observers()
  722. def position_cursor(self, x):
  723. # now, we have to figure out where the cursor goes.
  724. # approximate it based on assuming all characters the same length
  725. if len(self.text) == 0:
  726. self.cursor_index = 0
  727. else:
  728. bb = self.text_disp.get_window_extent()
  729. trans = self.ax.transData
  730. inv = self.ax.transData.inverted()
  731. bb = trans.transform(inv.transform(bb))
  732. text_start = bb[0, 0]
  733. text_end = bb[1, 0]
  734. ratio = (x - text_start) / (text_end - text_start)
  735. if ratio < 0:
  736. ratio = 0
  737. if ratio > 1:
  738. ratio = 1
  739. self.cursor_index = int(len(self.text) * ratio)
  740. self._rendercursor()
  741. def _click(self, event):
  742. if self.ignore(event):
  743. return
  744. if event.inaxes != self.ax:
  745. self.stop_typing()
  746. return
  747. if not self.eventson:
  748. return
  749. if event.canvas.mouse_grabber != self.ax:
  750. event.canvas.grab_mouse(self.ax)
  751. if not self.capturekeystrokes:
  752. self.begin_typing(event.x)
  753. self.position_cursor(event.x)
  754. def _resize(self, event):
  755. self.stop_typing()
  756. def _motion(self, event):
  757. if self.ignore(event):
  758. return
  759. if event.inaxes == self.ax:
  760. c = self.hovercolor
  761. else:
  762. c = self.color
  763. if c != self._lastcolor:
  764. self.ax.set_facecolor(c)
  765. self._lastcolor = c
  766. if self.drawon:
  767. self.ax.figure.canvas.draw()
  768. def on_text_change(self, func):
  769. """
  770. When the text changes, call this *func* with event.
  771. A connection id is returned which can be used to disconnect.
  772. """
  773. cid = self.cnt
  774. self.change_observers[cid] = func
  775. self.cnt += 1
  776. return cid
  777. def on_submit(self, func):
  778. """
  779. When the user hits enter or leaves the submission box, call this
  780. *func* with event.
  781. A connection id is returned which can be used to disconnect.
  782. """
  783. cid = self.cnt
  784. self.submit_observers[cid] = func
  785. self.cnt += 1
  786. return cid
  787. def disconnect(self, cid):
  788. """Remove the observer with connection id *cid*."""
  789. for reg in [self.change_observers, self.submit_observers]:
  790. try:
  791. del reg[cid]
  792. except KeyError:
  793. pass
  794. class RadioButtons(AxesWidget):
  795. """
  796. A GUI neutral radio button.
  797. For the buttons to remain responsive you must keep a reference to this
  798. object.
  799. Connect to the RadioButtons with the :meth:`on_clicked` method.
  800. Attributes
  801. ----------
  802. ax
  803. The containing `~.axes.Axes` instance.
  804. activecolor
  805. The color of the selected button.
  806. labels
  807. A list of `~.text.Text` instances containing the button labels.
  808. circles
  809. A list of `~.patches.Circle` instances defining the buttons.
  810. value_selected : str
  811. The label text of the currently selected button.
  812. """
  813. def __init__(self, ax, labels, active=0, activecolor='blue'):
  814. """
  815. Add radio buttons to an `~.axes.Axes`.
  816. Parameters
  817. ----------
  818. ax : `~matplotlib.axes.Axes`
  819. The axes to add the buttons to.
  820. labels : list of str
  821. The button labels.
  822. active : int
  823. The index of the initially selected button.
  824. activecolor : color
  825. The color of the selected button.
  826. """
  827. AxesWidget.__init__(self, ax)
  828. self.activecolor = activecolor
  829. self.value_selected = None
  830. ax.set_xticks([])
  831. ax.set_yticks([])
  832. ax.set_navigate(False)
  833. dy = 1. / (len(labels) + 1)
  834. ys = np.linspace(1 - dy, dy, len(labels))
  835. cnt = 0
  836. axcolor = ax.get_facecolor()
  837. # scale the radius of the circle with the spacing between each one
  838. circle_radius = dy / 2 - 0.01
  839. # default to hard-coded value if the radius becomes too large
  840. circle_radius = min(circle_radius, 0.05)
  841. self.labels = []
  842. self.circles = []
  843. for y, label in zip(ys, labels):
  844. t = ax.text(0.25, y, label, transform=ax.transAxes,
  845. horizontalalignment='left',
  846. verticalalignment='center')
  847. if cnt == active:
  848. self.value_selected = label
  849. facecolor = activecolor
  850. else:
  851. facecolor = axcolor
  852. p = Circle(xy=(0.15, y), radius=circle_radius, edgecolor='black',
  853. facecolor=facecolor, transform=ax.transAxes)
  854. self.labels.append(t)
  855. self.circles.append(p)
  856. ax.add_patch(p)
  857. cnt += 1
  858. self.connect_event('button_press_event', self._clicked)
  859. self.cnt = 0
  860. self.observers = {}
  861. def _clicked(self, event):
  862. if self.ignore(event) or event.button != 1 or event.inaxes != self.ax:
  863. return
  864. pclicked = self.ax.transAxes.inverted().transform((event.x, event.y))
  865. distances = {}
  866. for i, (p, t) in enumerate(zip(self.circles, self.labels)):
  867. if (t.get_window_extent().contains(event.x, event.y)
  868. or np.linalg.norm(pclicked - p.center) < p.radius):
  869. distances[i] = np.linalg.norm(pclicked - p.center)
  870. if len(distances) > 0:
  871. closest = min(distances, key=distances.get)
  872. self.set_active(closest)
  873. def set_active(self, index):
  874. """
  875. Select button with number *index*.
  876. Callbacks will be triggered if :attr:`eventson` is True.
  877. """
  878. if 0 > index >= len(self.labels):
  879. raise ValueError("Invalid RadioButton index: %d" % index)
  880. self.value_selected = self.labels[index].get_text()
  881. for i, p in enumerate(self.circles):
  882. if i == index:
  883. color = self.activecolor
  884. else:
  885. color = self.ax.get_facecolor()
  886. p.set_facecolor(color)
  887. if self.drawon:
  888. self.ax.figure.canvas.draw()
  889. if not self.eventson:
  890. return
  891. for cid, func in self.observers.items():
  892. func(self.labels[index].get_text())
  893. def on_clicked(self, func):
  894. """
  895. Connect the callback function *func* to button click events.
  896. Returns a connection id, which can be used to disconnect the callback.
  897. """
  898. cid = self.cnt
  899. self.observers[cid] = func
  900. self.cnt += 1
  901. return cid
  902. def disconnect(self, cid):
  903. """Remove the observer with connection id *cid*."""
  904. try:
  905. del self.observers[cid]
  906. except KeyError:
  907. pass
  908. class SubplotTool(Widget):
  909. """
  910. A tool to adjust the subplot params of a `matplotlib.figure.Figure`.
  911. """
  912. def __init__(self, targetfig, toolfig):
  913. """
  914. Parameters
  915. ----------
  916. targetfig : `.Figure`
  917. The figure instance to adjust.
  918. toolfig : `.Figure`
  919. The figure instance to embed the subplot tool into.
  920. """
  921. self.targetfig = targetfig
  922. toolfig.subplots_adjust(left=0.2, right=0.9)
  923. self.axleft = toolfig.add_subplot(711)
  924. self.axleft.set_title('Click on slider to adjust subplot param')
  925. self.axleft.set_navigate(False)
  926. self.sliderleft = Slider(self.axleft, 'left',
  927. 0, 1, targetfig.subplotpars.left,
  928. closedmax=False)
  929. self.sliderleft.on_changed(self.funcleft)
  930. self.axbottom = toolfig.add_subplot(712)
  931. self.axbottom.set_navigate(False)
  932. self.sliderbottom = Slider(self.axbottom,
  933. 'bottom', 0, 1,
  934. targetfig.subplotpars.bottom,
  935. closedmax=False)
  936. self.sliderbottom.on_changed(self.funcbottom)
  937. self.axright = toolfig.add_subplot(713)
  938. self.axright.set_navigate(False)
  939. self.sliderright = Slider(self.axright, 'right', 0, 1,
  940. targetfig.subplotpars.right,
  941. closedmin=False)
  942. self.sliderright.on_changed(self.funcright)
  943. self.axtop = toolfig.add_subplot(714)
  944. self.axtop.set_navigate(False)
  945. self.slidertop = Slider(self.axtop, 'top', 0, 1,
  946. targetfig.subplotpars.top,
  947. closedmin=False)
  948. self.slidertop.on_changed(self.functop)
  949. self.axwspace = toolfig.add_subplot(715)
  950. self.axwspace.set_navigate(False)
  951. self.sliderwspace = Slider(self.axwspace, 'wspace',
  952. 0, 1, targetfig.subplotpars.wspace,
  953. closedmax=False)
  954. self.sliderwspace.on_changed(self.funcwspace)
  955. self.axhspace = toolfig.add_subplot(716)
  956. self.axhspace.set_navigate(False)
  957. self.sliderhspace = Slider(self.axhspace, 'hspace',
  958. 0, 1, targetfig.subplotpars.hspace,
  959. closedmax=False)
  960. self.sliderhspace.on_changed(self.funchspace)
  961. # constraints
  962. self.sliderleft.slidermax = self.sliderright
  963. self.sliderright.slidermin = self.sliderleft
  964. self.sliderbottom.slidermax = self.slidertop
  965. self.slidertop.slidermin = self.sliderbottom
  966. bax = toolfig.add_axes([0.8, 0.05, 0.15, 0.075])
  967. self.buttonreset = Button(bax, 'Reset')
  968. sliders = (self.sliderleft, self.sliderbottom, self.sliderright,
  969. self.slidertop, self.sliderwspace, self.sliderhspace,)
  970. def func(event):
  971. with ExitStack() as stack:
  972. # Temporarily disable drawing on self and self's sliders.
  973. stack.enter_context(cbook._setattr_cm(self, drawon=False))
  974. for slider in sliders:
  975. stack.enter_context(
  976. cbook._setattr_cm(slider, drawon=False))
  977. # Reset the slider to the initial position.
  978. for slider in sliders:
  979. slider.reset()
  980. # Draw the canvas.
  981. if self.drawon:
  982. toolfig.canvas.draw()
  983. self.targetfig.canvas.draw()
  984. # during reset there can be a temporary invalid state
  985. # depending on the order of the reset so we turn off
  986. # validation for the resetting
  987. validate = toolfig.subplotpars.validate
  988. toolfig.subplotpars.validate = False
  989. self.buttonreset.on_clicked(func)
  990. toolfig.subplotpars.validate = validate
  991. def funcleft(self, val):
  992. self.targetfig.subplots_adjust(left=val)
  993. if self.drawon:
  994. self.targetfig.canvas.draw()
  995. def funcright(self, val):
  996. self.targetfig.subplots_adjust(right=val)
  997. if self.drawon:
  998. self.targetfig.canvas.draw()
  999. def funcbottom(self, val):
  1000. self.targetfig.subplots_adjust(bottom=val)
  1001. if self.drawon:
  1002. self.targetfig.canvas.draw()
  1003. def functop(self, val):
  1004. self.targetfig.subplots_adjust(top=val)
  1005. if self.drawon:
  1006. self.targetfig.canvas.draw()
  1007. def funcwspace(self, val):
  1008. self.targetfig.subplots_adjust(wspace=val)
  1009. if self.drawon:
  1010. self.targetfig.canvas.draw()
  1011. def funchspace(self, val):
  1012. self.targetfig.subplots_adjust(hspace=val)
  1013. if self.drawon:
  1014. self.targetfig.canvas.draw()
  1015. class Cursor(AxesWidget):
  1016. """
  1017. A crosshair cursor that spans the axes and moves with mouse cursor.
  1018. For the cursor to remain responsive you must keep a reference to it.
  1019. Parameters
  1020. ----------
  1021. ax : `matplotlib.axes.Axes`
  1022. The `~.axes.Axes` to attach the cursor to.
  1023. horizOn : bool, optional, default: True
  1024. Whether to draw the horizontal line.
  1025. vertOn : bool, optional, default: True
  1026. Whether to draw the vertical line.
  1027. useblit : bool, optional, default: False
  1028. Use blitting for faster drawing if supported by the backend.
  1029. Other Parameters
  1030. ----------------
  1031. **lineprops
  1032. `.Line2D` properties that control the appearance of the lines.
  1033. See also `~.Axes.axhline`.
  1034. Examples
  1035. --------
  1036. See :doc:`/gallery/widgets/cursor`.
  1037. """
  1038. def __init__(self, ax, horizOn=True, vertOn=True, useblit=False,
  1039. **lineprops):
  1040. AxesWidget.__init__(self, ax)
  1041. self.connect_event('motion_notify_event', self.onmove)
  1042. self.connect_event('draw_event', self.clear)
  1043. self.visible = True
  1044. self.horizOn = horizOn
  1045. self.vertOn = vertOn
  1046. self.useblit = useblit and self.canvas.supports_blit
  1047. if self.useblit:
  1048. lineprops['animated'] = True
  1049. self.lineh = ax.axhline(ax.get_ybound()[0], visible=False, **lineprops)
  1050. self.linev = ax.axvline(ax.get_xbound()[0], visible=False, **lineprops)
  1051. self.background = None
  1052. self.needclear = False
  1053. def clear(self, event):
  1054. """Internal event handler to clear the cursor."""
  1055. if self.ignore(event):
  1056. return
  1057. if self.useblit:
  1058. self.background = self.canvas.copy_from_bbox(self.ax.bbox)
  1059. self.linev.set_visible(False)
  1060. self.lineh.set_visible(False)
  1061. def onmove(self, event):
  1062. """Internal event handler to draw the cursor when the mouse moves."""
  1063. if self.ignore(event):
  1064. return
  1065. if not self.canvas.widgetlock.available(self):
  1066. return
  1067. if event.inaxes != self.ax:
  1068. self.linev.set_visible(False)
  1069. self.lineh.set_visible(False)
  1070. if self.needclear:
  1071. self.canvas.draw()
  1072. self.needclear = False
  1073. return
  1074. self.needclear = True
  1075. if not self.visible:
  1076. return
  1077. self.linev.set_xdata((event.xdata, event.xdata))
  1078. self.lineh.set_ydata((event.ydata, event.ydata))
  1079. self.linev.set_visible(self.visible and self.vertOn)
  1080. self.lineh.set_visible(self.visible and self.horizOn)
  1081. self._update()
  1082. def _update(self):
  1083. if self.useblit:
  1084. if self.background is not None:
  1085. self.canvas.restore_region(self.background)
  1086. self.ax.draw_artist(self.linev)
  1087. self.ax.draw_artist(self.lineh)
  1088. self.canvas.blit(self.ax.bbox)
  1089. else:
  1090. self.canvas.draw_idle()
  1091. return False
  1092. class MultiCursor(Widget):
  1093. """
  1094. Provide a vertical (default) and/or horizontal line cursor shared between
  1095. multiple axes.
  1096. For the cursor to remain responsive you must keep a reference to it.
  1097. Example usage::
  1098. from matplotlib.widgets import MultiCursor
  1099. import matplotlib.pyplot as plt
  1100. import numpy as np
  1101. fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
  1102. t = np.arange(0.0, 2.0, 0.01)
  1103. ax1.plot(t, np.sin(2*np.pi*t))
  1104. ax2.plot(t, np.sin(4*np.pi*t))
  1105. multi = MultiCursor(fig.canvas, (ax1, ax2), color='r', lw=1,
  1106. horizOn=False, vertOn=True)
  1107. plt.show()
  1108. """
  1109. def __init__(self, canvas, axes, useblit=True, horizOn=False, vertOn=True,
  1110. **lineprops):
  1111. self.canvas = canvas
  1112. self.axes = axes
  1113. self.horizOn = horizOn
  1114. self.vertOn = vertOn
  1115. xmin, xmax = axes[-1].get_xlim()
  1116. ymin, ymax = axes[-1].get_ylim()
  1117. xmid = 0.5 * (xmin + xmax)
  1118. ymid = 0.5 * (ymin + ymax)
  1119. self.visible = True
  1120. self.useblit = useblit and self.canvas.supports_blit
  1121. self.background = None
  1122. self.needclear = False
  1123. if self.useblit:
  1124. lineprops['animated'] = True
  1125. if vertOn:
  1126. self.vlines = [ax.axvline(xmid, visible=False, **lineprops)
  1127. for ax in axes]
  1128. else:
  1129. self.vlines = []
  1130. if horizOn:
  1131. self.hlines = [ax.axhline(ymid, visible=False, **lineprops)
  1132. for ax in axes]
  1133. else:
  1134. self.hlines = []
  1135. self.connect()
  1136. def connect(self):
  1137. """connect events"""
  1138. self._cidmotion = self.canvas.mpl_connect('motion_notify_event',
  1139. self.onmove)
  1140. self._ciddraw = self.canvas.mpl_connect('draw_event', self.clear)
  1141. def disconnect(self):
  1142. """disconnect events"""
  1143. self.canvas.mpl_disconnect(self._cidmotion)
  1144. self.canvas.mpl_disconnect(self._ciddraw)
  1145. def clear(self, event):
  1146. """clear the cursor"""
  1147. if self.ignore(event):
  1148. return
  1149. if self.useblit:
  1150. self.background = (
  1151. self.canvas.copy_from_bbox(self.canvas.figure.bbox))
  1152. for line in self.vlines + self.hlines:
  1153. line.set_visible(False)
  1154. def onmove(self, event):
  1155. if self.ignore(event):
  1156. return
  1157. if event.inaxes is None:
  1158. return
  1159. if not self.canvas.widgetlock.available(self):
  1160. return
  1161. self.needclear = True
  1162. if not self.visible:
  1163. return
  1164. if self.vertOn:
  1165. for line in self.vlines:
  1166. line.set_xdata((event.xdata, event.xdata))
  1167. line.set_visible(self.visible)
  1168. if self.horizOn:
  1169. for line in self.hlines:
  1170. line.set_ydata((event.ydata, event.ydata))
  1171. line.set_visible(self.visible)
  1172. self._update()
  1173. def _update(self):
  1174. if self.useblit:
  1175. if self.background is not None:
  1176. self.canvas.restore_region(self.background)
  1177. if self.vertOn:
  1178. for ax, line in zip(self.axes, self.vlines):
  1179. ax.draw_artist(line)
  1180. if self.horizOn:
  1181. for ax, line in zip(self.axes, self.hlines):
  1182. ax.draw_artist(line)
  1183. self.canvas.blit()
  1184. else:
  1185. self.canvas.draw_idle()
  1186. class _SelectorWidget(AxesWidget):
  1187. def __init__(self, ax, onselect, useblit=False, button=None,
  1188. state_modifier_keys=None):
  1189. AxesWidget.__init__(self, ax)
  1190. self.visible = True
  1191. self.onselect = onselect
  1192. self.useblit = useblit and self.canvas.supports_blit
  1193. self.connect_default_events()
  1194. self.state_modifier_keys = dict(move=' ', clear='escape',
  1195. square='shift', center='control')
  1196. self.state_modifier_keys.update(state_modifier_keys or {})
  1197. self.background = None
  1198. self.artists = []
  1199. if isinstance(button, Integral):
  1200. self.validButtons = [button]
  1201. else:
  1202. self.validButtons = button
  1203. # will save the data (position at mouseclick)
  1204. self.eventpress = None
  1205. # will save the data (pos. at mouserelease)
  1206. self.eventrelease = None
  1207. self._prev_event = None
  1208. self.state = set()
  1209. def set_active(self, active):
  1210. AxesWidget.set_active(self, active)
  1211. if active:
  1212. self.update_background(None)
  1213. def update_background(self, event):
  1214. """force an update of the background"""
  1215. # If you add a call to `ignore` here, you'll want to check edge case:
  1216. # `release` can call a draw event even when `ignore` is True.
  1217. if self.useblit:
  1218. self.background = self.canvas.copy_from_bbox(self.ax.bbox)
  1219. def connect_default_events(self):
  1220. """Connect the major canvas events to methods."""
  1221. self.connect_event('motion_notify_event', self.onmove)
  1222. self.connect_event('button_press_event', self.press)
  1223. self.connect_event('button_release_event', self.release)
  1224. self.connect_event('draw_event', self.update_background)
  1225. self.connect_event('key_press_event', self.on_key_press)
  1226. self.connect_event('key_release_event', self.on_key_release)
  1227. self.connect_event('scroll_event', self.on_scroll)
  1228. def ignore(self, event):
  1229. # docstring inherited
  1230. if not self.active or not self.ax.get_visible():
  1231. return True
  1232. # If canvas was locked
  1233. if not self.canvas.widgetlock.available(self):
  1234. return True
  1235. if not hasattr(event, 'button'):
  1236. event.button = None
  1237. # Only do rectangle selection if event was triggered
  1238. # with a desired button
  1239. if (self.validButtons is not None
  1240. and event.button not in self.validButtons):
  1241. return True
  1242. # If no button was pressed yet ignore the event if it was out
  1243. # of the axes
  1244. if self.eventpress is None:
  1245. return event.inaxes != self.ax
  1246. # If a button was pressed, check if the release-button is the same.
  1247. if event.button == self.eventpress.button:
  1248. return False
  1249. # If a button was pressed, check if the release-button is the same.
  1250. return (event.inaxes != self.ax or
  1251. event.button != self.eventpress.button)
  1252. def update(self):
  1253. """
  1254. Draw using blit() or draw_idle() depending on ``self.useblit``.
  1255. """
  1256. if not self.ax.get_visible():
  1257. return False
  1258. if self.useblit:
  1259. if self.background is not None:
  1260. self.canvas.restore_region(self.background)
  1261. for artist in self.artists:
  1262. self.ax.draw_artist(artist)
  1263. self.canvas.blit(self.ax.bbox)
  1264. else:
  1265. self.canvas.draw_idle()
  1266. return False
  1267. def _get_data(self, event):
  1268. """Get the xdata and ydata for event, with limits"""
  1269. if event.xdata is None:
  1270. return None, None
  1271. x0, x1 = self.ax.get_xbound()
  1272. y0, y1 = self.ax.get_ybound()
  1273. xdata = max(x0, event.xdata)
  1274. xdata = min(x1, xdata)
  1275. ydata = max(y0, event.ydata)
  1276. ydata = min(y1, ydata)
  1277. return xdata, ydata
  1278. def _clean_event(self, event):
  1279. """Clean up an event
  1280. Use prev event if there is no xdata
  1281. Limit the xdata and ydata to the axes limits
  1282. Set the prev event
  1283. """
  1284. if event.xdata is None:
  1285. event = self._prev_event
  1286. else:
  1287. event = copy.copy(event)
  1288. event.xdata, event.ydata = self._get_data(event)
  1289. self._prev_event = event
  1290. return event
  1291. def press(self, event):
  1292. """Button press handler and validator"""
  1293. if not self.ignore(event):
  1294. event = self._clean_event(event)
  1295. self.eventpress = event
  1296. self._prev_event = event
  1297. key = event.key or ''
  1298. key = key.replace('ctrl', 'control')
  1299. # move state is locked in on a button press
  1300. if key == self.state_modifier_keys['move']:
  1301. self.state.add('move')
  1302. self._press(event)
  1303. return True
  1304. return False
  1305. def _press(self, event):
  1306. """Button press handler"""
  1307. def release(self, event):
  1308. """Button release event handler and validator"""
  1309. if not self.ignore(event) and self.eventpress:
  1310. event = self._clean_event(event)
  1311. self.eventrelease = event
  1312. self._release(event)
  1313. self.eventpress = None
  1314. self.eventrelease = None
  1315. self.state.discard('move')
  1316. return True
  1317. return False
  1318. def _release(self, event):
  1319. """Button release event handler"""
  1320. def onmove(self, event):
  1321. """Cursor move event handler and validator"""
  1322. if not self.ignore(event) and self.eventpress:
  1323. event = self._clean_event(event)
  1324. self._onmove(event)
  1325. return True
  1326. return False
  1327. def _onmove(self, event):
  1328. """Cursor move event handler"""
  1329. def on_scroll(self, event):
  1330. """Mouse scroll event handler and validator"""
  1331. if not self.ignore(event):
  1332. self._on_scroll(event)
  1333. def _on_scroll(self, event):
  1334. """Mouse scroll event handler"""
  1335. def on_key_press(self, event):
  1336. """Key press event handler and validator for all selection widgets"""
  1337. if self.active:
  1338. key = event.key or ''
  1339. key = key.replace('ctrl', 'control')
  1340. if key == self.state_modifier_keys['clear']:
  1341. for artist in self.artists:
  1342. artist.set_visible(False)
  1343. self.update()
  1344. return
  1345. for (state, modifier) in self.state_modifier_keys.items():
  1346. if modifier in key:
  1347. self.state.add(state)
  1348. self._on_key_press(event)
  1349. def _on_key_press(self, event):
  1350. """Key press event handler - use for widget-specific key press actions.
  1351. """
  1352. def on_key_release(self, event):
  1353. """Key release event handler and validator."""
  1354. if self.active:
  1355. key = event.key or ''
  1356. for (state, modifier) in self.state_modifier_keys.items():
  1357. if modifier in key:
  1358. self.state.discard(state)
  1359. self._on_key_release(event)
  1360. def _on_key_release(self, event):
  1361. """Key release event handler."""
  1362. def set_visible(self, visible):
  1363. """Set the visibility of our artists."""
  1364. self.visible = visible
  1365. for artist in self.artists:
  1366. artist.set_visible(visible)
  1367. class SpanSelector(_SelectorWidget):
  1368. """
  1369. Visually select a min/max range on a single axis and call a function with
  1370. those values.
  1371. To guarantee that the selector remains responsive, keep a reference to it.
  1372. In order to turn off the SpanSelector, set `span_selector.active=False`. To
  1373. turn it back on, set `span_selector.active=True`.
  1374. Parameters
  1375. ----------
  1376. ax : `matplotlib.axes.Axes` object
  1377. onselect : func(min, max), min/max are floats
  1378. direction : {"horizontal", "vertical"}
  1379. The direction along which to draw the span selector.
  1380. minspan : float, default is None
  1381. If selection is less than *minspan*, do not call *onselect*.
  1382. useblit : bool, default is False
  1383. If True, use the backend-dependent blitting features for faster
  1384. canvas updates.
  1385. rectprops : dict, default is None
  1386. Dictionary of `matplotlib.patches.Patch` properties.
  1387. onmove_callback : func(min, max), min/max are floats, default is None
  1388. Called on mouse move while the span is being selected.
  1389. span_stays : bool, default is False
  1390. If True, the span stays visible after the mouse is released.
  1391. button : `.MouseButton` or list of `.MouseButton`
  1392. The mouse buttons which activate the span selector.
  1393. Examples
  1394. --------
  1395. >>> import matplotlib.pyplot as plt
  1396. >>> import matplotlib.widgets as mwidgets
  1397. >>> fig, ax = plt.subplots()
  1398. >>> ax.plot([1, 2, 3], [10, 50, 100])
  1399. >>> def onselect(vmin, vmax):
  1400. ... print(vmin, vmax)
  1401. >>> rectprops = dict(facecolor='blue', alpha=0.5)
  1402. >>> span = mwidgets.SpanSelector(ax, onselect, 'horizontal',
  1403. ... rectprops=rectprops)
  1404. >>> fig.show()
  1405. See also: :doc:`/gallery/widgets/span_selector`
  1406. """
  1407. def __init__(self, ax, onselect, direction, minspan=None, useblit=False,
  1408. rectprops=None, onmove_callback=None, span_stays=False,
  1409. button=None):
  1410. _SelectorWidget.__init__(self, ax, onselect, useblit=useblit,
  1411. button=button)
  1412. if rectprops is None:
  1413. rectprops = dict(facecolor='red', alpha=0.5)
  1414. rectprops['animated'] = self.useblit
  1415. cbook._check_in_list(['horizontal', 'vertical'], direction=direction)
  1416. self.direction = direction
  1417. self.rect = None
  1418. self.pressv = None
  1419. self.rectprops = rectprops
  1420. self.onmove_callback = onmove_callback
  1421. self.minspan = minspan
  1422. self.span_stays = span_stays
  1423. # Needed when dragging out of axes
  1424. self.prev = (0, 0)
  1425. # Reset canvas so that `new_axes` connects events.
  1426. self.canvas = None
  1427. self.new_axes(ax)
  1428. def new_axes(self, ax):
  1429. """Set SpanSelector to operate on a new Axes."""
  1430. self.ax = ax
  1431. if self.canvas is not ax.figure.canvas:
  1432. if self.canvas is not None:
  1433. self.disconnect_events()
  1434. self.canvas = ax.figure.canvas
  1435. self.connect_default_events()
  1436. if self.direction == 'horizontal':
  1437. trans = blended_transform_factory(self.ax.transData,
  1438. self.ax.transAxes)
  1439. w, h = 0, 1
  1440. else:
  1441. trans = blended_transform_factory(self.ax.transAxes,
  1442. self.ax.transData)
  1443. w, h = 1, 0
  1444. self.rect = Rectangle((0, 0), w, h,
  1445. transform=trans,
  1446. visible=False,
  1447. **self.rectprops)
  1448. if self.span_stays:
  1449. self.stay_rect = Rectangle((0, 0), w, h,
  1450. transform=trans,
  1451. visible=False,
  1452. **self.rectprops)
  1453. self.stay_rect.set_animated(False)
  1454. self.ax.add_patch(self.stay_rect)
  1455. self.ax.add_patch(self.rect)
  1456. self.artists = [self.rect]
  1457. def ignore(self, event):
  1458. # docstring inherited
  1459. return _SelectorWidget.ignore(self, event) or not self.visible
  1460. def _press(self, event):
  1461. """on button press event"""
  1462. self.rect.set_visible(self.visible)
  1463. if self.span_stays:
  1464. self.stay_rect.set_visible(False)
  1465. # really force a draw so that the stay rect is not in
  1466. # the blit background
  1467. if self.useblit:
  1468. self.canvas.draw()
  1469. xdata, ydata = self._get_data(event)
  1470. if self.direction == 'horizontal':
  1471. self.pressv = xdata
  1472. else:
  1473. self.pressv = ydata
  1474. self._set_span_xy(event)
  1475. return False
  1476. def _release(self, event):
  1477. """on button release event"""
  1478. if self.pressv is None:
  1479. return
  1480. self.rect.set_visible(False)
  1481. if self.span_stays:
  1482. self.stay_rect.set_x(self.rect.get_x())
  1483. self.stay_rect.set_y(self.rect.get_y())
  1484. self.stay_rect.set_width(self.rect.get_width())
  1485. self.stay_rect.set_height(self.rect.get_height())
  1486. self.stay_rect.set_visible(True)
  1487. self.canvas.draw_idle()
  1488. vmin = self.pressv
  1489. xdata, ydata = self._get_data(event)
  1490. if self.direction == 'horizontal':
  1491. vmax = xdata or self.prev[0]
  1492. else:
  1493. vmax = ydata or self.prev[1]
  1494. if vmin > vmax:
  1495. vmin, vmax = vmax, vmin
  1496. span = vmax - vmin
  1497. if self.minspan is not None and span < self.minspan:
  1498. return
  1499. self.onselect(vmin, vmax)
  1500. self.pressv = None
  1501. return False
  1502. @cbook.deprecated("3.1")
  1503. @property
  1504. def buttonDown(self):
  1505. return False
  1506. def _onmove(self, event):
  1507. """on motion notify event"""
  1508. if self.pressv is None:
  1509. return
  1510. self._set_span_xy(event)
  1511. if self.onmove_callback is not None:
  1512. vmin = self.pressv
  1513. xdata, ydata = self._get_data(event)
  1514. if self.direction == 'horizontal':
  1515. vmax = xdata or self.prev[0]
  1516. else:
  1517. vmax = ydata or self.prev[1]
  1518. if vmin > vmax:
  1519. vmin, vmax = vmax, vmin
  1520. self.onmove_callback(vmin, vmax)
  1521. self.update()
  1522. return False
  1523. def _set_span_xy(self, event):
  1524. """Setting the span coordinates"""
  1525. x, y = self._get_data(event)
  1526. if x is None:
  1527. return
  1528. self.prev = x, y
  1529. if self.direction == 'horizontal':
  1530. v = x
  1531. else:
  1532. v = y
  1533. minv, maxv = v, self.pressv
  1534. if minv > maxv:
  1535. minv, maxv = maxv, minv
  1536. if self.direction == 'horizontal':
  1537. self.rect.set_x(minv)
  1538. self.rect.set_width(maxv - minv)
  1539. else:
  1540. self.rect.set_y(minv)
  1541. self.rect.set_height(maxv - minv)
  1542. class ToolHandles:
  1543. """
  1544. Control handles for canvas tools.
  1545. Parameters
  1546. ----------
  1547. ax : `matplotlib.axes.Axes`
  1548. Matplotlib axes where tool handles are displayed.
  1549. x, y : 1D arrays
  1550. Coordinates of control handles.
  1551. marker : str
  1552. Shape of marker used to display handle. See `matplotlib.pyplot.plot`.
  1553. marker_props : dict
  1554. Additional marker properties. See `matplotlib.lines.Line2D`.
  1555. """
  1556. def __init__(self, ax, x, y, marker='o', marker_props=None, useblit=True):
  1557. self.ax = ax
  1558. props = dict(marker=marker, markersize=7, mfc='w', ls='none',
  1559. alpha=0.5, visible=False, label='_nolegend_')
  1560. props.update(marker_props if marker_props is not None else {})
  1561. self._markers = Line2D(x, y, animated=useblit, **props)
  1562. self.ax.add_line(self._markers)
  1563. self.artist = self._markers
  1564. @property
  1565. def x(self):
  1566. return self._markers.get_xdata()
  1567. @property
  1568. def y(self):
  1569. return self._markers.get_ydata()
  1570. def set_data(self, pts, y=None):
  1571. """Set x and y positions of handles"""
  1572. if y is not None:
  1573. x = pts
  1574. pts = np.array([x, y])
  1575. self._markers.set_data(pts)
  1576. def set_visible(self, val):
  1577. self._markers.set_visible(val)
  1578. def set_animated(self, val):
  1579. self._markers.set_animated(val)
  1580. def closest(self, x, y):
  1581. """Return index and pixel distance to closest index."""
  1582. pts = np.column_stack([self.x, self.y])
  1583. # Transform data coordinates to pixel coordinates.
  1584. pts = self.ax.transData.transform(pts)
  1585. diff = pts - [x, y]
  1586. dist = np.hypot(*diff.T)
  1587. min_index = np.argmin(dist)
  1588. return min_index, dist[min_index]
  1589. class RectangleSelector(_SelectorWidget):
  1590. """
  1591. Select a rectangular region of an axes.
  1592. For the cursor to remain responsive you must keep a reference to it.
  1593. Example usage::
  1594. import numpy as np
  1595. import matplotlib.pyplot as plt
  1596. from matplotlib.widgets import RectangleSelector
  1597. def onselect(eclick, erelease):
  1598. "eclick and erelease are matplotlib events at press and release."
  1599. print('startposition: (%f, %f)' % (eclick.xdata, eclick.ydata))
  1600. print('endposition : (%f, %f)' % (erelease.xdata, erelease.ydata))
  1601. print('used button : ', eclick.button)
  1602. def toggle_selector(event):
  1603. print('Key pressed.')
  1604. if event.key in ['Q', 'q'] and toggle_selector.RS.active:
  1605. print('RectangleSelector deactivated.')
  1606. toggle_selector.RS.set_active(False)
  1607. if event.key in ['A', 'a'] and not toggle_selector.RS.active:
  1608. print('RectangleSelector activated.')
  1609. toggle_selector.RS.set_active(True)
  1610. x = np.arange(100.) / 99
  1611. y = np.sin(x)
  1612. fig, ax = plt.subplots()
  1613. ax.plot(x, y)
  1614. toggle_selector.RS = RectangleSelector(ax, onselect, drawtype='line')
  1615. fig.canvas.mpl_connect('key_press_event', toggle_selector)
  1616. plt.show()
  1617. """
  1618. _shape_klass = Rectangle
  1619. def __init__(self, ax, onselect, drawtype='box',
  1620. minspanx=None, minspany=None, useblit=False,
  1621. lineprops=None, rectprops=None, spancoords='data',
  1622. button=None, maxdist=10, marker_props=None,
  1623. interactive=False, state_modifier_keys=None):
  1624. """
  1625. Create a selector in *ax*. When a selection is made, clear
  1626. the span and call onselect with::
  1627. onselect(pos_1, pos_2)
  1628. and clear the drawn box/line. The ``pos_1`` and ``pos_2`` are
  1629. arrays of length 2 containing the x- and y-coordinate.
  1630. If *minspanx* is not *None* then events smaller than *minspanx*
  1631. in x direction are ignored (it's the same for y).
  1632. The rectangle is drawn with *rectprops*; default::
  1633. rectprops = dict(facecolor='red', edgecolor = 'black',
  1634. alpha=0.2, fill=True)
  1635. The line is drawn with *lineprops*; default::
  1636. lineprops = dict(color='black', linestyle='-',
  1637. linewidth = 2, alpha=0.5)
  1638. Use *drawtype* if you want the mouse to draw a line,
  1639. a box or nothing between click and actual position by setting
  1640. ``drawtype = 'line'``, ``drawtype='box'`` or ``drawtype = 'none'``.
  1641. Drawing a line would result in a line from vertex A to vertex C in
  1642. a rectangle ABCD.
  1643. *spancoords* is one of 'data' or 'pixels'. If 'data', *minspanx*
  1644. and *minspanx* will be interpreted in the same coordinates as
  1645. the x and y axis. If 'pixels', they are in pixels.
  1646. *button* is a list of integers indicating which mouse buttons should
  1647. be used for rectangle selection. You can also specify a single
  1648. integer if only a single button is desired. Default is *None*,
  1649. which does not limit which button can be used.
  1650. Note, typically:
  1651. 1 = left mouse button
  1652. 2 = center mouse button (scroll wheel)
  1653. 3 = right mouse button
  1654. *interactive* will draw a set of handles and allow you interact
  1655. with the widget after it is drawn.
  1656. *state_modifier_keys* are keyboard modifiers that affect the behavior
  1657. of the widget.
  1658. The defaults are:
  1659. dict(move=' ', clear='escape', square='shift', center='ctrl')
  1660. Keyboard modifiers, which:
  1661. 'move': Move the existing shape.
  1662. 'clear': Clear the current shape.
  1663. 'square': Makes the shape square.
  1664. 'center': Make the initial point the center of the shape.
  1665. 'square' and 'center' can be combined.
  1666. """
  1667. _SelectorWidget.__init__(self, ax, onselect, useblit=useblit,
  1668. button=button,
  1669. state_modifier_keys=state_modifier_keys)
  1670. self.to_draw = None
  1671. self.visible = True
  1672. self.interactive = interactive
  1673. if drawtype == 'none': # draw a line but make it invisible
  1674. drawtype = 'line'
  1675. self.visible = False
  1676. if drawtype == 'box':
  1677. if rectprops is None:
  1678. rectprops = dict(facecolor='red', edgecolor='black',
  1679. alpha=0.2, fill=True)
  1680. rectprops['animated'] = self.useblit
  1681. self.rectprops = rectprops
  1682. self.to_draw = self._shape_klass((0, 0), 0, 1, visible=False,
  1683. **self.rectprops)
  1684. self.ax.add_patch(self.to_draw)
  1685. if drawtype == 'line':
  1686. if lineprops is None:
  1687. lineprops = dict(color='black', linestyle='-',
  1688. linewidth=2, alpha=0.5)
  1689. lineprops['animated'] = self.useblit
  1690. self.lineprops = lineprops
  1691. self.to_draw = Line2D([0, 0], [0, 0], visible=False,
  1692. **self.lineprops)
  1693. self.ax.add_line(self.to_draw)
  1694. self.minspanx = minspanx
  1695. self.minspany = minspany
  1696. cbook._check_in_list(['data', 'pixels'], spancoords=spancoords)
  1697. self.spancoords = spancoords
  1698. self.drawtype = drawtype
  1699. self.maxdist = maxdist
  1700. if rectprops is None:
  1701. props = dict(mec='r')
  1702. else:
  1703. props = dict(mec=rectprops.get('edgecolor', 'r'))
  1704. self._corner_order = ['NW', 'NE', 'SE', 'SW']
  1705. xc, yc = self.corners
  1706. self._corner_handles = ToolHandles(self.ax, xc, yc, marker_props=props,
  1707. useblit=self.useblit)
  1708. self._edge_order = ['W', 'N', 'E', 'S']
  1709. xe, ye = self.edge_centers
  1710. self._edge_handles = ToolHandles(self.ax, xe, ye, marker='s',
  1711. marker_props=props,
  1712. useblit=self.useblit)
  1713. xc, yc = self.center
  1714. self._center_handle = ToolHandles(self.ax, [xc], [yc], marker='s',
  1715. marker_props=props,
  1716. useblit=self.useblit)
  1717. self.active_handle = None
  1718. self.artists = [self.to_draw, self._center_handle.artist,
  1719. self._corner_handles.artist,
  1720. self._edge_handles.artist]
  1721. if not self.interactive:
  1722. self.artists = [self.to_draw]
  1723. self._extents_on_press = None
  1724. def _press(self, event):
  1725. """on button press event"""
  1726. # make the drawed box/line visible get the click-coordinates,
  1727. # button, ...
  1728. if self.interactive and self.to_draw.get_visible():
  1729. self._set_active_handle(event)
  1730. else:
  1731. self.active_handle = None
  1732. if self.active_handle is None or not self.interactive:
  1733. # Clear previous rectangle before drawing new rectangle.
  1734. self.update()
  1735. if not self.interactive:
  1736. x = event.xdata
  1737. y = event.ydata
  1738. self.extents = x, x, y, y
  1739. self.set_visible(self.visible)
  1740. def _release(self, event):
  1741. """on button release event"""
  1742. if not self.interactive:
  1743. self.to_draw.set_visible(False)
  1744. # update the eventpress and eventrelease with the resulting extents
  1745. x1, x2, y1, y2 = self.extents
  1746. self.eventpress.xdata = x1
  1747. self.eventpress.ydata = y1
  1748. xy1 = self.ax.transData.transform([x1, y1])
  1749. self.eventpress.x, self.eventpress.y = xy1
  1750. self.eventrelease.xdata = x2
  1751. self.eventrelease.ydata = y2
  1752. xy2 = self.ax.transData.transform([x2, y2])
  1753. self.eventrelease.x, self.eventrelease.y = xy2
  1754. if self.spancoords == 'data':
  1755. xmin, ymin = self.eventpress.xdata, self.eventpress.ydata
  1756. xmax, ymax = self.eventrelease.xdata, self.eventrelease.ydata
  1757. # calculate dimensions of box or line get values in the right order
  1758. elif self.spancoords == 'pixels':
  1759. xmin, ymin = self.eventpress.x, self.eventpress.y
  1760. xmax, ymax = self.eventrelease.x, self.eventrelease.y
  1761. else:
  1762. cbook._check_in_list(['data', 'pixels'],
  1763. spancoords=self.spancoords)
  1764. if xmin > xmax:
  1765. xmin, xmax = xmax, xmin
  1766. if ymin > ymax:
  1767. ymin, ymax = ymax, ymin
  1768. spanx = xmax - xmin
  1769. spany = ymax - ymin
  1770. xproblems = self.minspanx is not None and spanx < self.minspanx
  1771. yproblems = self.minspany is not None and spany < self.minspany
  1772. # check if drawn distance (if it exists) is not too small in
  1773. # either x or y-direction
  1774. if self.drawtype != 'none' and (xproblems or yproblems):
  1775. for artist in self.artists:
  1776. artist.set_visible(False)
  1777. self.update()
  1778. return
  1779. # call desired function
  1780. self.onselect(self.eventpress, self.eventrelease)
  1781. self.update()
  1782. return False
  1783. def _onmove(self, event):
  1784. """on motion notify event if box/line is wanted"""
  1785. # resize an existing shape
  1786. if self.active_handle and self.active_handle != 'C':
  1787. x1, x2, y1, y2 = self._extents_on_press
  1788. if self.active_handle in ['E', 'W'] + self._corner_order:
  1789. x2 = event.xdata
  1790. if self.active_handle in ['N', 'S'] + self._corner_order:
  1791. y2 = event.ydata
  1792. # move existing shape
  1793. elif (('move' in self.state or self.active_handle == 'C')
  1794. and self._extents_on_press is not None):
  1795. x1, x2, y1, y2 = self._extents_on_press
  1796. dx = event.xdata - self.eventpress.xdata
  1797. dy = event.ydata - self.eventpress.ydata
  1798. x1 += dx
  1799. x2 += dx
  1800. y1 += dy
  1801. y2 += dy
  1802. # new shape
  1803. else:
  1804. center = [self.eventpress.xdata, self.eventpress.ydata]
  1805. center_pix = [self.eventpress.x, self.eventpress.y]
  1806. dx = (event.xdata - center[0]) / 2.
  1807. dy = (event.ydata - center[1]) / 2.
  1808. # square shape
  1809. if 'square' in self.state:
  1810. dx_pix = abs(event.x - center_pix[0])
  1811. dy_pix = abs(event.y - center_pix[1])
  1812. if not dx_pix:
  1813. return
  1814. maxd = max(abs(dx_pix), abs(dy_pix))
  1815. if abs(dx_pix) < maxd:
  1816. dx *= maxd / (abs(dx_pix) + 1e-6)
  1817. if abs(dy_pix) < maxd:
  1818. dy *= maxd / (abs(dy_pix) + 1e-6)
  1819. # from center
  1820. if 'center' in self.state:
  1821. dx *= 2
  1822. dy *= 2
  1823. # from corner
  1824. else:
  1825. center[0] += dx
  1826. center[1] += dy
  1827. x1, x2, y1, y2 = (center[0] - dx, center[0] + dx,
  1828. center[1] - dy, center[1] + dy)
  1829. self.extents = x1, x2, y1, y2
  1830. @property
  1831. def _rect_bbox(self):
  1832. if self.drawtype == 'box':
  1833. x0 = self.to_draw.get_x()
  1834. y0 = self.to_draw.get_y()
  1835. width = self.to_draw.get_width()
  1836. height = self.to_draw.get_height()
  1837. return x0, y0, width, height
  1838. else:
  1839. x, y = self.to_draw.get_data()
  1840. x0, x1 = min(x), max(x)
  1841. y0, y1 = min(y), max(y)
  1842. return x0, y0, x1 - x0, y1 - y0
  1843. @property
  1844. def corners(self):
  1845. """Corners of rectangle from lower left, moving clockwise."""
  1846. x0, y0, width, height = self._rect_bbox
  1847. xc = x0, x0 + width, x0 + width, x0
  1848. yc = y0, y0, y0 + height, y0 + height
  1849. return xc, yc
  1850. @property
  1851. def edge_centers(self):
  1852. """Midpoint of rectangle edges from left, moving clockwise."""
  1853. x0, y0, width, height = self._rect_bbox
  1854. w = width / 2.
  1855. h = height / 2.
  1856. xe = x0, x0 + w, x0 + width, x0 + w
  1857. ye = y0 + h, y0, y0 + h, y0 + height
  1858. return xe, ye
  1859. @property
  1860. def center(self):
  1861. """Center of rectangle"""
  1862. x0, y0, width, height = self._rect_bbox
  1863. return x0 + width / 2., y0 + height / 2.
  1864. @property
  1865. def extents(self):
  1866. """Return (xmin, xmax, ymin, ymax)."""
  1867. x0, y0, width, height = self._rect_bbox
  1868. xmin, xmax = sorted([x0, x0 + width])
  1869. ymin, ymax = sorted([y0, y0 + height])
  1870. return xmin, xmax, ymin, ymax
  1871. @extents.setter
  1872. def extents(self, extents):
  1873. # Update displayed shape
  1874. self.draw_shape(extents)
  1875. # Update displayed handles
  1876. self._corner_handles.set_data(*self.corners)
  1877. self._edge_handles.set_data(*self.edge_centers)
  1878. self._center_handle.set_data(*self.center)
  1879. self.set_visible(self.visible)
  1880. self.update()
  1881. def draw_shape(self, extents):
  1882. x0, x1, y0, y1 = extents
  1883. xmin, xmax = sorted([x0, x1])
  1884. ymin, ymax = sorted([y0, y1])
  1885. xlim = sorted(self.ax.get_xlim())
  1886. ylim = sorted(self.ax.get_ylim())
  1887. xmin = max(xlim[0], xmin)
  1888. ymin = max(ylim[0], ymin)
  1889. xmax = min(xmax, xlim[1])
  1890. ymax = min(ymax, ylim[1])
  1891. if self.drawtype == 'box':
  1892. self.to_draw.set_x(xmin)
  1893. self.to_draw.set_y(ymin)
  1894. self.to_draw.set_width(xmax - xmin)
  1895. self.to_draw.set_height(ymax - ymin)
  1896. elif self.drawtype == 'line':
  1897. self.to_draw.set_data([xmin, xmax], [ymin, ymax])
  1898. def _set_active_handle(self, event):
  1899. """Set active handle based on the location of the mouse event"""
  1900. # Note: event.xdata/ydata in data coordinates, event.x/y in pixels
  1901. c_idx, c_dist = self._corner_handles.closest(event.x, event.y)
  1902. e_idx, e_dist = self._edge_handles.closest(event.x, event.y)
  1903. m_idx, m_dist = self._center_handle.closest(event.x, event.y)
  1904. if 'move' in self.state:
  1905. self.active_handle = 'C'
  1906. self._extents_on_press = self.extents
  1907. # Set active handle as closest handle, if mouse click is close enough.
  1908. elif m_dist < self.maxdist * 2:
  1909. self.active_handle = 'C'
  1910. elif c_dist > self.maxdist and e_dist > self.maxdist:
  1911. self.active_handle = None
  1912. return
  1913. elif c_dist < e_dist:
  1914. self.active_handle = self._corner_order[c_idx]
  1915. else:
  1916. self.active_handle = self._edge_order[e_idx]
  1917. # Save coordinates of rectangle at the start of handle movement.
  1918. x1, x2, y1, y2 = self.extents
  1919. # Switch variables so that only x2 and/or y2 are updated on move.
  1920. if self.active_handle in ['W', 'SW', 'NW']:
  1921. x1, x2 = x2, event.xdata
  1922. if self.active_handle in ['N', 'NW', 'NE']:
  1923. y1, y2 = y2, event.ydata
  1924. self._extents_on_press = x1, x2, y1, y2
  1925. @property
  1926. def geometry(self):
  1927. """
  1928. Return an array of shape (2, 5) containing the
  1929. x (``RectangleSelector.geometry[1, :]``) and
  1930. y (``RectangleSelector.geometry[0, :]``) coordinates
  1931. of the four corners of the rectangle starting and ending
  1932. in the top left corner.
  1933. """
  1934. if hasattr(self.to_draw, 'get_verts'):
  1935. xfm = self.ax.transData.inverted()
  1936. y, x = xfm.transform(self.to_draw.get_verts()).T
  1937. return np.array([x, y])
  1938. else:
  1939. return np.array(self.to_draw.get_data())
  1940. class EllipseSelector(RectangleSelector):
  1941. """
  1942. Select an elliptical region of an axes.
  1943. For the cursor to remain responsive you must keep a reference to it.
  1944. Example usage::
  1945. import numpy as np
  1946. import matplotlib.pyplot as plt
  1947. from matplotlib.widgets import EllipseSelector
  1948. def onselect(eclick, erelease):
  1949. "eclick and erelease are matplotlib events at press and release."
  1950. print('startposition: (%f, %f)' % (eclick.xdata, eclick.ydata))
  1951. print('endposition : (%f, %f)' % (erelease.xdata, erelease.ydata))
  1952. print('used button : ', eclick.button)
  1953. def toggle_selector(event):
  1954. print(' Key pressed.')
  1955. if event.key in ['Q', 'q'] and toggle_selector.ES.active:
  1956. print('EllipseSelector deactivated.')
  1957. toggle_selector.RS.set_active(False)
  1958. if event.key in ['A', 'a'] and not toggle_selector.ES.active:
  1959. print('EllipseSelector activated.')
  1960. toggle_selector.ES.set_active(True)
  1961. x = np.arange(100.) / 99
  1962. y = np.sin(x)
  1963. fig, ax = plt.subplots()
  1964. ax.plot(x, y)
  1965. toggle_selector.ES = EllipseSelector(ax, onselect, drawtype='line')
  1966. fig.canvas.mpl_connect('key_press_event', toggle_selector)
  1967. plt.show()
  1968. """
  1969. _shape_klass = Ellipse
  1970. def draw_shape(self, extents):
  1971. x1, x2, y1, y2 = extents
  1972. xmin, xmax = sorted([x1, x2])
  1973. ymin, ymax = sorted([y1, y2])
  1974. center = [x1 + (x2 - x1) / 2., y1 + (y2 - y1) / 2.]
  1975. a = (xmax - xmin) / 2.
  1976. b = (ymax - ymin) / 2.
  1977. if self.drawtype == 'box':
  1978. self.to_draw.center = center
  1979. self.to_draw.width = 2 * a
  1980. self.to_draw.height = 2 * b
  1981. else:
  1982. rad = np.deg2rad(np.arange(31) * 12)
  1983. x = a * np.cos(rad) + center[0]
  1984. y = b * np.sin(rad) + center[1]
  1985. self.to_draw.set_data(x, y)
  1986. @property
  1987. def _rect_bbox(self):
  1988. if self.drawtype == 'box':
  1989. x, y = self.to_draw.center
  1990. width = self.to_draw.width
  1991. height = self.to_draw.height
  1992. return x - width / 2., y - height / 2., width, height
  1993. else:
  1994. x, y = self.to_draw.get_data()
  1995. x0, x1 = min(x), max(x)
  1996. y0, y1 = min(y), max(y)
  1997. return x0, y0, x1 - x0, y1 - y0
  1998. class LassoSelector(_SelectorWidget):
  1999. """
  2000. Selection curve of an arbitrary shape.
  2001. For the selector to remain responsive you must keep a reference to it.
  2002. The selected path can be used in conjunction with `~.Path.contains_point`
  2003. to select data points from an image.
  2004. In contrast to `Lasso`, `LassoSelector` is written with an interface
  2005. similar to `RectangleSelector` and `SpanSelector`, and will continue to
  2006. interact with the axes until disconnected.
  2007. Example usage::
  2008. ax = subplot(111)
  2009. ax.plot(x, y)
  2010. def onselect(verts):
  2011. print(verts)
  2012. lasso = LassoSelector(ax, onselect)
  2013. Parameters
  2014. ----------
  2015. ax : `~matplotlib.axes.Axes`
  2016. The parent axes for the widget.
  2017. onselect : function
  2018. Whenever the lasso is released, the *onselect* function is called and
  2019. passed the vertices of the selected path.
  2020. button : `.MouseButton` or list of `.MouseButton`, optional
  2021. The mouse buttons used for rectangle selection. Default is ``None``,
  2022. which corresponds to all buttons.
  2023. """
  2024. def __init__(self, ax, onselect=None, useblit=True, lineprops=None,
  2025. button=None):
  2026. _SelectorWidget.__init__(self, ax, onselect, useblit=useblit,
  2027. button=button)
  2028. self.verts = None
  2029. if lineprops is None:
  2030. lineprops = dict()
  2031. # self.useblit may be != useblit, if the canvas doesn't support blit.
  2032. lineprops.update(animated=self.useblit, visible=False)
  2033. self.line = Line2D([], [], **lineprops)
  2034. self.ax.add_line(self.line)
  2035. self.artists = [self.line]
  2036. def onpress(self, event):
  2037. self.press(event)
  2038. def _press(self, event):
  2039. self.verts = [self._get_data(event)]
  2040. self.line.set_visible(True)
  2041. def onrelease(self, event):
  2042. self.release(event)
  2043. def _release(self, event):
  2044. if self.verts is not None:
  2045. self.verts.append(self._get_data(event))
  2046. self.onselect(self.verts)
  2047. self.line.set_data([[], []])
  2048. self.line.set_visible(False)
  2049. self.verts = None
  2050. def _onmove(self, event):
  2051. if self.verts is None:
  2052. return
  2053. self.verts.append(self._get_data(event))
  2054. self.line.set_data(list(zip(*self.verts)))
  2055. self.update()
  2056. class PolygonSelector(_SelectorWidget):
  2057. """
  2058. Select a polygon region of an axes.
  2059. Place vertices with each mouse click, and make the selection by completing
  2060. the polygon (clicking on the first vertex). Hold the *ctrl* key and click
  2061. and drag a vertex to reposition it (the *ctrl* key is not necessary if the
  2062. polygon has already been completed). Hold the *shift* key and click and
  2063. drag anywhere in the axes to move all vertices. Press the *esc* key to
  2064. start a new polygon.
  2065. For the selector to remain responsive you must keep a reference to
  2066. it.
  2067. Parameters
  2068. ----------
  2069. ax : `~matplotlib.axes.Axes`
  2070. The parent axes for the widget.
  2071. onselect : function
  2072. When a polygon is completed or modified after completion,
  2073. the `onselect` function is called and passed a list of the vertices as
  2074. ``(xdata, ydata)`` tuples.
  2075. useblit : bool, optional
  2076. lineprops : dict, optional
  2077. The line for the sides of the polygon is drawn with the properties
  2078. given by `lineprops`. The default is ``dict(color='k', linestyle='-',
  2079. linewidth=2, alpha=0.5)``.
  2080. markerprops : dict, optional
  2081. The markers for the vertices of the polygon are drawn with the
  2082. properties given by `markerprops`. The default is ``dict(marker='o',
  2083. markersize=7, mec='k', mfc='k', alpha=0.5)``.
  2084. vertex_select_radius : float, optional
  2085. A vertex is selected (to complete the polygon or to move a vertex)
  2086. if the mouse click is within `vertex_select_radius` pixels of the
  2087. vertex. The default radius is 15 pixels.
  2088. Examples
  2089. --------
  2090. :doc:`/gallery/widgets/polygon_selector_demo`
  2091. """
  2092. def __init__(self, ax, onselect, useblit=False,
  2093. lineprops=None, markerprops=None, vertex_select_radius=15):
  2094. # The state modifiers 'move', 'square', and 'center' are expected by
  2095. # _SelectorWidget but are not supported by PolygonSelector
  2096. # Note: could not use the existing 'move' state modifier in-place of
  2097. # 'move_all' because _SelectorWidget automatically discards 'move'
  2098. # from the state on button release.
  2099. state_modifier_keys = dict(clear='escape', move_vertex='control',
  2100. move_all='shift', move='not-applicable',
  2101. square='not-applicable',
  2102. center='not-applicable')
  2103. _SelectorWidget.__init__(self, ax, onselect, useblit=useblit,
  2104. state_modifier_keys=state_modifier_keys)
  2105. self._xs, self._ys = [0], [0]
  2106. self._polygon_completed = False
  2107. if lineprops is None:
  2108. lineprops = dict(color='k', linestyle='-', linewidth=2, alpha=0.5)
  2109. lineprops['animated'] = self.useblit
  2110. self.line = Line2D(self._xs, self._ys, **lineprops)
  2111. self.ax.add_line(self.line)
  2112. if markerprops is None:
  2113. markerprops = dict(mec='k', mfc=lineprops.get('color', 'k'))
  2114. self._polygon_handles = ToolHandles(self.ax, self._xs, self._ys,
  2115. useblit=self.useblit,
  2116. marker_props=markerprops)
  2117. self._active_handle_idx = -1
  2118. self.vertex_select_radius = vertex_select_radius
  2119. self.artists = [self.line, self._polygon_handles.artist]
  2120. self.set_visible(True)
  2121. def _press(self, event):
  2122. """Button press event handler"""
  2123. # Check for selection of a tool handle.
  2124. if ((self._polygon_completed or 'move_vertex' in self.state)
  2125. and len(self._xs) > 0):
  2126. h_idx, h_dist = self._polygon_handles.closest(event.x, event.y)
  2127. if h_dist < self.vertex_select_radius:
  2128. self._active_handle_idx = h_idx
  2129. # Save the vertex positions at the time of the press event (needed to
  2130. # support the 'move_all' state modifier).
  2131. self._xs_at_press, self._ys_at_press = self._xs[:], self._ys[:]
  2132. def _release(self, event):
  2133. """Button release event handler"""
  2134. # Release active tool handle.
  2135. if self._active_handle_idx >= 0:
  2136. self._active_handle_idx = -1
  2137. # Complete the polygon.
  2138. elif (len(self._xs) > 3
  2139. and self._xs[-1] == self._xs[0]
  2140. and self._ys[-1] == self._ys[0]):
  2141. self._polygon_completed = True
  2142. # Place new vertex.
  2143. elif (not self._polygon_completed
  2144. and 'move_all' not in self.state
  2145. and 'move_vertex' not in self.state):
  2146. self._xs.insert(-1, event.xdata)
  2147. self._ys.insert(-1, event.ydata)
  2148. if self._polygon_completed:
  2149. self.onselect(self.verts)
  2150. def onmove(self, event):
  2151. """Cursor move event handler and validator"""
  2152. # Method overrides _SelectorWidget.onmove because the polygon selector
  2153. # needs to process the move callback even if there is no button press.
  2154. # _SelectorWidget.onmove include logic to ignore move event if
  2155. # eventpress is None.
  2156. if not self.ignore(event):
  2157. event = self._clean_event(event)
  2158. self._onmove(event)
  2159. return True
  2160. return False
  2161. def _onmove(self, event):
  2162. """Cursor move event handler"""
  2163. # Move the active vertex (ToolHandle).
  2164. if self._active_handle_idx >= 0:
  2165. idx = self._active_handle_idx
  2166. self._xs[idx], self._ys[idx] = event.xdata, event.ydata
  2167. # Also update the end of the polygon line if the first vertex is
  2168. # the active handle and the polygon is completed.
  2169. if idx == 0 and self._polygon_completed:
  2170. self._xs[-1], self._ys[-1] = event.xdata, event.ydata
  2171. # Move all vertices.
  2172. elif 'move_all' in self.state and self.eventpress:
  2173. dx = event.xdata - self.eventpress.xdata
  2174. dy = event.ydata - self.eventpress.ydata
  2175. for k in range(len(self._xs)):
  2176. self._xs[k] = self._xs_at_press[k] + dx
  2177. self._ys[k] = self._ys_at_press[k] + dy
  2178. # Do nothing if completed or waiting for a move.
  2179. elif (self._polygon_completed
  2180. or 'move_vertex' in self.state or 'move_all' in self.state):
  2181. return
  2182. # Position pending vertex.
  2183. else:
  2184. # Calculate distance to the start vertex.
  2185. x0, y0 = self.line.get_transform().transform((self._xs[0],
  2186. self._ys[0]))
  2187. v0_dist = np.hypot(x0 - event.x, y0 - event.y)
  2188. # Lock on to the start vertex if near it and ready to complete.
  2189. if len(self._xs) > 3 and v0_dist < self.vertex_select_radius:
  2190. self._xs[-1], self._ys[-1] = self._xs[0], self._ys[0]
  2191. else:
  2192. self._xs[-1], self._ys[-1] = event.xdata, event.ydata
  2193. self._draw_polygon()
  2194. def _on_key_press(self, event):
  2195. """Key press event handler"""
  2196. # Remove the pending vertex if entering the 'move_vertex' or
  2197. # 'move_all' mode
  2198. if (not self._polygon_completed
  2199. and ('move_vertex' in self.state or 'move_all' in self.state)):
  2200. self._xs, self._ys = self._xs[:-1], self._ys[:-1]
  2201. self._draw_polygon()
  2202. def _on_key_release(self, event):
  2203. """Key release event handler"""
  2204. # Add back the pending vertex if leaving the 'move_vertex' or
  2205. # 'move_all' mode (by checking the released key)
  2206. if (not self._polygon_completed
  2207. and
  2208. (event.key == self.state_modifier_keys.get('move_vertex')
  2209. or event.key == self.state_modifier_keys.get('move_all'))):
  2210. self._xs.append(event.xdata)
  2211. self._ys.append(event.ydata)
  2212. self._draw_polygon()
  2213. # Reset the polygon if the released key is the 'clear' key.
  2214. elif event.key == self.state_modifier_keys.get('clear'):
  2215. event = self._clean_event(event)
  2216. self._xs, self._ys = [event.xdata], [event.ydata]
  2217. self._polygon_completed = False
  2218. self.set_visible(True)
  2219. def _draw_polygon(self):
  2220. """Redraw the polygon based on the new vertex positions."""
  2221. self.line.set_data(self._xs, self._ys)
  2222. # Only show one tool handle at the start and end vertex of the polygon
  2223. # if the polygon is completed or the user is locked on to the start
  2224. # vertex.
  2225. if (self._polygon_completed
  2226. or (len(self._xs) > 3
  2227. and self._xs[-1] == self._xs[0]
  2228. and self._ys[-1] == self._ys[0])):
  2229. self._polygon_handles.set_data(self._xs[:-1], self._ys[:-1])
  2230. else:
  2231. self._polygon_handles.set_data(self._xs, self._ys)
  2232. self.update()
  2233. @property
  2234. def verts(self):
  2235. """The polygon vertices, as a list of ``(x, y)`` pairs."""
  2236. return list(zip(self._xs[:-1], self._ys[:-1]))
  2237. class Lasso(AxesWidget):
  2238. """
  2239. Selection curve of an arbitrary shape.
  2240. The selected path can be used in conjunction with
  2241. `~matplotlib.path.Path.contains_point` to select data points from an image.
  2242. Unlike `LassoSelector`, this must be initialized with a starting
  2243. point `xy`, and the `Lasso` events are destroyed upon release.
  2244. Parameters
  2245. ----------
  2246. ax : `~matplotlib.axes.Axes`
  2247. The parent axes for the widget.
  2248. xy : (float, float)
  2249. Coordinates of the start of the lasso.
  2250. callback : callable
  2251. Whenever the lasso is released, the `callback` function is called and
  2252. passed the vertices of the selected path.
  2253. """
  2254. def __init__(self, ax, xy, callback=None, useblit=True):
  2255. AxesWidget.__init__(self, ax)
  2256. self.useblit = useblit and self.canvas.supports_blit
  2257. if self.useblit:
  2258. self.background = self.canvas.copy_from_bbox(self.ax.bbox)
  2259. x, y = xy
  2260. self.verts = [(x, y)]
  2261. self.line = Line2D([x], [y], linestyle='-', color='black', lw=2)
  2262. self.ax.add_line(self.line)
  2263. self.callback = callback
  2264. self.connect_event('button_release_event', self.onrelease)
  2265. self.connect_event('motion_notify_event', self.onmove)
  2266. def onrelease(self, event):
  2267. if self.ignore(event):
  2268. return
  2269. if self.verts is not None:
  2270. self.verts.append((event.xdata, event.ydata))
  2271. if len(self.verts) > 2:
  2272. self.callback(self.verts)
  2273. self.ax.lines.remove(self.line)
  2274. self.verts = None
  2275. self.disconnect_events()
  2276. def onmove(self, event):
  2277. if self.ignore(event):
  2278. return
  2279. if self.verts is None:
  2280. return
  2281. if event.inaxes != self.ax:
  2282. return
  2283. if event.button != 1:
  2284. return
  2285. self.verts.append((event.xdata, event.ydata))
  2286. self.line.set_data(list(zip(*self.verts)))
  2287. if self.useblit:
  2288. self.canvas.restore_region(self.background)
  2289. self.ax.draw_artist(self.line)
  2290. self.canvas.blit(self.ax.bbox)
  2291. else:
  2292. self.canvas.draw_idle()