matplotlib-rs 0.0.8__cp313-cp313-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (352) hide show
  1. docs/releases/0.0.1.md +268 -0
  2. docs/releases/0.0.2.md +69 -0
  3. docs/releases/0.0.3.md +80 -0
  4. docs/releases/0.0.4.md +73 -0
  5. docs/releases/0.0.5.md +24 -0
  6. docs/releases/0.0.6.md +24 -0
  7. docs/releases/0.0.7.md +24 -0
  8. docs/releases/0.0.8.md +16 -0
  9. licenses/LICENSE_CONTOURPY +29 -0
  10. licenses/LICENSE_CYCLER +27 -0
  11. licenses/LICENSE_DATEUTIL +54 -0
  12. licenses/LICENSE_KIWISOLVER +71 -0
  13. licenses/LICENSE_LIBWEBP +56 -0
  14. licenses/LICENSE_MATPLOTLIB +1253 -0
  15. licenses/LICENSE_PYPARSING +20 -0
  16. licenses/LICENSE_QHULL +39 -0
  17. licenses/LICENSE_SIX +18 -0
  18. matplotlib_rs/__init__.py +1683 -0
  19. matplotlib_rs/__main__.py +27 -0
  20. matplotlib_rs/_afm.py +500 -0
  21. matplotlib_rs/_animation_data.py +263 -0
  22. matplotlib_rs/_api/__init__.py +495 -0
  23. matplotlib_rs/_api/deprecation.py +534 -0
  24. matplotlib_rs/_axis_py.py +2991 -0
  25. matplotlib_rs/_blocking_input.py +31 -0
  26. matplotlib_rs/_cm.py +1500 -0
  27. matplotlib_rs/_cm_bivar.py +1289 -0
  28. matplotlib_rs/_cm_listed.py +2848 -0
  29. matplotlib_rs/_cm_multivar.py +167 -0
  30. matplotlib_rs/_color_data.py +1142 -0
  31. matplotlib_rs/_colormap.py +132 -0
  32. matplotlib_rs/_constrained_layout.py +825 -0
  33. matplotlib_rs/_contour.py +108 -0
  34. matplotlib_rs/_doc_cache.py +12214 -0
  35. matplotlib_rs/_docstring.py +142 -0
  36. matplotlib_rs/_enums.py +178 -0
  37. matplotlib_rs/_figure_rs.py +294 -0
  38. matplotlib_rs/_fontconfig_pattern.py +129 -0
  39. matplotlib_rs/_foreign.py +220 -0
  40. matplotlib_rs/_hook.py +94 -0
  41. matplotlib_rs/_image.py +160 -0
  42. matplotlib_rs/_imageio.py +229 -0
  43. matplotlib_rs/_internal_utils.py +65 -0
  44. matplotlib_rs/_kiwi.py +484 -0
  45. matplotlib_rs/_layoutgrid.py +549 -0
  46. matplotlib_rs/_live.py +192 -0
  47. matplotlib_rs/_mathtext.py +3103 -0
  48. matplotlib_rs/_mathtext_data.py +1811 -0
  49. matplotlib_rs/_mplrs.cp313-win_amd64.pyd +0 -0
  50. matplotlib_rs/_path.py +25 -0
  51. matplotlib_rs/_png.py +162 -0
  52. matplotlib_rs/_pylab_helpers.py +137 -0
  53. matplotlib_rs/_qhull.py +66 -0
  54. matplotlib_rs/_rcpush.py +84 -0
  55. matplotlib_rs/_spines_rs.py +108 -0
  56. matplotlib_rs/_style_helpers.py +52 -0
  57. matplotlib_rs/_text_helpers.py +51 -0
  58. matplotlib_rs/_tight_bbox.py +85 -0
  59. matplotlib_rs/_tight_layout.py +302 -0
  60. matplotlib_rs/_tri.py +140 -0
  61. matplotlib_rs/_type1font.py +1228 -0
  62. matplotlib_rs/_vendor/__init__.py +8 -0
  63. matplotlib_rs/_vendor/cycler.py +574 -0
  64. matplotlib_rs/_vendor/dateutil/__init__.py +27 -0
  65. matplotlib_rs/_vendor/dateutil/_common.py +44 -0
  66. matplotlib_rs/_vendor/dateutil/_tzdata_impl.py +148 -0
  67. matplotlib_rs/_vendor/dateutil/_version.py +5 -0
  68. matplotlib_rs/_vendor/dateutil/easter.py +90 -0
  69. matplotlib_rs/_vendor/dateutil/parser/__init__.py +62 -0
  70. matplotlib_rs/_vendor/dateutil/parser/_parser.py +1614 -0
  71. matplotlib_rs/_vendor/dateutil/parser/isoparser.py +417 -0
  72. matplotlib_rs/_vendor/dateutil/relativedelta.py +597 -0
  73. matplotlib_rs/_vendor/dateutil/rrule.py +1765 -0
  74. matplotlib_rs/_vendor/dateutil/tz/__init__.py +61 -0
  75. matplotlib_rs/_vendor/dateutil/tz/_common.py +420 -0
  76. matplotlib_rs/_vendor/dateutil/tz/_factories.py +81 -0
  77. matplotlib_rs/_vendor/dateutil/tz/_tzfile.py +1429 -0
  78. matplotlib_rs/_vendor/dateutil/tz/_tzpath.py +105 -0
  79. matplotlib_rs/_vendor/dateutil/tz/tz.py +1473 -0
  80. matplotlib_rs/_vendor/dateutil/tz/win.py +371 -0
  81. matplotlib_rs/_vendor/dateutil/tzwin.py +3 -0
  82. matplotlib_rs/_vendor/dateutil/utils.py +72 -0
  83. matplotlib_rs/_vendor/dateutil/zoneinfo/__init__.py +234 -0
  84. matplotlib_rs/_vendor/pyparsing/__init__.py +414 -0
  85. matplotlib_rs/_vendor/pyparsing/actions.py +265 -0
  86. matplotlib_rs/_vendor/pyparsing/common.py +571 -0
  87. matplotlib_rs/_vendor/pyparsing/core.py +6973 -0
  88. matplotlib_rs/_vendor/pyparsing/exceptions.py +354 -0
  89. matplotlib_rs/_vendor/pyparsing/helpers.py +1770 -0
  90. matplotlib_rs/_vendor/pyparsing/results.py +929 -0
  91. matplotlib_rs/_vendor/pyparsing/testing.py +399 -0
  92. matplotlib_rs/_vendor/pyparsing/unicode.py +357 -0
  93. matplotlib_rs/_vendor/pyparsing/util.py +515 -0
  94. matplotlib_rs/_vendor/pyparsing/warnings.py +11 -0
  95. matplotlib_rs/_vendor/six.py +1004 -0
  96. matplotlib_rs/animation.py +1843 -0
  97. matplotlib_rs/artist.py +2302 -0
  98. matplotlib_rs/axes/__init__.py +19 -0
  99. matplotlib_rs/axes/_axes.py +9402 -0
  100. matplotlib_rs/axes/_bar.py +185 -0
  101. matplotlib_rs/axes/_base.py +5236 -0
  102. matplotlib_rs/axes/_base_rs.py +727 -0
  103. matplotlib_rs/axes/_boxplot.py +391 -0
  104. matplotlib_rs/axes/_hist.py +99 -0
  105. matplotlib_rs/axes/_secondary_axes.py +357 -0
  106. matplotlib_rs/axis.py +1963 -0
  107. matplotlib_rs/backend_bases.py +3760 -0
  108. matplotlib_rs/backend_managers.py +388 -0
  109. matplotlib_rs/backend_tools.py +1002 -0
  110. matplotlib_rs/backends/__init__.py +6 -0
  111. matplotlib_rs/backends/_backend_pdf_ps.py +451 -0
  112. matplotlib_rs/backends/backend_agg.py +552 -0
  113. matplotlib_rs/backends/backend_mixed.py +123 -0
  114. matplotlib_rs/backends/backend_pdf.py +2711 -0
  115. matplotlib_rs/backends/backend_pgf.py +1031 -0
  116. matplotlib_rs/backends/backend_ps.py +1491 -0
  117. matplotlib_rs/backends/backend_svg.py +1395 -0
  118. matplotlib_rs/backends/backend_template.py +214 -0
  119. matplotlib_rs/backends/registry.py +423 -0
  120. matplotlib_rs/bezier.py +691 -0
  121. matplotlib_rs/category.py +236 -0
  122. matplotlib_rs/cbook.py +2762 -0
  123. matplotlib_rs/cm.py +251 -0
  124. matplotlib_rs/collections.py +2711 -0
  125. matplotlib_rs/colorbar.py +1586 -0
  126. matplotlib_rs/colorizer.py +909 -0
  127. matplotlib_rs/colors.py +4278 -0
  128. matplotlib_rs/container.py +256 -0
  129. matplotlib_rs/contour.py +1756 -0
  130. matplotlib_rs/dates.py +1847 -0
  131. matplotlib_rs/dviread.py +1386 -0
  132. matplotlib_rs/figure.py +3815 -0
  133. matplotlib_rs/font_manager.py +1855 -0
  134. matplotlib_rs/ft2font.py +515 -0
  135. matplotlib_rs/gridspec.py +808 -0
  136. matplotlib_rs/hatch.py +244 -0
  137. matplotlib_rs/image.py +1863 -0
  138. matplotlib_rs/inset.py +291 -0
  139. matplotlib_rs/layout_engine.py +310 -0
  140. matplotlib_rs/legend.py +1480 -0
  141. matplotlib_rs/legend_handler.py +812 -0
  142. matplotlib_rs/lines.py +1886 -0
  143. matplotlib_rs/markers.py +908 -0
  144. matplotlib_rs/mathtext.py +141 -0
  145. matplotlib_rs/mlab.py +959 -0
  146. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-Bold.ttf +0 -0
  147. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-BoldOblique.ttf +0 -0
  148. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-Oblique.ttf +0 -0
  149. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans.ttf +0 -0
  150. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansDisplay.ttf +0 -0
  151. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-Bold.ttf +0 -0
  152. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-BoldOblique.ttf +0 -0
  153. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-Oblique.ttf +0 -0
  154. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono.ttf +0 -0
  155. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-Bold.ttf +0 -0
  156. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-BoldItalic.ttf +0 -0
  157. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-Italic.ttf +0 -0
  158. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif.ttf +0 -0
  159. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerifDisplay.ttf +0 -0
  160. matplotlib_rs/mpl-data/fonts/ttf/LICENSE_DEJAVU +99 -0
  161. matplotlib_rs/mpl-data/fonts/ttf/LICENSE_STIX +124 -0
  162. matplotlib_rs/mpl-data/fonts/ttf/LastResortHE-Regular.ttf +0 -0
  163. matplotlib_rs/mpl-data/fonts/ttf/STIXGeneral.ttf +0 -0
  164. matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralBol.ttf +0 -0
  165. matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralBolIta.ttf +0 -0
  166. matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralItalic.ttf +0 -0
  167. matplotlib_rs/mpl-data/fonts/ttf/STIXNonUni.ttf +0 -0
  168. matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniBol.ttf +0 -0
  169. matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniBolIta.ttf +0 -0
  170. matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniIta.ttf +0 -0
  171. matplotlib_rs/mpl-data/fonts/ttf/STIXSizFiveSymReg.ttf +0 -0
  172. matplotlib_rs/mpl-data/fonts/ttf/STIXSizFourSymBol.ttf +0 -0
  173. matplotlib_rs/mpl-data/fonts/ttf/STIXSizFourSymReg.ttf +0 -0
  174. matplotlib_rs/mpl-data/fonts/ttf/STIXSizOneSymBol.ttf +0 -0
  175. matplotlib_rs/mpl-data/fonts/ttf/STIXSizOneSymReg.ttf +0 -0
  176. matplotlib_rs/mpl-data/fonts/ttf/STIXSizThreeSymBol.ttf +0 -0
  177. matplotlib_rs/mpl-data/fonts/ttf/STIXSizThreeSymReg.ttf +0 -0
  178. matplotlib_rs/mpl-data/fonts/ttf/STIXSizTwoSymBol.ttf +0 -0
  179. matplotlib_rs/mpl-data/fonts/ttf/STIXSizTwoSymReg.ttf +0 -0
  180. matplotlib_rs/mpl-data/fonts/ttf/cmb10.ttf +0 -0
  181. matplotlib_rs/mpl-data/fonts/ttf/cmex10.ttf +0 -0
  182. matplotlib_rs/mpl-data/fonts/ttf/cmmi10.ttf +0 -0
  183. matplotlib_rs/mpl-data/fonts/ttf/cmr10.ttf +0 -0
  184. matplotlib_rs/mpl-data/fonts/ttf/cmss10.ttf +0 -0
  185. matplotlib_rs/mpl-data/fonts/ttf/cmsy10.ttf +0 -0
  186. matplotlib_rs/mpl-data/fonts/ttf/cmti10.ttf +0 -0
  187. matplotlib_rs/mpl-data/fonts/ttf/cmtt10.ttf +0 -0
  188. matplotlib_rs/mpl-data/images/back-symbolic.svg +46 -0
  189. matplotlib_rs/mpl-data/images/back.pdf +0 -0
  190. matplotlib_rs/mpl-data/images/back.png +0 -0
  191. matplotlib_rs/mpl-data/images/back.svg +46 -0
  192. matplotlib_rs/mpl-data/images/back_large.png +0 -0
  193. matplotlib_rs/mpl-data/images/filesave-symbolic.svg +68 -0
  194. matplotlib_rs/mpl-data/images/filesave.pdf +72 -0
  195. matplotlib_rs/mpl-data/images/filesave.png +0 -0
  196. matplotlib_rs/mpl-data/images/filesave.svg +68 -0
  197. matplotlib_rs/mpl-data/images/filesave_large.png +0 -0
  198. matplotlib_rs/mpl-data/images/forward-symbolic.svg +46 -0
  199. matplotlib_rs/mpl-data/images/forward.pdf +0 -0
  200. matplotlib_rs/mpl-data/images/forward.png +0 -0
  201. matplotlib_rs/mpl-data/images/forward.svg +46 -0
  202. matplotlib_rs/mpl-data/images/forward_large.png +0 -0
  203. matplotlib_rs/mpl-data/images/hand.pdf +0 -0
  204. matplotlib_rs/mpl-data/images/hand.png +0 -0
  205. matplotlib_rs/mpl-data/images/hand.svg +130 -0
  206. matplotlib_rs/mpl-data/images/help-symbolic.svg +52 -0
  207. matplotlib_rs/mpl-data/images/help.pdf +71 -0
  208. matplotlib_rs/mpl-data/images/help.png +0 -0
  209. matplotlib_rs/mpl-data/images/help.svg +52 -0
  210. matplotlib_rs/mpl-data/images/help_large.png +0 -0
  211. matplotlib_rs/mpl-data/images/home-symbolic.svg +59 -0
  212. matplotlib_rs/mpl-data/images/home.pdf +0 -0
  213. matplotlib_rs/mpl-data/images/home.png +0 -0
  214. matplotlib_rs/mpl-data/images/home.svg +59 -0
  215. matplotlib_rs/mpl-data/images/home_large.png +0 -0
  216. matplotlib_rs/mpl-data/images/matplotlib.pdf +0 -0
  217. matplotlib_rs/mpl-data/images/matplotlib.png +0 -0
  218. matplotlib_rs/mpl-data/images/matplotlib.svg +3171 -0
  219. matplotlib_rs/mpl-data/images/matplotlib_large.png +0 -0
  220. matplotlib_rs/mpl-data/images/move-symbolic.svg +73 -0
  221. matplotlib_rs/mpl-data/images/move.pdf +0 -0
  222. matplotlib_rs/mpl-data/images/move.png +0 -0
  223. matplotlib_rs/mpl-data/images/move.svg +73 -0
  224. matplotlib_rs/mpl-data/images/move_large.png +0 -0
  225. matplotlib_rs/mpl-data/images/qt4_editor_options.pdf +0 -0
  226. matplotlib_rs/mpl-data/images/qt4_editor_options.png +0 -0
  227. matplotlib_rs/mpl-data/images/qt4_editor_options.svg +48 -0
  228. matplotlib_rs/mpl-data/images/qt4_editor_options_large.png +0 -0
  229. matplotlib_rs/mpl-data/images/subplots-symbolic.svg +81 -0
  230. matplotlib_rs/mpl-data/images/subplots.pdf +0 -0
  231. matplotlib_rs/mpl-data/images/subplots.png +0 -0
  232. matplotlib_rs/mpl-data/images/subplots.svg +81 -0
  233. matplotlib_rs/mpl-data/images/subplots_large.png +0 -0
  234. matplotlib_rs/mpl-data/images/zoom_to_rect-symbolic.svg +40 -0
  235. matplotlib_rs/mpl-data/images/zoom_to_rect.pdf +69 -0
  236. matplotlib_rs/mpl-data/images/zoom_to_rect.png +0 -0
  237. matplotlib_rs/mpl-data/images/zoom_to_rect.svg +40 -0
  238. matplotlib_rs/mpl-data/images/zoom_to_rect_large.png +0 -0
  239. matplotlib_rs/mpl-data/kpsewhich.lua +4 -0
  240. matplotlib_rs/mpl-data/matplotlibrc +849 -0
  241. matplotlib_rs/mpl-data/plot_directive/plot_directive.css +16 -0
  242. matplotlib_rs/mpl-data/sample_data/Minduka_Present_Blue_Pack.png +0 -0
  243. matplotlib_rs/mpl-data/sample_data/README.txt +2 -0
  244. matplotlib_rs/mpl-data/sample_data/Stocks.csv +526 -0
  245. matplotlib_rs/mpl-data/sample_data/axes_grid/bivariate_normal.npy +0 -0
  246. matplotlib_rs/mpl-data/sample_data/data_x_x2_x3.csv +11 -0
  247. matplotlib_rs/mpl-data/sample_data/eeg.dat +0 -0
  248. matplotlib_rs/mpl-data/sample_data/embedding_in_wx3.xrc +65 -0
  249. matplotlib_rs/mpl-data/sample_data/goog.npz +0 -0
  250. matplotlib_rs/mpl-data/sample_data/grace_hopper.jpg +0 -0
  251. matplotlib_rs/mpl-data/sample_data/jacksboro_fault_dem.npz +0 -0
  252. matplotlib_rs/mpl-data/sample_data/logo2.png +0 -0
  253. matplotlib_rs/mpl-data/sample_data/membrane.dat +0 -0
  254. matplotlib_rs/mpl-data/sample_data/msft.csv +66 -0
  255. matplotlib_rs/mpl-data/sample_data/s1045.ima.gz +0 -0
  256. matplotlib_rs/mpl-data/sample_data/topobathy.npz +0 -0
  257. matplotlib_rs/mpl-data/stylelib/Solarize_Light2.mplstyle +53 -0
  258. matplotlib_rs/mpl-data/stylelib/_classic_test_patch.mplstyle +8 -0
  259. matplotlib_rs/mpl-data/stylelib/_mpl-gallery-nogrid.mplstyle +19 -0
  260. matplotlib_rs/mpl-data/stylelib/_mpl-gallery.mplstyle +19 -0
  261. matplotlib_rs/mpl-data/stylelib/bmh.mplstyle +27 -0
  262. matplotlib_rs/mpl-data/stylelib/classic.mplstyle +491 -0
  263. matplotlib_rs/mpl-data/stylelib/dark_background.mplstyle +26 -0
  264. matplotlib_rs/mpl-data/stylelib/fast.mplstyle +11 -0
  265. matplotlib_rs/mpl-data/stylelib/fivethirtyeight.mplstyle +37 -0
  266. matplotlib_rs/mpl-data/stylelib/ggplot.mplstyle +39 -0
  267. matplotlib_rs/mpl-data/stylelib/grayscale.mplstyle +29 -0
  268. matplotlib_rs/mpl-data/stylelib/petroff10.mplstyle +5 -0
  269. matplotlib_rs/mpl-data/stylelib/petroff6.mplstyle +5 -0
  270. matplotlib_rs/mpl-data/stylelib/petroff8.mplstyle +5 -0
  271. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-bright.mplstyle +3 -0
  272. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-colorblind.mplstyle +3 -0
  273. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-dark-palette.mplstyle +3 -0
  274. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-dark.mplstyle +30 -0
  275. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-darkgrid.mplstyle +30 -0
  276. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-deep.mplstyle +3 -0
  277. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-muted.mplstyle +3 -0
  278. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-notebook.mplstyle +21 -0
  279. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-paper.mplstyle +21 -0
  280. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-pastel.mplstyle +3 -0
  281. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-poster.mplstyle +21 -0
  282. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-talk.mplstyle +21 -0
  283. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-ticks.mplstyle +30 -0
  284. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-white.mplstyle +30 -0
  285. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-whitegrid.mplstyle +30 -0
  286. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8.mplstyle +57 -0
  287. matplotlib_rs/mpl-data/stylelib/tableau-colorblind10.mplstyle +3 -0
  288. matplotlib_rs/mpl_toolkits/__init__.py +3 -0
  289. matplotlib_rs/mpl_toolkits/axes_grid1/__init__.py +11 -0
  290. matplotlib_rs/mpl_toolkits/axes_grid1/anchored_artists.py +415 -0
  291. matplotlib_rs/mpl_toolkits/axes_grid1/axes_divider.py +619 -0
  292. matplotlib_rs/mpl_toolkits/axes_grid1/axes_grid.py +565 -0
  293. matplotlib_rs/mpl_toolkits/axes_grid1/axes_rgb.py +158 -0
  294. matplotlib_rs/mpl_toolkits/axes_grid1/axes_size.py +272 -0
  295. matplotlib_rs/mpl_toolkits/axes_grid1/inset_locator.py +525 -0
  296. matplotlib_rs/mpl_toolkits/axes_grid1/mpl_axes.py +129 -0
  297. matplotlib_rs/mpl_toolkits/axes_grid1/parasite_axes.py +261 -0
  298. matplotlib_rs/mpl_toolkits/axisartist/__init__.py +15 -0
  299. matplotlib_rs/mpl_toolkits/axisartist/angle_helper.py +396 -0
  300. matplotlib_rs/mpl_toolkits/axisartist/axes_divider.py +3 -0
  301. matplotlib_rs/mpl_toolkits/axisartist/axis_artist.py +1148 -0
  302. matplotlib_rs/mpl_toolkits/axisartist/axisline_style.py +193 -0
  303. matplotlib_rs/mpl_toolkits/axisartist/axislines.py +475 -0
  304. matplotlib_rs/mpl_toolkits/axisartist/floating_axes.py +265 -0
  305. matplotlib_rs/mpl_toolkits/axisartist/grid_finder.py +329 -0
  306. matplotlib_rs/mpl_toolkits/axisartist/grid_helper_curvelinear.py +353 -0
  307. matplotlib_rs/mpl_toolkits/axisartist/parasite_axes.py +8 -0
  308. matplotlib_rs/mpl_toolkits/mplot3d/__init__.py +4 -0
  309. matplotlib_rs/mpl_toolkits/mplot3d/art3d.py +1758 -0
  310. matplotlib_rs/mpl_toolkits/mplot3d/axes3d.py +4462 -0
  311. matplotlib_rs/mpl_toolkits/mplot3d/axis3d.py +807 -0
  312. matplotlib_rs/mpl_toolkits/mplot3d/proj3d.py +270 -0
  313. matplotlib_rs/offsetbox.py +1726 -0
  314. matplotlib_rs/patches.py +5049 -0
  315. matplotlib_rs/path.py +1147 -0
  316. matplotlib_rs/patheffects.py +512 -0
  317. matplotlib_rs/projections/__init__.py +126 -0
  318. matplotlib_rs/projections/geo.py +512 -0
  319. matplotlib_rs/projections/polar.py +1518 -0
  320. matplotlib_rs/pylab.py +68 -0
  321. matplotlib_rs/pyplot.py +4834 -0
  322. matplotlib_rs/quiver.py +1236 -0
  323. matplotlib_rs/rcsetup.py +3435 -0
  324. matplotlib_rs/sankey.py +815 -0
  325. matplotlib_rs/scale.py +1002 -0
  326. matplotlib_rs/spines.py +618 -0
  327. matplotlib_rs/stackplot.py +144 -0
  328. matplotlib_rs/streamplot.py +768 -0
  329. matplotlib_rs/style/__init__.py +269 -0
  330. matplotlib_rs/style/core.py +28 -0
  331. matplotlib_rs/table.py +860 -0
  332. matplotlib_rs/texmanager.py +375 -0
  333. matplotlib_rs/text.py +2412 -0
  334. matplotlib_rs/textpath.py +377 -0
  335. matplotlib_rs/ticker.py +3111 -0
  336. matplotlib_rs/transforms.py +3069 -0
  337. matplotlib_rs/tri/__init__.py +24 -0
  338. matplotlib_rs/tri/_triangulation.py +248 -0
  339. matplotlib_rs/tri/_tricontour.py +271 -0
  340. matplotlib_rs/tri/_trifinder.py +97 -0
  341. matplotlib_rs/tri/_triinterpolate.py +1575 -0
  342. matplotlib_rs/tri/_tripcolor.py +170 -0
  343. matplotlib_rs/tri/_triplot.py +87 -0
  344. matplotlib_rs/tri/_trirefine.py +308 -0
  345. matplotlib_rs/tri/_tritools.py +264 -0
  346. matplotlib_rs/typing.py +597 -0
  347. matplotlib_rs/units.py +196 -0
  348. matplotlib_rs/widgets.py +4455 -0
  349. matplotlib_rs-0.0.8.dist-info/METADATA +392 -0
  350. matplotlib_rs-0.0.8.dist-info/RECORD +352 -0
  351. matplotlib_rs-0.0.8.dist-info/WHEEL +4 -0
  352. matplotlib_rs-0.0.8.dist-info/sboms/matplotlib-rs.cyclonedx.json +4390 -0
@@ -0,0 +1,4455 @@
1
+ # Vendored from matplotlib 3.11 (see licenses/LICENSE_MATPLOTLIB), adapted for matplotlib_rs.
2
+ """
3
+ Widgets that are designed to work for any of the GUI backends.
4
+
5
+ All of these widgets require you to predefine an `~.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
+
11
+ from contextlib import ExitStack
12
+ import copy
13
+ import enum
14
+ import functools
15
+ import itertools
16
+ import weakref
17
+ from numbers import Integral, Number
18
+
19
+ from matplotlib_rs.rcsetup import ccycler as cycler
20
+ import numpy as np
21
+
22
+ import matplotlib_rs as mpl
23
+ from . import (_api, _docstring, backend_tools, cbook, collections, colors,
24
+ text as mtext, ticker, transforms)
25
+ from .lines import Line2D
26
+ from .patches import Rectangle, Ellipse, Polygon
27
+ from .transforms import TransformedPatchPath, Affine2D
28
+
29
+
30
+ class LockDraw:
31
+ """
32
+ Some widgets, like the cursor, draw onto the canvas, and this is not
33
+ desirable under all circumstances, like when the toolbar is in zoom-to-rect
34
+ mode and drawing a rectangle. To avoid this, a widget can acquire a
35
+ canvas' lock with ``canvas.widgetlock(widget)`` before drawing on the
36
+ canvas; this will prevent other widgets from doing so at the same time (if
37
+ they also try to acquire the lock first).
38
+ """
39
+
40
+ def __init__(self):
41
+ self._owner = None
42
+
43
+ def __call__(self, o):
44
+ """Reserve the lock for *o*."""
45
+ if not self.available(o):
46
+ raise ValueError('already locked')
47
+ self._owner = o
48
+
49
+ def release(self, o):
50
+ """Release the lock from *o*."""
51
+ if not self.available(o):
52
+ raise ValueError('you do not own this lock')
53
+ self._owner = None
54
+
55
+ def available(self, o):
56
+ """Return whether drawing is available to *o*."""
57
+ return not self.locked() or self.isowner(o)
58
+
59
+ def isowner(self, o):
60
+ """Return whether *o* owns this lock."""
61
+ return self._owner is o
62
+
63
+ def locked(self):
64
+ """Return whether the lock is currently held by an owner."""
65
+ return self._owner is not None
66
+
67
+
68
+ class Widget:
69
+ """
70
+ Abstract base class for GUI neutral widgets.
71
+ """
72
+ drawon = True
73
+ eventson = True
74
+ _active = True
75
+
76
+ def set_active(self, active):
77
+ """Set whether the widget is active."""
78
+ self._active = active
79
+
80
+ def get_active(self):
81
+ """Get whether the widget is active."""
82
+ return self._active
83
+
84
+ # set_active is overridden by SelectorWidgets.
85
+ active = property(get_active, set_active, doc="Is the widget active?")
86
+
87
+ def ignore(self, event):
88
+ """
89
+ Return whether *event* should be ignored.
90
+
91
+ This method should be called at the beginning of any event callback.
92
+ """
93
+ return not self.active
94
+
95
+
96
+ class AxesWidget(Widget):
97
+ """
98
+ Widget connected to a single `~matplotlib.axes.Axes`.
99
+
100
+ To guarantee that the widget remains responsive and not garbage-collected,
101
+ a reference to the object should be maintained by the user.
102
+
103
+ This is necessary because the callback registry
104
+ maintains only weak-refs to the functions, which are member
105
+ functions of the widget. If there are no references to the widget
106
+ object it may be garbage collected which will disconnect the callbacks.
107
+
108
+ Attributes
109
+ ----------
110
+ ax : `~matplotlib.axes.Axes`
111
+ The parent Axes for the widget.
112
+ canvas : `~matplotlib.backend_bases.FigureCanvasBase`
113
+ The parent figure canvas for the widget.
114
+ active : bool
115
+ If False, the widget does not respond to events.
116
+ """
117
+
118
+ def __init__(self, ax):
119
+ self.ax = ax
120
+ self._cids = []
121
+ self._blit_background_id = None
122
+
123
+ canvas = property(
124
+ lambda self: getattr(self.ax.get_figure(root=True), 'canvas', None)
125
+ )
126
+
127
+ def connect_event(self, event, callback):
128
+ """
129
+ Connect a callback function with an event.
130
+
131
+ This should be used in lieu of ``figure.canvas.mpl_connect`` since this
132
+ function stores callback ids for later clean up.
133
+ """
134
+ cid = self.canvas.mpl_connect(event, callback)
135
+ self._cids.append(cid)
136
+
137
+ def disconnect_events(self):
138
+ """Disconnect all events created by this widget."""
139
+ for c in self._cids:
140
+ self.canvas.mpl_disconnect(c)
141
+
142
+ def ignore(self, event):
143
+ # docstring inherited
144
+ return super().ignore(event) or self.canvas is None
145
+
146
+ def _set_cursor(self, cursor):
147
+ """Update the canvas cursor."""
148
+ self.ax.get_figure(root=True).canvas.set_cursor(cursor)
149
+
150
+ def _save_blit_background(self, background):
151
+ """
152
+ Save a blit background.
153
+
154
+ The background is stored on the canvas in a uniquely identifiable way.
155
+ It should be read back via `._load_blit_background`. Be prepared that
156
+ some events may invalidate the background, in which case
157
+ `._load_blit_background` will return None.
158
+
159
+ This currently allows at most one background per widget, which is
160
+ good enough for all existing widgets.
161
+ """
162
+ if self._blit_background_id is None:
163
+ bbid = self.canvas._get_blit_background_id()
164
+ weakref.finalize(self, self.canvas._release_blit_background_id, bbid)
165
+ self._blit_background_id = bbid
166
+ self.canvas._blit_backgrounds[self._blit_background_id] = background
167
+
168
+ def _load_blit_background(self):
169
+ """Load a blit background; may be None at any time."""
170
+ return self.canvas._blit_backgrounds.get(self._blit_background_id)
171
+
172
+
173
+ def _call_with_reparented_event(func):
174
+ """
175
+ Event callback decorator ensuring that the callback is called with an event
176
+ that has been reparented to the widget's axes.
177
+ """
178
+ # This decorator handles the possibility that event.inaxes != self.ax
179
+ # (e.g. if multiple Axes are overlaid), in which case event.xdata/.ydata
180
+ # will be wrong. Note that we still special-case the common case where
181
+ # event.inaxes == self.ax and avoid re-running the inverse data transform,
182
+ # because that can introduce floating point errors for synthetic events.
183
+ @functools.wraps(func)
184
+ def wrapper(self, event):
185
+ if event.inaxes is not self.ax:
186
+ event = copy.copy(event)
187
+ event.guiEvent = None
188
+ event.inaxes = self.ax
189
+ try:
190
+ event.xdata, event.ydata = (
191
+ self.ax.transData.inverted().transform((event.x, event.y)))
192
+ except ValueError: # cf LocationEvent._set_inaxes.
193
+ event.xdata = event.ydata = None
194
+ return func(self, event)
195
+
196
+ return wrapper
197
+
198
+
199
+ class Button(AxesWidget):
200
+ """
201
+ A GUI neutral button.
202
+
203
+ For the button to remain responsive you must keep a reference to it.
204
+ Call `.on_clicked` to connect to the button.
205
+
206
+ Attributes
207
+ ----------
208
+ ax
209
+ The `~.axes.Axes` the button renders into.
210
+ label
211
+ A `.Text` instance.
212
+ color
213
+ The color of the button when not hovering.
214
+ hovercolor
215
+ The color of the button when hovering.
216
+ """
217
+
218
+ def __init__(self, ax, label, image=None,
219
+ color='0.85', hovercolor='0.95', *, useblit=True):
220
+ """
221
+ Parameters
222
+ ----------
223
+ ax : `~matplotlib.axes.Axes`
224
+ The `~.axes.Axes` instance the button will be placed into.
225
+ label : str
226
+ The button text.
227
+ image : array-like or PIL Image
228
+ The image to place in the button, if not *None*. The parameter is
229
+ directly forwarded to `~.axes.Axes.imshow`.
230
+ color : :mpltype:`color`
231
+ The color of the button when not activated.
232
+ hovercolor : :mpltype:`color`
233
+ The color of the button when the mouse is over it.
234
+ useblit : bool, default: True
235
+ Use blitting for faster drawing if supported by the backend.
236
+ See the tutorial :ref:`blitting` for details.
237
+
238
+ .. versionadded:: 3.7
239
+ """
240
+ super().__init__(ax)
241
+
242
+ if image is not None:
243
+ ax.imshow(image)
244
+ self.label = ax.text(0.5, 0.5, label,
245
+ verticalalignment='center',
246
+ horizontalalignment='center',
247
+ transform=ax.transAxes)
248
+
249
+ self._useblit = useblit
250
+
251
+ self._observers = cbook.CallbackRegistry(signals=["clicked"])
252
+
253
+ self.connect_event('button_press_event', self._click)
254
+ self.connect_event('button_release_event', self._release)
255
+ self.connect_event('motion_notify_event', self._motion)
256
+ ax.set_navigate(False)
257
+ ax.set_facecolor(color)
258
+ ax.set_xticks([])
259
+ ax.set_yticks([])
260
+ self.color = color
261
+ self.hovercolor = hovercolor
262
+
263
+ @_call_with_reparented_event
264
+ def _click(self, event):
265
+ if not self.eventson or self.ignore(event) or not self.ax.contains(event)[0]:
266
+ return
267
+ if event.canvas.mouse_grabber != self.ax:
268
+ event.canvas.grab_mouse(self.ax)
269
+
270
+ @_call_with_reparented_event
271
+ def _release(self, event):
272
+ if self.ignore(event) or event.canvas.mouse_grabber != self.ax:
273
+ return
274
+ event.canvas.release_mouse(self.ax)
275
+ if self.eventson and self.ax.contains(event)[0]:
276
+ self._observers.process('clicked', event)
277
+
278
+ @_call_with_reparented_event
279
+ def _motion(self, event):
280
+ if self.ignore(event):
281
+ return
282
+ c = self.hovercolor if self.ax.contains(event)[0] else self.color
283
+ if not colors.same_color(c, self.ax.get_facecolor()):
284
+ self.ax.set_facecolor(c)
285
+ if self.drawon:
286
+ if self._useblit and self.canvas.supports_blit:
287
+ self.ax.draw_artist(self.ax)
288
+ self.canvas.blit(self.ax.bbox)
289
+ else:
290
+ self.canvas.draw()
291
+
292
+ def on_clicked(self, func):
293
+ """
294
+ Connect the callback function *func* to button click events.
295
+
296
+ Returns a connection id, which can be used to disconnect the callback.
297
+ """
298
+ return self._observers.connect('clicked', lambda event: func(event))
299
+
300
+ def disconnect(self, cid):
301
+ """Remove the callback function with connection id *cid*."""
302
+ self._observers.disconnect(cid)
303
+
304
+
305
+ class SliderBase(AxesWidget):
306
+ """
307
+ The base class for constructing Slider widgets. Not intended for direct
308
+ usage.
309
+
310
+ For the slider to remain responsive you must maintain a reference to it.
311
+ """
312
+ def __init__(self, ax, orientation, closedmin, closedmax,
313
+ valmin, valmax, valfmt, dragging, valstep):
314
+ if ax.name == '3d':
315
+ raise ValueError('Sliders cannot be added to 3D Axes')
316
+
317
+ super().__init__(ax)
318
+ _api.check_in_list(['horizontal', 'vertical'], orientation=orientation)
319
+
320
+ self.orientation = orientation
321
+ self.closedmin = closedmin
322
+ self.closedmax = closedmax
323
+ self.valmin = valmin
324
+ self.valmax = valmax
325
+ self.valstep = valstep
326
+ self.drag_active = False
327
+ self.valfmt = valfmt
328
+
329
+ if orientation == "vertical":
330
+ ax.set_ylim(valmin, valmax)
331
+ axis = ax.yaxis
332
+ else:
333
+ ax.set_xlim(valmin, valmax)
334
+ axis = ax.xaxis
335
+
336
+ self._fmt = axis.get_major_formatter()
337
+ if not isinstance(self._fmt, ticker.ScalarFormatter):
338
+ self._fmt = ticker.ScalarFormatter()
339
+ self._fmt.set_axis(axis)
340
+ self._fmt.set_useOffset(False) # No additive offset.
341
+ self._fmt.set_useMathText(True) # x sign before multiplicative offset.
342
+
343
+ ax.set_axis_off()
344
+ ax.set_navigate(False)
345
+
346
+ self.connect_event("button_press_event", self._update)
347
+ self.connect_event("button_release_event", self._update)
348
+ if dragging:
349
+ self.connect_event("motion_notify_event", self._update)
350
+ self._observers = cbook.CallbackRegistry(signals=["changed"])
351
+
352
+ def _stepped_value(self, val):
353
+ """Return *val* coerced to closest number in the ``valstep`` grid."""
354
+ if isinstance(self.valstep, Number):
355
+ val = (self.valmin
356
+ + round((val - self.valmin) / self.valstep) * self.valstep)
357
+ elif self.valstep is not None:
358
+ valstep = np.asanyarray(self.valstep)
359
+ if valstep.ndim != 1:
360
+ raise ValueError(
361
+ f"valstep must have 1 dimension but has {valstep.ndim}"
362
+ )
363
+ val = valstep[np.argmin(np.abs(valstep - val))]
364
+ return val
365
+
366
+ def disconnect(self, cid):
367
+ """
368
+ Remove the observer with connection id *cid*.
369
+
370
+ Parameters
371
+ ----------
372
+ cid : int
373
+ Connection id of the observer to be removed.
374
+ """
375
+ self._observers.disconnect(cid)
376
+
377
+ def reset(self):
378
+ """Reset the slider to the initial value."""
379
+ if np.any(self.val != self.valinit):
380
+ self.set_val(self.valinit)
381
+
382
+
383
+ class Slider(SliderBase):
384
+ """
385
+ A slider representing a floating point range.
386
+
387
+ Create a slider from *valmin* to *valmax* in Axes *ax*. For the slider to
388
+ remain responsive you must maintain a reference to it. Call
389
+ :meth:`on_changed` to connect to the slider event.
390
+
391
+ Attributes
392
+ ----------
393
+ val : float
394
+ Slider value.
395
+ """
396
+
397
+ def __init__(self, ax, label, valmin, valmax, *, valinit=0.5, valfmt=None,
398
+ closedmin=True, closedmax=True, slidermin=None,
399
+ slidermax=None, dragging=True, valstep=None,
400
+ orientation='horizontal', initcolor='r',
401
+ track_color='lightgrey', handle_style=None, **kwargs):
402
+ """
403
+ Parameters
404
+ ----------
405
+ ax : Axes
406
+ The Axes to put the slider in.
407
+
408
+ label : str
409
+ Slider label.
410
+
411
+ valmin : float
412
+ The minimum value of the slider.
413
+
414
+ valmax : float
415
+ The maximum value of the slider.
416
+
417
+ valinit : float, default: 0.5
418
+ The slider initial position.
419
+
420
+ valfmt : str, default: None
421
+ The way to format the slider value. If a string, it must be in %-format.
422
+ If a callable, it must have the signature ``valfmt(val: float) -> str``.
423
+ If None, a `.ScalarFormatter` is used.
424
+
425
+ closedmin : bool, default: True
426
+ Whether the slider interval is closed on the bottom.
427
+
428
+ closedmax : bool, default: True
429
+ Whether the slider interval is closed on the top.
430
+
431
+ slidermin : Slider, default: None
432
+ Do not allow the current slider to have a value less than
433
+ the value of the Slider *slidermin*.
434
+
435
+ slidermax : Slider, default: None
436
+ Do not allow the current slider to have a value greater than
437
+ the value of the Slider *slidermax*.
438
+
439
+ dragging : bool, default: True
440
+ If True the slider can be dragged by the mouse.
441
+
442
+ valstep : float or array-like, default: None
443
+ If a float, the slider will snap to multiples of *valstep*.
444
+ If an array the slider will snap to the values in the array.
445
+
446
+ orientation : {'horizontal', 'vertical'}, default: 'horizontal'
447
+ The orientation of the slider.
448
+
449
+ initcolor : :mpltype:`color`, default: 'r'
450
+ The color of the line at the *valinit* position. Set to ``'none'``
451
+ for no line.
452
+
453
+ track_color : :mpltype:`color`, default: 'lightgrey'
454
+ The color of the background track. The track is accessible for
455
+ further styling via the *track* attribute.
456
+
457
+ handle_style : dict
458
+ Properties of the slider handle. Default values are
459
+
460
+ ========= ===== ======= ========================================
461
+ Key Value Default Description
462
+ ========= ===== ======= ========================================
463
+ facecolor color 'white' The facecolor of the slider handle.
464
+ edgecolor color '.75' The edgecolor of the slider handle.
465
+ size int 10 The size of the slider handle in points.
466
+ ========= ===== ======= ========================================
467
+
468
+ Other values will be transformed as marker{foo} and passed to the
469
+ `~.Line2D` constructor. e.g. ``handle_style = {'style'='x'}`` will
470
+ result in ``markerstyle = 'x'``.
471
+
472
+ Notes
473
+ -----
474
+ Additional kwargs are passed on to ``self.poly`` which is the
475
+ `~matplotlib.patches.Rectangle` that draws the slider knob. See the
476
+ `.Rectangle` documentation for valid property names (``facecolor``,
477
+ ``edgecolor``, ``alpha``, etc.).
478
+ """
479
+ super().__init__(ax, orientation, closedmin, closedmax,
480
+ valmin, valmax, valfmt, dragging, valstep)
481
+
482
+ if slidermin is not None and not hasattr(slidermin, 'val'):
483
+ raise ValueError(
484
+ f"Argument slidermin ({type(slidermin)}) has no 'val'")
485
+ if slidermax is not None and not hasattr(slidermax, 'val'):
486
+ raise ValueError(
487
+ f"Argument slidermax ({type(slidermax)}) has no 'val'")
488
+ self.slidermin = slidermin
489
+ self.slidermax = slidermax
490
+ valinit = self._value_in_bounds(valinit)
491
+ if valinit is None:
492
+ valinit = valmin
493
+ self.val = valinit
494
+ self.valinit = valinit
495
+
496
+ defaults = {'facecolor': 'white', 'edgecolor': '.75', 'size': 10}
497
+ handle_style = {} if handle_style is None else handle_style
498
+ marker_props = {
499
+ f'marker{k}': v for k, v in {**defaults, **handle_style}.items()
500
+ }
501
+
502
+ if orientation == 'vertical':
503
+ self.track = Rectangle(
504
+ (.25, 0), .5, 1,
505
+ transform=ax.transAxes,
506
+ facecolor=track_color
507
+ )
508
+ ax.add_patch(self.track)
509
+ self.poly = ax.axhspan(valmin, valinit, .25, .75, **kwargs)
510
+ # Drawing a longer line and clipping it to the track avoids
511
+ # pixelation-related asymmetries.
512
+ self.hline = ax.axhline(valinit, 0, 1, color=initcolor, lw=1,
513
+ clip_path=TransformedPatchPath(self.track))
514
+ handleXY = [[0.5], [valinit]]
515
+ else:
516
+ self.track = Rectangle(
517
+ (0, .25), 1, .5,
518
+ transform=ax.transAxes,
519
+ facecolor=track_color
520
+ )
521
+ ax.add_patch(self.track)
522
+ self.poly = ax.axvspan(valmin, valinit, .25, .75, **kwargs)
523
+ self.vline = ax.axvline(valinit, 0, 1, color=initcolor, lw=1,
524
+ clip_path=TransformedPatchPath(self.track))
525
+ handleXY = [[valinit], [0.5]]
526
+ self._handle, = ax.plot(
527
+ *handleXY,
528
+ "o",
529
+ **marker_props,
530
+ clip_on=False
531
+ )
532
+
533
+ if orientation == 'vertical':
534
+ self.label = ax.text(0.5, 1.02, label, transform=ax.transAxes,
535
+ verticalalignment='bottom',
536
+ horizontalalignment='center')
537
+
538
+ self.valtext = ax.text(0.5, -0.02, self._format(valinit),
539
+ transform=ax.transAxes,
540
+ verticalalignment='top',
541
+ horizontalalignment='center')
542
+ else:
543
+ self.label = ax.text(-0.02, 0.5, label, transform=ax.transAxes,
544
+ verticalalignment='center',
545
+ horizontalalignment='right')
546
+
547
+ self.valtext = ax.text(1.02, 0.5, self._format(valinit),
548
+ transform=ax.transAxes,
549
+ verticalalignment='center',
550
+ horizontalalignment='left')
551
+
552
+ self.set_val(valinit)
553
+
554
+ def _value_in_bounds(self, val):
555
+ """Makes sure *val* is with given bounds."""
556
+ val = self._stepped_value(val)
557
+
558
+ if val <= self.valmin:
559
+ if not self.closedmin:
560
+ return
561
+ val = self.valmin
562
+ elif val >= self.valmax:
563
+ if not self.closedmax:
564
+ return
565
+ val = self.valmax
566
+
567
+ if self.slidermin is not None and val <= self.slidermin.val:
568
+ if not self.closedmin:
569
+ return
570
+ val = self.slidermin.val
571
+
572
+ if self.slidermax is not None and val >= self.slidermax.val:
573
+ if not self.closedmax:
574
+ return
575
+ val = self.slidermax.val
576
+ return val
577
+
578
+ @_call_with_reparented_event
579
+ def _update(self, event):
580
+ """Update the slider position."""
581
+ if self.ignore(event) or event.button != 1:
582
+ return
583
+
584
+ if event.name == 'button_press_event' and self.ax.contains(event)[0]:
585
+ self.drag_active = True
586
+ event.canvas.grab_mouse(self.ax)
587
+
588
+ if not self.drag_active:
589
+ return
590
+
591
+ if (event.name == 'button_release_event'
592
+ or event.name == 'button_press_event' and not self.ax.contains(event)[0]):
593
+ self.drag_active = False
594
+ event.canvas.release_mouse(self.ax)
595
+ return
596
+
597
+ val = self._value_in_bounds(
598
+ event.xdata if self.orientation == 'horizontal' else event.ydata)
599
+ if val not in [None, self.val]:
600
+ self.set_val(val)
601
+
602
+ def _format(self, val):
603
+ """Pretty-print *val*."""
604
+ if self.valfmt is not None:
605
+ if callable(self.valfmt):
606
+ return self.valfmt(val)
607
+ else:
608
+ return self.valfmt % val
609
+ else:
610
+ _, s, _ = self._fmt.format_ticks([self.valmin, val, self.valmax])
611
+ # fmt.get_offset is actually the multiplicative factor, if any.
612
+ return s + self._fmt.get_offset()
613
+
614
+ def set_val(self, val):
615
+ """
616
+ Set slider value to *val*.
617
+
618
+ Parameters
619
+ ----------
620
+ val : float
621
+ """
622
+ if self.orientation == 'vertical':
623
+ self.poly.set_height(val - self.poly.get_y())
624
+ self._handle.set_ydata([val])
625
+ else:
626
+ self.poly.set_width(val - self.poly.get_x())
627
+ self._handle.set_xdata([val])
628
+ self.valtext.set_text(self._format(val))
629
+ if self.drawon:
630
+ self.ax.get_figure(root=True).canvas.draw_idle()
631
+ self.val = val
632
+ if self.eventson:
633
+ self._observers.process('changed', val)
634
+
635
+ def on_changed(self, func):
636
+ """
637
+ Connect *func* as callback function to changes of the slider value.
638
+
639
+ Parameters
640
+ ----------
641
+ func : callable
642
+ Function to call when slider is changed.
643
+ The function must accept a single float as its arguments.
644
+
645
+ Returns
646
+ -------
647
+ int
648
+ Connection id (which can be used to disconnect *func*).
649
+ """
650
+ return self._observers.connect('changed', lambda val: func(val))
651
+
652
+
653
+ class RangeSlider(SliderBase):
654
+ """
655
+ A slider representing a range of floating point values. Defines the min and
656
+ max of the range via the *val* attribute as a tuple of (min, max).
657
+
658
+ Create a slider that defines a range contained within [*valmin*, *valmax*]
659
+ in Axes *ax*. For the slider to remain responsive you must maintain a
660
+ reference to it. Call :meth:`on_changed` to connect to the slider event.
661
+
662
+ Attributes
663
+ ----------
664
+ val : tuple of float
665
+ Slider value.
666
+ """
667
+
668
+ def __init__(
669
+ self,
670
+ ax,
671
+ label,
672
+ valmin,
673
+ valmax,
674
+ *,
675
+ valinit=None,
676
+ valfmt=None,
677
+ closedmin=True,
678
+ closedmax=True,
679
+ dragging=True,
680
+ valstep=None,
681
+ orientation="horizontal",
682
+ track_color='lightgrey',
683
+ handle_style=None,
684
+ **kwargs,
685
+ ):
686
+ """
687
+ Parameters
688
+ ----------
689
+ ax : Axes
690
+ The Axes to put the slider in.
691
+
692
+ label : str
693
+ Slider label.
694
+
695
+ valmin : float
696
+ The minimum value of the slider.
697
+
698
+ valmax : float
699
+ The maximum value of the slider.
700
+
701
+ valinit : tuple of float or None, default: None
702
+ The initial positions of the slider. If None the initial positions
703
+ will be at the 25th and 75th percentiles of the range.
704
+
705
+ valfmt : str or callable, default: None
706
+ The way to format the range's minimal and maximal values. If a
707
+ string, it must be in %-format. If a callable, it must have the
708
+ signature ``valfmt(val: float) -> str``. If None, a
709
+ `.ScalarFormatter` is used.
710
+
711
+ closedmin : bool, default: True
712
+ Whether the slider interval is closed on the bottom.
713
+
714
+ closedmax : bool, default: True
715
+ Whether the slider interval is closed on the top.
716
+
717
+ dragging : bool, default: True
718
+ If True the slider can be dragged by the mouse.
719
+
720
+ valstep : float, default: None
721
+ If given, the slider will snap to multiples of *valstep*.
722
+
723
+ orientation : {'horizontal', 'vertical'}, default: 'horizontal'
724
+ The orientation of the slider.
725
+
726
+ track_color : :mpltype:`color`, default: 'lightgrey'
727
+ The color of the background track. The track is accessible for
728
+ further styling via the *track* attribute.
729
+
730
+ handle_style : dict
731
+ Properties of the slider handles. Default values are
732
+
733
+ ========= ===== ======= =========================================
734
+ Key Value Default Description
735
+ ========= ===== ======= =========================================
736
+ facecolor color 'white' The facecolor of the slider handles.
737
+ edgecolor color '.75' The edgecolor of the slider handles.
738
+ size int 10 The size of the slider handles in points.
739
+ ========= ===== ======= =========================================
740
+
741
+ Other values will be transformed as marker{foo} and passed to the
742
+ `~.Line2D` constructor. e.g. ``handle_style = {'style'='x'}`` will
743
+ result in ``markerstyle = 'x'``.
744
+
745
+ Notes
746
+ -----
747
+ Additional kwargs are passed on to ``self.poly`` which is the
748
+ `~matplotlib.patches.Polygon` that draws the slider knob. See the
749
+ `.Polygon` documentation for valid property names (``facecolor``,
750
+ ``edgecolor``, ``alpha``, etc.).
751
+ """
752
+ super().__init__(ax, orientation, closedmin, closedmax,
753
+ valmin, valmax, valfmt, dragging, valstep)
754
+
755
+ # Set a value to allow _value_in_bounds() to work.
756
+ self.val = (valmin, valmax)
757
+ if valinit is None:
758
+ # Place at the 25th and 75th percentiles
759
+ extent = valmax - valmin
760
+ valinit = np.array([valmin + extent * 0.25,
761
+ valmin + extent * 0.75])
762
+ else:
763
+ valinit = self._value_in_bounds(valinit)
764
+ self.val = valinit
765
+ self.valinit = valinit
766
+
767
+ defaults = {'facecolor': 'white', 'edgecolor': '.75', 'size': 10}
768
+ handle_style = {} if handle_style is None else handle_style
769
+ marker_props = {
770
+ f'marker{k}': v for k, v in {**defaults, **handle_style}.items()
771
+ }
772
+
773
+ if orientation == "vertical":
774
+ self.track = Rectangle(
775
+ (.25, 0), .5, 2,
776
+ transform=ax.transAxes,
777
+ facecolor=track_color
778
+ )
779
+ ax.add_patch(self.track)
780
+ poly_transform = self.ax.get_yaxis_transform(which="grid")
781
+ handleXY_1 = [.5, valinit[0]]
782
+ handleXY_2 = [.5, valinit[1]]
783
+ else:
784
+ self.track = Rectangle(
785
+ (0, .25), 1, .5,
786
+ transform=ax.transAxes,
787
+ facecolor=track_color
788
+ )
789
+ ax.add_patch(self.track)
790
+ poly_transform = self.ax.get_xaxis_transform(which="grid")
791
+ handleXY_1 = [valinit[0], .5]
792
+ handleXY_2 = [valinit[1], .5]
793
+ self.poly = Polygon(np.zeros([5, 2]), **kwargs)
794
+ self._update_selection_poly(*valinit)
795
+ self.poly.set_transform(poly_transform)
796
+ self.poly.get_path()._interpolation_steps = 100
797
+ self.ax.add_patch(self.poly)
798
+ self.ax._request_autoscale_view()
799
+ self._handles = [
800
+ ax.plot(
801
+ *handleXY_1,
802
+ "o",
803
+ **marker_props,
804
+ clip_on=False
805
+ )[0],
806
+ ax.plot(
807
+ *handleXY_2,
808
+ "o",
809
+ **marker_props,
810
+ clip_on=False
811
+ )[0]
812
+ ]
813
+
814
+ if orientation == "vertical":
815
+ self.label = ax.text(
816
+ 0.5,
817
+ 1.02,
818
+ label,
819
+ transform=ax.transAxes,
820
+ verticalalignment="bottom",
821
+ horizontalalignment="center",
822
+ )
823
+
824
+ self.valtext = ax.text(
825
+ 0.5,
826
+ -0.02,
827
+ self._format(valinit),
828
+ transform=ax.transAxes,
829
+ verticalalignment="top",
830
+ horizontalalignment="center",
831
+ )
832
+ else:
833
+ self.label = ax.text(
834
+ -0.02,
835
+ 0.5,
836
+ label,
837
+ transform=ax.transAxes,
838
+ verticalalignment="center",
839
+ horizontalalignment="right",
840
+ )
841
+
842
+ self.valtext = ax.text(
843
+ 1.02,
844
+ 0.5,
845
+ self._format(valinit),
846
+ transform=ax.transAxes,
847
+ verticalalignment="center",
848
+ horizontalalignment="left",
849
+ )
850
+
851
+ self._active_handle = None
852
+ self.set_val(valinit)
853
+
854
+ def _update_selection_poly(self, vmin, vmax):
855
+ """
856
+ Update the vertices of the *self.poly* slider in-place
857
+ to cover the data range *vmin*, *vmax*.
858
+ """
859
+ # The vertices are positioned
860
+ # 1 ------ 2
861
+ # | |
862
+ # 0, 4 ---- 3
863
+ verts = self.poly.xy
864
+ if self.orientation == "vertical":
865
+ verts[0] = verts[4] = .25, vmin
866
+ verts[1] = .25, vmax
867
+ verts[2] = .75, vmax
868
+ verts[3] = .75, vmin
869
+ else:
870
+ verts[0] = verts[4] = vmin, .25
871
+ verts[1] = vmin, .75
872
+ verts[2] = vmax, .75
873
+ verts[3] = vmax, .25
874
+
875
+ def _min_in_bounds(self, min):
876
+ """Ensure the new min value is between valmin and self.val[1]."""
877
+ if min <= self.valmin:
878
+ if not self.closedmin:
879
+ return self.val[0]
880
+ min = self.valmin
881
+
882
+ if min > self.val[1]:
883
+ min = self.val[1]
884
+ return self._stepped_value(min)
885
+
886
+ def _max_in_bounds(self, max):
887
+ """Ensure the new max value is between valmax and self.val[0]."""
888
+ if max >= self.valmax:
889
+ if not self.closedmax:
890
+ return self.val[1]
891
+ max = self.valmax
892
+
893
+ if max <= self.val[0]:
894
+ max = self.val[0]
895
+ return self._stepped_value(max)
896
+
897
+ def _value_in_bounds(self, vals):
898
+ """Clip min, max values to the bounds."""
899
+ return (self._min_in_bounds(vals[0]), self._max_in_bounds(vals[1]))
900
+
901
+ def _update_val_from_pos(self, pos):
902
+ """Update the slider value based on a given position."""
903
+ idx = np.argmin(np.abs(self.val - pos))
904
+ if idx == 0:
905
+ val = self._min_in_bounds(pos)
906
+ self.set_min(val)
907
+ else:
908
+ val = self._max_in_bounds(pos)
909
+ self.set_max(val)
910
+ if self._active_handle:
911
+ if self.orientation == "vertical":
912
+ self._active_handle.set_ydata([val])
913
+ else:
914
+ self._active_handle.set_xdata([val])
915
+
916
+ @_call_with_reparented_event
917
+ def _update(self, event):
918
+ """Update the slider position."""
919
+ if self.ignore(event) or event.button != 1:
920
+ return
921
+
922
+ if event.name == "button_press_event" and self.ax.contains(event)[0]:
923
+ self.drag_active = True
924
+ event.canvas.grab_mouse(self.ax)
925
+
926
+ if not self.drag_active:
927
+ return
928
+
929
+ if (event.name == "button_release_event"
930
+ or event.name == "button_press_event" and not self.ax.contains(event)[0]):
931
+ self.drag_active = False
932
+ event.canvas.release_mouse(self.ax)
933
+ self._active_handle = None
934
+ return
935
+
936
+ # determine which handle was grabbed
937
+ handle_index = np.argmin(np.abs(
938
+ [h.get_xdata()[0] - event.xdata for h in self._handles]
939
+ if self.orientation == "horizontal" else
940
+ [h.get_ydata()[0] - event.ydata for h in self._handles]))
941
+ handle = self._handles[handle_index]
942
+
943
+ # these checks ensure smooth behavior if the handles swap which one
944
+ # has a higher value. i.e. if one is dragged over and past the other.
945
+ if handle is not self._active_handle:
946
+ self._active_handle = handle
947
+
948
+ self._update_val_from_pos(
949
+ event.xdata if self.orientation == "horizontal" else event.ydata)
950
+
951
+ def _format(self, val):
952
+ """Pretty-print *val*."""
953
+ if self.valfmt is not None:
954
+ if callable(self.valfmt):
955
+ return f"({self.valfmt(val[0])}, {self.valfmt(val[1])})"
956
+ else:
957
+ return f"({self.valfmt % val[0]}, {self.valfmt % val[1]})"
958
+ else:
959
+ _, s1, s2, _ = self._fmt.format_ticks(
960
+ [self.valmin, *val, self.valmax]
961
+ )
962
+ # fmt.get_offset is actually the multiplicative factor, if any.
963
+ s1 += self._fmt.get_offset()
964
+ s2 += self._fmt.get_offset()
965
+ # Use f string to avoid issues with backslashes when cast to a str
966
+ return f"({s1}, {s2})"
967
+
968
+ def set_min(self, min):
969
+ """
970
+ Set the lower value of the slider to *min*.
971
+
972
+ Parameters
973
+ ----------
974
+ min : float
975
+ """
976
+ self.set_val((min, self.val[1]))
977
+
978
+ def set_max(self, max):
979
+ """
980
+ Set the lower value of the slider to *max*.
981
+
982
+ Parameters
983
+ ----------
984
+ max : float
985
+ """
986
+ self.set_val((self.val[0], max))
987
+
988
+ def set_val(self, val):
989
+ """
990
+ Set slider value to *val*.
991
+
992
+ Parameters
993
+ ----------
994
+ val : tuple or array-like of float
995
+ """
996
+ val = np.sort(val)
997
+ _api.check_shape((2,), val=val)
998
+ # Reset value to allow _value_in_bounds() to work.
999
+ self.val = (self.valmin, self.valmax)
1000
+ vmin, vmax = self._value_in_bounds(val)
1001
+ self._update_selection_poly(vmin, vmax)
1002
+ if self.orientation == "vertical":
1003
+ self._handles[0].set_ydata([vmin])
1004
+ self._handles[1].set_ydata([vmax])
1005
+ else:
1006
+ self._handles[0].set_xdata([vmin])
1007
+ self._handles[1].set_xdata([vmax])
1008
+
1009
+ self.valtext.set_text(self._format((vmin, vmax)))
1010
+
1011
+ if self.drawon:
1012
+ self.ax.get_figure(root=True).canvas.draw_idle()
1013
+ self.val = (vmin, vmax)
1014
+ if self.eventson:
1015
+ self._observers.process("changed", (vmin, vmax))
1016
+
1017
+ def on_changed(self, func):
1018
+ """
1019
+ Connect *func* as callback function to changes of the slider value.
1020
+
1021
+ Parameters
1022
+ ----------
1023
+ func : callable
1024
+ Function to call when slider is changed. The function
1025
+ must accept a 2-tuple of floats as its argument.
1026
+
1027
+ Returns
1028
+ -------
1029
+ int
1030
+ Connection id (which can be used to disconnect *func*).
1031
+ """
1032
+ return self._observers.connect('changed', lambda val: func(val))
1033
+
1034
+
1035
+ def _expand_text_props(props):
1036
+ props = cbook.normalize_kwargs(props, mtext.Text)
1037
+ return cycler(**props)() if props else itertools.repeat({})
1038
+
1039
+
1040
+ class _Buttons(AxesWidget):
1041
+ """
1042
+ The base class for `CheckButtons` and `RadioButtons`.
1043
+
1044
+ This class provides common functionality for button widgets,
1045
+ such as handling click events, managing button labels, and connecting callbacks.
1046
+
1047
+ The class itself is private and may be changed or removed without prior warning.
1048
+ However, the public API it provides to subclasses is stable and considered
1049
+ public on the subclasses.
1050
+ """
1051
+
1052
+ def __init__(self, ax, labels, *, useblit=True, label_props=None, layout=None,
1053
+ **kwargs):
1054
+ super().__init__(ax)
1055
+
1056
+ ax.set_xticks([])
1057
+ ax.set_yticks([])
1058
+ ax.set_navigate(False)
1059
+
1060
+ self._useblit = useblit
1061
+
1062
+ self._init_layout(layout, labels, label_props)
1063
+ text_size = np.array([text.get_fontsize() for text in self.labels]) / 2
1064
+
1065
+ self._init_props(text_size, **kwargs)
1066
+
1067
+ self.connect_event('button_press_event', self._clicked)
1068
+ if self._useblit:
1069
+ self.connect_event('draw_event', self._clear)
1070
+
1071
+ self._observers = cbook.CallbackRegistry(signals=["clicked"])
1072
+
1073
+ def _init_layout(self, layout, labels, label_props):
1074
+
1075
+ label_props = _expand_text_props(label_props)
1076
+
1077
+ if layout is None:
1078
+ # legacy hard-coded vertical layout
1079
+ self._buttons_xs = [0.15] * len(labels)
1080
+ self._buttons_ys = np.linspace(1, 0, len(labels)+2)[1:-1]
1081
+ self.labels = [
1082
+ self.ax.text(0.25, y, label, transform=self.ax.transAxes,
1083
+ horizontalalignment="left", verticalalignment="center",
1084
+ **props)
1085
+ for y, label, props in zip(self._buttons_ys, labels, label_props)]
1086
+ return
1087
+
1088
+ # New layout algorithm with text measurement
1089
+ # Parse layout parameter
1090
+ n_labels = len(labels)
1091
+ match layout:
1092
+ case "vertical":
1093
+ n_rows, n_cols = n_labels, 1
1094
+ case "horizontal":
1095
+ n_rows, n_cols = 1, n_labels
1096
+ case (int() as n_rows, int() as n_cols):
1097
+ if n_rows * n_cols < n_labels:
1098
+ raise ValueError(
1099
+ f"layout {layout} has {n_rows * n_cols} positions but "
1100
+ f"{n_labels} labels were provided"
1101
+ )
1102
+ case _:
1103
+ raise ValueError(
1104
+ "layout must be None, 'vertical', 'horizontal', or a (rows, cols) "
1105
+ f"tuple; got {layout!r}")
1106
+
1107
+ # Define spacing in points for DPI-independent sizing
1108
+ fig = self.ax.get_figure(root=False)
1109
+ axes_width_display = 72 * self.ax.bbox.transformed(
1110
+ fig.dpi_scale_trans.inverted()
1111
+ ).width
1112
+ left_margin_display = 11 # points
1113
+ button_text_offset_display = 5.5 # points
1114
+ col_spacing_display = 11 # points
1115
+
1116
+ # Convert to axes coordinates
1117
+ left_margin = left_margin_display / axes_width_display
1118
+ button_text_offset = button_text_offset_display / axes_width_display
1119
+ col_spacing = col_spacing_display / axes_width_display
1120
+
1121
+ # Create text objects to measure widths.
1122
+ # We create Text objects directly rather than using ax.text() since we're
1123
+ # only measuring them and only later add them to the axes.
1124
+ self.labels = [
1125
+ mtext.Text(0, 0, text=label, transform=self.ax.transAxes,
1126
+ horizontalalignment="left", verticalalignment="center",
1127
+ **props)
1128
+ for label, props in zip(labels, label_props)
1129
+ ]
1130
+ # Set figure reference so Text objects can access figure properties
1131
+ for text in self.labels:
1132
+ text.set_figure(fig)
1133
+ # Calculate max text width per column (in axes coordinates)
1134
+ renderer = self.ax.figure.canvas.get_renderer()
1135
+ inv_trans = fig.dpi_scale_trans.inverted()
1136
+ col_widths = [
1137
+ max(
1138
+ (
1139
+ text.get_window_extent(renderer).transformed(inv_trans).width * 72
1140
+ for text in self.labels[col_idx::n_cols]
1141
+ ),
1142
+ default=0,
1143
+ )
1144
+ / axes_width_display
1145
+ for col_idx in range(n_cols)
1146
+ ]
1147
+
1148
+ # Center rows vertically in the axes
1149
+ ys_per_row = np.linspace(1, 0, n_rows + 2)[1:-1]
1150
+ # Calculate x positions based on text widths
1151
+ col_x_positions = [left_margin] # First column starts at left margin
1152
+ for col_idx in range(n_cols - 1):
1153
+ col_x_positions.append(
1154
+ col_x_positions[-1] +
1155
+ button_text_offset +
1156
+ col_widths[col_idx] +
1157
+ col_spacing
1158
+ )
1159
+ label_idx = np.arange(n_labels)
1160
+ self._buttons_xs = np.take(col_x_positions, label_idx % n_cols)
1161
+ self._buttons_ys = ys_per_row[label_idx // n_cols]
1162
+ for text, x, y in zip(self.labels, self._buttons_xs, self._buttons_ys):
1163
+ text.set_position((x + button_text_offset, y))
1164
+ self.ax.add_artist(text)
1165
+
1166
+ def _init_props(self, text_size, **kwargs):
1167
+ raise NotImplementedError("This method should be defined in subclasses")
1168
+
1169
+ def _clear(self, event):
1170
+ """Internal event handler to clear the buttons."""
1171
+ if self.ignore(event) or self.canvas.is_saving():
1172
+ return
1173
+ if self._useblit and self.canvas.supports_blit:
1174
+ self._save_blit_background(self.canvas.copy_from_bbox(self.ax.bbox))
1175
+ self.ax.draw_artist(self._buttons)
1176
+
1177
+ def set_label_props(self, props):
1178
+ """
1179
+ Set properties of the `.Text` labels.
1180
+
1181
+ .. versionadded:: 3.7
1182
+
1183
+ Parameters
1184
+ ----------
1185
+ props : dict
1186
+ Dictionary of `.Text` properties to be used for the labels. Same
1187
+ format as label_props argument of :class:`RadioButtons` or
1188
+ :class:`CheckButtons`.
1189
+ """
1190
+ _api.check_isinstance(dict, props=props)
1191
+ props = _expand_text_props(props)
1192
+ for text, prop in zip(self.labels, props):
1193
+ text.update(prop)
1194
+
1195
+ @_call_with_reparented_event
1196
+ def _clicked(self, event):
1197
+ if self.ignore(event) or event.button != 1 or not self.ax.contains(event)[0]:
1198
+ return
1199
+ idxs = [ # Indices of frames and of texts that contain the event.
1200
+ *self._buttons.contains(event)[1]["ind"],
1201
+ *[i for i, text in enumerate(self.labels) if text.contains(event)[0]]]
1202
+ if idxs:
1203
+ coords = self._buttons.get_offset_transform().transform(
1204
+ self._buttons.get_offsets())
1205
+ self.set_active( # Closest index, only looking in idxs.
1206
+ idxs[(((event.x, event.y) - coords[idxs]) ** 2).sum(-1).argmin()])
1207
+
1208
+ def on_clicked(self, func):
1209
+ """
1210
+ Connect the callback function *func* to button click events.
1211
+
1212
+ Parameters
1213
+ ----------
1214
+ func : callable
1215
+ When the button is clicked, call *func* with button label.
1216
+ When all buttons are cleared, call *func* with None.
1217
+ The callback func must have the signature::
1218
+
1219
+ def func(label: str | None) -> Any
1220
+
1221
+ Return values may exist, but are ignored.
1222
+
1223
+ Returns
1224
+ -------
1225
+ A connection id, which can be used to disconnect the callback.
1226
+ """
1227
+ return self._observers.connect('clicked', func)
1228
+
1229
+ def disconnect(self, cid):
1230
+ """Remove the observer with connection id *cid*."""
1231
+ self._observers.disconnect(cid)
1232
+
1233
+
1234
+ class CheckButtons(_Buttons):
1235
+ r"""
1236
+ A GUI neutral set of check buttons.
1237
+
1238
+ For the check buttons to remain responsive you must keep a
1239
+ reference to this object.
1240
+
1241
+ Connect to the CheckButtons with the `~._Buttons.on_clicked` method.
1242
+
1243
+ Attributes
1244
+ ----------
1245
+ ax : `~matplotlib.axes.Axes`
1246
+ The parent Axes for the widget.
1247
+ labels : list of `~matplotlib.text.Text`
1248
+ The text label objects of the check buttons.
1249
+ """
1250
+
1251
+ def __init__(self, ax, labels, actives=None, *, layout=None, useblit=True,
1252
+ label_props=None, frame_props=None, check_props=None):
1253
+ """
1254
+ Add check buttons to `~.axes.Axes` instance *ax*.
1255
+
1256
+ Parameters
1257
+ ----------
1258
+ ax : `~matplotlib.axes.Axes`
1259
+ The parent Axes for the widget.
1260
+ labels : list of str
1261
+ The labels of the check buttons.
1262
+ actives : list of bool, optional
1263
+ The initial check states of the buttons. The list must have the
1264
+ same length as *labels*. If not given, all buttons are unchecked.
1265
+ layout : None or "vertical" or "horizontal" or (int, int), default: None
1266
+ The layout of the check buttons. Options are:
1267
+
1268
+ - ``None``: Use legacy vertical layout (default).
1269
+ - ``"vertical"``: Arrange buttons in a single column with
1270
+ dynamic positioning based on text widths.
1271
+ - ``"horizontal"``: Arrange buttons in a single row with
1272
+ dynamic positioning based on text widths.
1273
+ - ``(rows, cols)`` tuple: Arrange buttons in a grid with the
1274
+ specified number of rows and columns. Buttons are placed
1275
+ left-to-right, top-to-bottom with dynamic positioning.
1276
+
1277
+ The layout options "vertical", "horizontal" and ``(rows, cols)``
1278
+ create ``mtext.Text`` objects to determine exact text sizes, and
1279
+ then they are added to the Axes. This is usually okay, but may cause
1280
+ side-effects and has a slight performance impact. Therefore the
1281
+ default ``None`` value avoids this.
1282
+
1283
+ .. admonition:: Provisional
1284
+ The new layout options are provisional. Their algorithmic
1285
+ behavior, including the exact positions of buttons and labels,
1286
+ may still change without prior warning.
1287
+
1288
+ .. versionadded:: 3.11
1289
+ useblit : bool, default: True
1290
+ Use blitting for faster drawing if supported by the backend.
1291
+ See the tutorial :ref:`blitting` for details.
1292
+
1293
+ .. versionadded:: 3.7
1294
+
1295
+ label_props : dict of lists, optional
1296
+ Dictionary of `.Text` properties to be used for the labels. Each
1297
+ dictionary value should be a list of at least a single element. If
1298
+ the list is of length M, its values are cycled such that the Nth
1299
+ label gets the (N mod M) property.
1300
+
1301
+ .. versionadded:: 3.7
1302
+ frame_props : dict, optional
1303
+ Dictionary of scatter `.Collection` properties to be used for the
1304
+ check button frame. Defaults (label font size / 2)**2 size, black
1305
+ edgecolor, no facecolor, and 1.0 linewidth.
1306
+
1307
+ .. versionadded:: 3.7
1308
+ check_props : dict, optional
1309
+ Dictionary of scatter `.Collection` properties to be used for the
1310
+ check button check. Defaults to (label font size / 2)**2 size,
1311
+ black color, and 1.0 linewidth.
1312
+
1313
+ .. versionadded:: 3.7
1314
+ """
1315
+ _api.check_isinstance((dict, None), label_props=label_props,
1316
+ frame_props=frame_props, check_props=check_props)
1317
+
1318
+ super().__init__(ax, labels, layout=layout, useblit=useblit,
1319
+ label_props=label_props, actives=actives,
1320
+ frame_props=frame_props, check_props=check_props)
1321
+
1322
+ def _init_props(self, text_size, actives, frame_props, check_props):
1323
+ frame_props = {
1324
+ 's': text_size**2,
1325
+ 'linewidth': 1,
1326
+ **cbook.normalize_kwargs(frame_props, collections.PathCollection),
1327
+ 'marker': 's',
1328
+ 'transform': self.ax.transAxes,
1329
+ }
1330
+ frame_props.setdefault('facecolor', frame_props.get('color', 'none'))
1331
+ frame_props.setdefault('edgecolor', frame_props.pop('color', 'black'))
1332
+ self._frames = self.ax.scatter(
1333
+ self._buttons_xs,
1334
+ self._buttons_ys,
1335
+ **frame_props,
1336
+ )
1337
+ check_props = {
1338
+ 'linewidth': 1,
1339
+ 's': text_size**2,
1340
+ **cbook.normalize_kwargs(check_props, collections.PathCollection),
1341
+ 'marker': 'x',
1342
+ 'transform': self.ax.transAxes,
1343
+ 'animated': self._useblit and self.canvas.supports_blit,
1344
+ # TODO: This may need an update when switching out the canvas.
1345
+ # Can set this to `_useblit` only and live with the animated=True
1346
+ # overhead on unsupported backends.
1347
+ }
1348
+ check_props.setdefault('facecolor', check_props.pop('color', 'black'))
1349
+ self._buttons = self.ax.scatter(
1350
+ self._buttons_xs,
1351
+ self._buttons_ys,
1352
+ **check_props
1353
+ )
1354
+ if actives is None:
1355
+ actives = [False] * len(self.labels)
1356
+ # The user may have passed custom colours in check_props, so we need to
1357
+ # create the checks (above), and modify the visibility after getting
1358
+ # whatever the user set.
1359
+ self._init_status(actives)
1360
+
1361
+ def set_frame_props(self, props):
1362
+ """
1363
+ Set properties of the check button frames.
1364
+
1365
+ .. versionadded:: 3.7
1366
+
1367
+ Parameters
1368
+ ----------
1369
+ props : dict
1370
+ Dictionary of `.Collection` properties to be used for the check
1371
+ button frames.
1372
+ """
1373
+ _api.check_isinstance(dict, props=props)
1374
+ if 's' in props: # Keep API consistent with constructor.
1375
+ props['sizes'] = np.broadcast_to(props.pop('s'), len(self.labels))
1376
+ self._frames.update(props)
1377
+
1378
+ def set_check_props(self, props):
1379
+ """
1380
+ Set properties of the check button checks.
1381
+
1382
+ .. versionadded:: 3.7
1383
+
1384
+ Parameters
1385
+ ----------
1386
+ props : dict
1387
+ Dictionary of `.Collection` properties to be used for the check
1388
+ button check.
1389
+ """
1390
+ _api.check_isinstance(dict, props=props)
1391
+ if 's' in props: # Keep API consistent with constructor.
1392
+ props['sizes'] = np.broadcast_to(props.pop('s'), len(self.labels))
1393
+ actives = self.get_status()
1394
+ self._buttons.update(props)
1395
+ # If new colours are supplied, then we must re-apply the status.
1396
+ self._init_status(actives)
1397
+
1398
+ def set_active(self, index, state=None):
1399
+ """
1400
+ Modify the state of a check button by index.
1401
+
1402
+ Callbacks will be triggered if :attr:`!eventson` is True.
1403
+
1404
+ Parameters
1405
+ ----------
1406
+ index : int
1407
+ Index of the check button to toggle.
1408
+
1409
+ state : bool, optional
1410
+ If a boolean value, set the state explicitly. If no value is
1411
+ provided, the state is toggled.
1412
+
1413
+ Raises
1414
+ ------
1415
+ ValueError
1416
+ If *index* is invalid.
1417
+ TypeError
1418
+ If *state* is not boolean.
1419
+ """
1420
+ if index not in range(len(self.labels)):
1421
+ raise ValueError(f'Invalid CheckButton index: {index}')
1422
+ _api.check_isinstance((bool, None), state=state)
1423
+
1424
+ invisible = colors.to_rgba('none')
1425
+
1426
+ facecolors = self._buttons.get_facecolor()
1427
+ if state is None:
1428
+ state = colors.same_color(facecolors[index], invisible)
1429
+ facecolors[index] = self._active_check_colors[index] if state else invisible
1430
+ self._buttons.set_facecolor(facecolors)
1431
+
1432
+ if self.drawon:
1433
+ if self._useblit and self.canvas.supports_blit:
1434
+ background = self._load_blit_background()
1435
+ if background is not None:
1436
+ self.canvas.restore_region(background)
1437
+ self.ax.draw_artist(self._buttons)
1438
+ self.canvas.blit(self.ax.bbox)
1439
+ else:
1440
+ self.canvas.draw()
1441
+
1442
+ if self.eventson:
1443
+ self._observers.process('clicked', self.labels[index].get_text())
1444
+
1445
+ def _init_status(self, actives):
1446
+ """
1447
+ Initialize properties to match active status.
1448
+
1449
+ The user may have passed custom colours in *check_props* to the
1450
+ constructor, or to `.set_check_props`, so we need to modify the
1451
+ visibility after getting whatever the user set.
1452
+ """
1453
+ self._active_check_colors = self._buttons.get_facecolor()
1454
+ if len(self._active_check_colors) == 1:
1455
+ self._active_check_colors = np.repeat(self._active_check_colors,
1456
+ len(actives), axis=0)
1457
+ self._buttons.set_facecolor(
1458
+ [ec if active else "none"
1459
+ for ec, active in zip(self._active_check_colors, actives)])
1460
+
1461
+ def clear(self):
1462
+ """Uncheck all checkboxes."""
1463
+
1464
+ self._buttons.set_facecolor(['none'] * len(self._active_check_colors))
1465
+
1466
+ if hasattr(self, '_lines'):
1467
+ for l1, l2 in self._lines:
1468
+ l1.set_visible(False)
1469
+ l2.set_visible(False)
1470
+
1471
+ if self.drawon:
1472
+ self.canvas.draw()
1473
+
1474
+ if self.eventson:
1475
+ # Call with no label, as all checkboxes are being cleared.
1476
+ self._observers.process('clicked', None)
1477
+
1478
+ def get_status(self):
1479
+ """
1480
+ Return a list of the status (True/False) of all of the check buttons.
1481
+ """
1482
+ return [not colors.same_color(color, colors.to_rgba("none"))
1483
+ for color in self._buttons.get_facecolors()]
1484
+
1485
+ def get_checked_labels(self):
1486
+ """Return a list of labels currently checked by user."""
1487
+
1488
+ return [l.get_text() for l, box_checked in
1489
+ zip(self.labels, self.get_status())
1490
+ if box_checked]
1491
+
1492
+
1493
+ class TextBox(AxesWidget):
1494
+ """
1495
+ A GUI neutral text input box.
1496
+
1497
+ For the text box to remain responsive you must keep a reference to it.
1498
+
1499
+ Call `.on_text_change` to be updated whenever the text changes.
1500
+
1501
+ Call `.on_submit` to be updated whenever the user hits enter or
1502
+ leaves the text entry field.
1503
+
1504
+ Attributes
1505
+ ----------
1506
+ ax : `~matplotlib.axes.Axes`
1507
+ The parent Axes for the widget.
1508
+ label : `~matplotlib.text.Text`
1509
+
1510
+ color : :mpltype:`color`
1511
+ The color of the text box when not hovering.
1512
+ hovercolor : :mpltype:`color`
1513
+ The color of the text box when hovering.
1514
+ """
1515
+
1516
+ def __init__(self, ax, label, initial='', *,
1517
+ color='.95', hovercolor='1', label_pad=.01,
1518
+ textalignment="left"):
1519
+ """
1520
+ Parameters
1521
+ ----------
1522
+ ax : `~matplotlib.axes.Axes`
1523
+ The `~.axes.Axes` instance the button will be placed into.
1524
+ label : str
1525
+ Label for this text box.
1526
+ initial : str
1527
+ Initial value in the text box.
1528
+ color : :mpltype:`color`
1529
+ The color of the box.
1530
+ hovercolor : :mpltype:`color`
1531
+ The color of the box when the mouse is over it.
1532
+ label_pad : float
1533
+ The distance between the label and the right side of the textbox.
1534
+ textalignment : {'left', 'center', 'right'}
1535
+ The horizontal location of the text.
1536
+ """
1537
+ super().__init__(ax)
1538
+
1539
+ self._text_position = _api.getitem_checked(
1540
+ {"left": 0.05, "center": 0.5, "right": 0.95},
1541
+ textalignment=textalignment)
1542
+
1543
+ self.label = ax.text(
1544
+ -label_pad, 0.5, label, transform=ax.transAxes,
1545
+ verticalalignment='center', horizontalalignment='right')
1546
+
1547
+ # TextBox's text object should not parse mathtext at all.
1548
+ self.text_disp = self.ax.text(
1549
+ self._text_position, 0.5, initial, transform=self.ax.transAxes,
1550
+ verticalalignment='center', horizontalalignment=textalignment,
1551
+ parse_math=False)
1552
+
1553
+ self._observers = cbook.CallbackRegistry(signals=["change", "submit"])
1554
+
1555
+ ax.set(
1556
+ xlim=(0, 1), ylim=(0, 1), # s.t. cursor appears from first click.
1557
+ navigate=False, facecolor=color,
1558
+ xticks=[], yticks=[])
1559
+
1560
+ self.cursor_index = 0
1561
+
1562
+ self.cursor = ax.vlines(0, 0, 0, visible=False, color="k", lw=1,
1563
+ transform=mpl.transforms.IdentityTransform())
1564
+
1565
+ self.connect_event('button_press_event', self._click)
1566
+ self.connect_event('button_release_event', self._release)
1567
+ self.connect_event('motion_notify_event', self._motion)
1568
+ self.connect_event('key_press_event', self._keypress)
1569
+ self.connect_event('resize_event', self._resize)
1570
+
1571
+ self.color = color
1572
+ self.hovercolor = hovercolor
1573
+
1574
+ self.capturekeystrokes = False
1575
+
1576
+ @property
1577
+ def text(self):
1578
+ return self.text_disp.get_text()
1579
+
1580
+ def _rendercursor(self):
1581
+ # this is a hack to figure out where the cursor should go.
1582
+ # we draw the text up to where the cursor should go, measure
1583
+ # and save its dimensions, draw the real text, then put the cursor
1584
+ # at the saved dimensions
1585
+
1586
+ # This causes a single extra draw if the figure has never been rendered
1587
+ # yet, which should be fine as we're going to repeatedly re-render the
1588
+ # figure later anyways.
1589
+ fig = self.ax.get_figure(root=True)
1590
+ if fig._get_renderer() is None:
1591
+ fig.canvas.draw()
1592
+
1593
+ text = self.text_disp.get_text() # Save value before overwriting it.
1594
+ widthtext = text[:self.cursor_index]
1595
+
1596
+ bb_text = self.text_disp.get_window_extent()
1597
+ self.text_disp.set_text(widthtext or ",")
1598
+ bb_widthtext = self.text_disp.get_window_extent()
1599
+
1600
+ if bb_text.y0 == bb_text.y1: # Restoring the height if no text.
1601
+ bb_text.y0 -= bb_widthtext.height / 2
1602
+ bb_text.y1 += bb_widthtext.height / 2
1603
+ elif not widthtext: # Keep width to 0.
1604
+ bb_text.x1 = bb_text.x0
1605
+ else: # Move the cursor using width of bb_widthtext.
1606
+ bb_text.x1 = bb_text.x0 + bb_widthtext.width
1607
+
1608
+ self.cursor.set(
1609
+ segments=[[(bb_text.x1, bb_text.y0), (bb_text.x1, bb_text.y1)]],
1610
+ visible=True)
1611
+ self.text_disp.set_text(text)
1612
+
1613
+ fig.canvas.draw()
1614
+
1615
+ @_call_with_reparented_event
1616
+ def _release(self, event):
1617
+ if self.ignore(event):
1618
+ return
1619
+ if event.canvas.mouse_grabber != self.ax:
1620
+ return
1621
+ event.canvas.release_mouse(self.ax)
1622
+
1623
+ @_call_with_reparented_event
1624
+ def _keypress(self, event):
1625
+ if self.ignore(event):
1626
+ return
1627
+ if self.capturekeystrokes:
1628
+ key = event.key
1629
+ text = self.text
1630
+ if len(key) == 1:
1631
+ text = (text[:self.cursor_index] + key +
1632
+ text[self.cursor_index:])
1633
+ self.cursor_index += 1
1634
+ elif key == "right":
1635
+ if self.cursor_index != len(text):
1636
+ self.cursor_index += 1
1637
+ elif key == "left":
1638
+ if self.cursor_index != 0:
1639
+ self.cursor_index -= 1
1640
+ elif key == "home":
1641
+ self.cursor_index = 0
1642
+ elif key == "end":
1643
+ self.cursor_index = len(text)
1644
+ elif key == "backspace":
1645
+ if self.cursor_index != 0:
1646
+ text = (text[:self.cursor_index - 1] +
1647
+ text[self.cursor_index:])
1648
+ self.cursor_index -= 1
1649
+ elif key == "delete":
1650
+ if self.cursor_index != len(self.text):
1651
+ text = (text[:self.cursor_index] +
1652
+ text[self.cursor_index + 1:])
1653
+ self.text_disp.set_text(text)
1654
+ self._rendercursor()
1655
+ if self.eventson:
1656
+ self._observers.process('change', self.text)
1657
+ if key in ["enter", "return"]:
1658
+ self._observers.process('submit', self.text)
1659
+
1660
+ def set_val(self, val):
1661
+ newval = str(val)
1662
+ if self.text == newval:
1663
+ return
1664
+ self.text_disp.set_text(newval)
1665
+ self._rendercursor()
1666
+ if self.eventson:
1667
+ self._observers.process('change', self.text)
1668
+ self._observers.process('submit', self.text)
1669
+
1670
+ def begin_typing(self):
1671
+ self.capturekeystrokes = True
1672
+ # Disable keypress shortcuts, which may otherwise cause the figure to
1673
+ # be saved, closed, etc., until the user stops typing. The way to
1674
+ # achieve this depends on whether toolmanager is in use.
1675
+ stack = ExitStack() # Register cleanup actions when user stops typing.
1676
+ self._on_stop_typing = stack.close
1677
+ toolmanager = getattr(
1678
+ self.ax.get_figure(root=True).canvas.manager, "toolmanager", None)
1679
+ if toolmanager is not None:
1680
+ # If using toolmanager, lock keypresses, and plan to release the
1681
+ # lock when typing stops.
1682
+ toolmanager.keypresslock(self)
1683
+ stack.callback(toolmanager.keypresslock.release, self)
1684
+ else:
1685
+ # If not using toolmanager, disable all keypress-related rcParams.
1686
+ # Avoid spurious warnings if keymaps are getting deprecated.
1687
+ with _api.suppress_matplotlib_deprecation_warning():
1688
+ stack.enter_context(mpl.rc_context(
1689
+ {k: [] for k in mpl.rcParams if k.startswith("keymap.")}))
1690
+
1691
+ def stop_typing(self):
1692
+ if self.capturekeystrokes:
1693
+ self._on_stop_typing()
1694
+ self._on_stop_typing = None
1695
+ notifysubmit = True
1696
+ else:
1697
+ notifysubmit = False
1698
+ self.capturekeystrokes = False
1699
+ self.cursor.set_visible(False)
1700
+ self.ax.get_figure(root=True).canvas.draw()
1701
+ if notifysubmit and self.eventson:
1702
+ # Because process() might throw an error in the user's code, only
1703
+ # call it once we've already done our cleanup.
1704
+ self._observers.process('submit', self.text)
1705
+
1706
+ @_call_with_reparented_event
1707
+ def _click(self, event):
1708
+ if self.ignore(event):
1709
+ return
1710
+ if not self.ax.contains(event)[0]:
1711
+ self.stop_typing()
1712
+ return
1713
+ if not self.eventson:
1714
+ return
1715
+ if event.canvas.mouse_grabber != self.ax:
1716
+ event.canvas.grab_mouse(self.ax)
1717
+ if not self.capturekeystrokes:
1718
+ self.begin_typing()
1719
+ self.cursor_index = self.text_disp._char_index_at(event.x)
1720
+ self._rendercursor()
1721
+
1722
+ def _resize(self, event):
1723
+ self.stop_typing()
1724
+
1725
+ @_call_with_reparented_event
1726
+ def _motion(self, event):
1727
+ if self.ignore(event):
1728
+ return
1729
+ c = self.hovercolor if self.ax.contains(event)[0] else self.color
1730
+ if not colors.same_color(c, self.ax.get_facecolor()):
1731
+ self.ax.set_facecolor(c)
1732
+ if self.drawon:
1733
+ self.ax.get_figure(root=True).canvas.draw()
1734
+
1735
+ def on_text_change(self, func):
1736
+ """
1737
+ When the text changes, call this *func* with event.
1738
+
1739
+ A connection id is returned which can be used to disconnect.
1740
+ """
1741
+ return self._observers.connect('change', lambda text: func(text))
1742
+
1743
+ def on_submit(self, func):
1744
+ """
1745
+ When the user hits enter or leaves the submission box, call this
1746
+ *func* with event.
1747
+
1748
+ A connection id is returned which can be used to disconnect.
1749
+ """
1750
+ return self._observers.connect('submit', lambda text: func(text))
1751
+
1752
+ def disconnect(self, cid):
1753
+ """Remove the observer with connection id *cid*."""
1754
+ self._observers.disconnect(cid)
1755
+
1756
+
1757
+ class RadioButtons(_Buttons):
1758
+ """
1759
+ A GUI neutral radio button.
1760
+
1761
+ For the buttons to remain responsive you must keep a reference to this
1762
+ object.
1763
+
1764
+ Connect to the RadioButtons with the `~._Buttons.on_clicked` method.
1765
+
1766
+ Attributes
1767
+ ----------
1768
+ ax : `~matplotlib.axes.Axes`
1769
+ The parent Axes for the widget.
1770
+ activecolor : :mpltype:`color`
1771
+ The color of the selected button.
1772
+ labels : list of `.Text`
1773
+ The button labels.
1774
+ value_selected : str
1775
+ The label text of the currently selected button.
1776
+ index_selected : int
1777
+ The index of the selected button.
1778
+ """
1779
+
1780
+ def __init__(self, ax, labels, active=0, activecolor=None, *, layout=None,
1781
+ useblit=True, label_props=None, radio_props=None):
1782
+ """
1783
+ Add radio buttons to an `~.axes.Axes`.
1784
+
1785
+ Parameters
1786
+ ----------
1787
+ ax : `~matplotlib.axes.Axes`
1788
+ The Axes to add the buttons to.
1789
+ labels : list of str
1790
+ The button labels.
1791
+ active : int
1792
+ The index of the initially selected button.
1793
+ activecolor : :mpltype:`color`
1794
+ The color of the selected button. The default is ``'blue'`` if not
1795
+ specified here or in *radio_props*.
1796
+ layout : None or "vertical" or "horizontal" or (int, int), default: None
1797
+ The layout of the radio buttons. Options are:
1798
+
1799
+ - ``None``: Use legacy vertical layout (default).
1800
+ - ``"vertical"``: Arrange buttons in a single column with
1801
+ dynamic positioning based on text widths.
1802
+ - ``"horizontal"``: Arrange buttons in a single row with
1803
+ dynamic positioning based on text widths.
1804
+ - ``(rows, cols)`` tuple: Arrange buttons in a grid with the
1805
+ specified number of rows and columns. Buttons are placed
1806
+ left-to-right, top-to-bottom with dynamic positioning.
1807
+
1808
+ The layout options "vertical", "horizontal" and ``(rows, cols)``
1809
+ create ``mtext.Text`` objects to determine exact text sizes, and
1810
+ then they are added to the Axes. This is usually okay, but may cause
1811
+ side-effects and has a slight performance impact. Therefore the
1812
+ default ``None`` value avoids this.
1813
+
1814
+ .. admonition:: Provisional
1815
+ The new layout options are provisional. Their algorithmic
1816
+ behavior, including the exact positions of buttons and labels,
1817
+ may still change without prior warning.
1818
+
1819
+ .. versionadded:: 3.11
1820
+ useblit : bool, default: True
1821
+ Use blitting for faster drawing if supported by the backend.
1822
+ See the tutorial :ref:`blitting` for details.
1823
+
1824
+ .. versionadded:: 3.7
1825
+
1826
+ label_props : dict of lists, optional
1827
+ Dictionary of `.Text` properties to be used for the labels. Each
1828
+ dictionary value should be a list of at least a single element. If
1829
+ the list is of length M, its values are cycled such that the Nth
1830
+ label gets the (N mod M) property.
1831
+
1832
+ .. versionadded:: 3.7
1833
+ radio_props : dict, optional
1834
+ Dictionary of scatter `.Collection` properties to be used for the
1835
+ radio buttons. Defaults to (label font size / 2)**2 size, black
1836
+ edgecolor, and *activecolor* facecolor (when active).
1837
+
1838
+ .. note::
1839
+ If a facecolor is supplied in *radio_props*, it will override
1840
+ *activecolor*. This may be used to provide an active color per
1841
+ button.
1842
+
1843
+ .. versionadded:: 3.7
1844
+ """
1845
+ _api.check_isinstance((dict, None), label_props=label_props,
1846
+ radio_props=radio_props)
1847
+
1848
+ radio_props = cbook.normalize_kwargs(radio_props,
1849
+ collections.PathCollection)
1850
+ if activecolor is not None:
1851
+ if 'facecolor' in radio_props:
1852
+ _api.warn_external(
1853
+ 'Both the *activecolor* parameter and the *facecolor* '
1854
+ 'key in the *radio_props* parameter has been specified. '
1855
+ '*activecolor* will be ignored.')
1856
+ else:
1857
+ activecolor = 'blue' # Default.
1858
+ super().__init__(ax, labels, useblit=useblit, label_props=label_props,
1859
+ active=active, layout=layout, activecolor=activecolor,
1860
+ radio_props=radio_props)
1861
+
1862
+ self._activecolor = activecolor
1863
+ self._initial_active = active
1864
+ self.value_selected = labels[active]
1865
+ self.index_selected = active
1866
+
1867
+ def _init_props(self, text_size, active, activecolor, radio_props):
1868
+ radio_props = {
1869
+ 's': text_size**2,
1870
+ **radio_props,
1871
+ 'marker': 'o',
1872
+ 'transform': self.ax.transAxes,
1873
+ 'animated': self._useblit and self.canvas.supports_blit,
1874
+ # TODO: This may need an update when switching out the canvas.
1875
+ # Can set this to `_useblit` only and live with the animated=True
1876
+ # overhead on unsupported backends.
1877
+
1878
+ }
1879
+ radio_props.setdefault('edgecolor', radio_props.get('color', 'black'))
1880
+ radio_props.setdefault('facecolor',
1881
+ radio_props.pop('color', activecolor))
1882
+ self._buttons = self.ax.scatter(
1883
+ self._buttons_xs,
1884
+ self._buttons_ys,
1885
+ **radio_props,
1886
+ )
1887
+ # The user may have passed custom colours in radio_props, so we need to
1888
+ # create the radios, and modify the visibility after getting whatever
1889
+ # the user set.
1890
+ self._active_colors = self._buttons.get_facecolor()
1891
+ if len(self._active_colors) == 1:
1892
+ self._active_colors = np.repeat(self._active_colors, len(self.labels),
1893
+ axis=0)
1894
+ self._buttons.set_facecolor(
1895
+ [activecolor if i == active else "none"
1896
+ for i, activecolor in enumerate(self._active_colors)])
1897
+
1898
+ def set_radio_props(self, props):
1899
+ """
1900
+ Set properties of the `.Text` labels.
1901
+
1902
+ .. versionadded:: 3.7
1903
+
1904
+ Parameters
1905
+ ----------
1906
+ props : dict
1907
+ Dictionary of `.Collection` properties to be used for the radio
1908
+ buttons.
1909
+ """
1910
+ _api.check_isinstance(dict, props=props)
1911
+ if 's' in props: # Keep API consistent with constructor.
1912
+ props['sizes'] = np.broadcast_to(props.pop('s'), len(self.labels))
1913
+ self._buttons.update(props)
1914
+ self._active_colors = self._buttons.get_facecolor()
1915
+ if len(self._active_colors) == 1:
1916
+ self._active_colors = np.repeat(self._active_colors,
1917
+ len(self.labels), axis=0)
1918
+ self._buttons.set_facecolor(
1919
+ [activecolor if text.get_text() == self.value_selected else "none"
1920
+ for text, activecolor in zip(self.labels, self._active_colors)])
1921
+
1922
+ @property
1923
+ def activecolor(self):
1924
+ return self._activecolor
1925
+
1926
+ @activecolor.setter
1927
+ def activecolor(self, activecolor):
1928
+ colors._check_color_like(activecolor=activecolor)
1929
+ self._activecolor = activecolor
1930
+ self.set_radio_props({'facecolor': activecolor})
1931
+
1932
+ def set_active(self, index):
1933
+ """
1934
+ Select button with number *index*.
1935
+
1936
+ Callbacks will be triggered if :attr:`!eventson` is True.
1937
+
1938
+ Parameters
1939
+ ----------
1940
+ index : int
1941
+ The index of the button to activate.
1942
+
1943
+ Raises
1944
+ ------
1945
+ ValueError
1946
+ If the index is invalid.
1947
+ """
1948
+ if index not in range(len(self.labels)):
1949
+ raise ValueError(f'Invalid RadioButton index: {index}')
1950
+ self.value_selected = self.labels[index].get_text()
1951
+ self.index_selected = index
1952
+ button_facecolors = self._buttons.get_facecolor()
1953
+ button_facecolors[:] = colors.to_rgba("none")
1954
+ button_facecolors[index] = colors.to_rgba(self._active_colors[index])
1955
+ self._buttons.set_facecolor(button_facecolors)
1956
+
1957
+ if self.drawon:
1958
+ if self._useblit and self.canvas.supports_blit:
1959
+ background = self._load_blit_background()
1960
+ if background is not None:
1961
+ self.canvas.restore_region(background)
1962
+ self.ax.draw_artist(self._buttons)
1963
+ self.canvas.blit(self.ax.bbox)
1964
+ else:
1965
+ self.canvas.draw()
1966
+
1967
+ if self.eventson:
1968
+ self._observers.process('clicked', self.labels[index].get_text())
1969
+
1970
+ def clear(self):
1971
+ """Reset the active button to the initially active one."""
1972
+ self.set_active(self._initial_active)
1973
+
1974
+
1975
+ class SubplotTool(Widget):
1976
+ """
1977
+ A tool to adjust the subplot params of a `.Figure`.
1978
+ """
1979
+
1980
+ def __init__(self, targetfig, toolfig):
1981
+ """
1982
+ Parameters
1983
+ ----------
1984
+ targetfig : `~matplotlib.figure.Figure`
1985
+ The figure instance to adjust.
1986
+ toolfig : `~matplotlib.figure.Figure`
1987
+ The figure instance to embed the subplot tool into.
1988
+ """
1989
+
1990
+ self.figure = toolfig
1991
+ self.targetfig = targetfig
1992
+ toolfig.subplots_adjust(left=0.2, right=0.9)
1993
+ toolfig.suptitle("Click on slider to adjust subplot param")
1994
+
1995
+ self._sliders = []
1996
+ names = ["left", "bottom", "right", "top", "wspace", "hspace"]
1997
+ # The last subplot, removed below, keeps space for the "Reset" button.
1998
+ for name, ax in zip(names, toolfig.subplots(len(names) + 1)):
1999
+ ax.set_navigate(False)
2000
+ slider = Slider(ax, name, 0, 1,
2001
+ valinit=getattr(targetfig.subplotpars, name))
2002
+ slider.on_changed(self._on_slider_changed)
2003
+ self._sliders.append(slider)
2004
+ toolfig.axes[-1].remove()
2005
+ (self.sliderleft, self.sliderbottom, self.sliderright, self.slidertop,
2006
+ self.sliderwspace, self.sliderhspace) = self._sliders
2007
+ for slider in [self.sliderleft, self.sliderbottom,
2008
+ self.sliderwspace, self.sliderhspace]:
2009
+ slider.closedmax = False
2010
+ for slider in [self.sliderright, self.slidertop]:
2011
+ slider.closedmin = False
2012
+
2013
+ # constraints
2014
+ self.sliderleft.slidermax = self.sliderright
2015
+ self.sliderright.slidermin = self.sliderleft
2016
+ self.sliderbottom.slidermax = self.slidertop
2017
+ self.slidertop.slidermin = self.sliderbottom
2018
+
2019
+ bax = toolfig.add_axes((0.8, 0.05, 0.15, 0.075))
2020
+ self.buttonreset = Button(bax, 'Reset')
2021
+ self.buttonreset.on_clicked(self._on_reset)
2022
+
2023
+ def _on_slider_changed(self, _):
2024
+ self.targetfig.subplots_adjust(
2025
+ **{slider.label.get_text(): slider.val
2026
+ for slider in self._sliders})
2027
+ if self.drawon:
2028
+ self.targetfig.canvas.draw()
2029
+
2030
+ def _on_reset(self, event):
2031
+ with ExitStack() as stack:
2032
+ # Temporarily disable drawing on self and self's sliders, and
2033
+ # disconnect slider events (as the subplotparams can be temporarily
2034
+ # invalid, depending on the order in which they are restored).
2035
+ stack.enter_context(cbook._setattr_cm(self, drawon=False))
2036
+ for slider in self._sliders:
2037
+ stack.enter_context(
2038
+ cbook._setattr_cm(slider, drawon=False, eventson=False))
2039
+ # Reset the slider to the initial position.
2040
+ for slider in self._sliders:
2041
+ slider.reset()
2042
+ if self.drawon:
2043
+ event.canvas.draw() # Redraw the subplottool canvas.
2044
+ self._on_slider_changed(None) # Apply changes to the target window.
2045
+
2046
+
2047
+ class Cursor(AxesWidget):
2048
+ """
2049
+ A crosshair cursor that spans the Axes and moves with mouse cursor.
2050
+
2051
+ For the cursor to remain responsive you must keep a reference to it.
2052
+
2053
+ Parameters
2054
+ ----------
2055
+ ax : `~matplotlib.axes.Axes`
2056
+ The `~.axes.Axes` to attach the cursor to.
2057
+ horizOn : bool, default: True
2058
+ Whether to draw the horizontal line.
2059
+ vertOn : bool, default: True
2060
+ Whether to draw the vertical line.
2061
+ useblit : bool, default: False
2062
+ Use blitting for faster drawing if supported by the backend.
2063
+ See the tutorial :ref:`blitting` for details.
2064
+
2065
+ Other Parameters
2066
+ ----------------
2067
+ **lineprops
2068
+ `.Line2D` properties that control the appearance of the lines.
2069
+ See also `~.Axes.axhline`.
2070
+
2071
+ Examples
2072
+ --------
2073
+ See :doc:`/gallery/widgets/cursor`.
2074
+ """
2075
+ def __init__(self, ax, *, horizOn=True, vertOn=True, useblit=False,
2076
+ **lineprops):
2077
+ super().__init__(ax)
2078
+
2079
+ self.connect_event('motion_notify_event', self.onmove)
2080
+ self.connect_event('draw_event', self.clear)
2081
+
2082
+ self.visible = True
2083
+ self.horizOn = horizOn
2084
+ self.vertOn = vertOn
2085
+ self.useblit = useblit and self.canvas.supports_blit # TODO: make dynamic
2086
+
2087
+ if self.useblit:
2088
+ for ax_ in ax.get_figure(root=True).get_axes():
2089
+ if ax_ is not ax and ax.bbox.overlaps(ax_.bbox):
2090
+ _api.warn_external(
2091
+ "Cursor blitting is currently not supported on "
2092
+ "overlapping axes; falling back to useblit=False."
2093
+ )
2094
+ self.useblit = False
2095
+ break
2096
+
2097
+ if self.useblit:
2098
+ lineprops['animated'] = True
2099
+ self.lineh = ax.axhline(ax.get_ybound()[0], visible=False, **lineprops)
2100
+ self.linev = ax.axvline(ax.get_xbound()[0], visible=False, **lineprops)
2101
+
2102
+ self.needclear = False
2103
+
2104
+ def clear(self, event):
2105
+ """Internal event handler to clear the cursor."""
2106
+ if self.ignore(event) or self.canvas.is_saving():
2107
+ return
2108
+ if self.useblit:
2109
+ self._save_blit_background(self.canvas.copy_from_bbox(self.ax.bbox))
2110
+
2111
+ @_call_with_reparented_event
2112
+ def onmove(self, event):
2113
+ """Internal event handler to draw the cursor when the mouse moves."""
2114
+ if self.ignore(event):
2115
+ return
2116
+ if not self.canvas.widgetlock.available(self):
2117
+ return
2118
+ if not self.ax.contains(event)[0]:
2119
+ self.linev.set_visible(False)
2120
+ self.lineh.set_visible(False)
2121
+ if self.needclear:
2122
+ background = self._load_blit_background()
2123
+ if self.useblit and background is not None:
2124
+ self.canvas.restore_region(background)
2125
+ self.canvas.blit(self.ax.bbox)
2126
+ else:
2127
+ self.canvas.draw()
2128
+ self.needclear = False
2129
+ return
2130
+ self.needclear = True
2131
+ self.linev.set_xdata((event.xdata, event.xdata))
2132
+ self.linev.set_visible(self.visible and self.vertOn)
2133
+ self.lineh.set_ydata((event.ydata, event.ydata))
2134
+ self.lineh.set_visible(self.visible and self.horizOn)
2135
+ if not (self.visible and (self.vertOn or self.horizOn)):
2136
+ return
2137
+ # Redraw.
2138
+ if self.useblit:
2139
+ background = self._load_blit_background()
2140
+ if background is not None:
2141
+ self.canvas.restore_region(background)
2142
+ self.ax.draw_artist(self.linev)
2143
+ self.ax.draw_artist(self.lineh)
2144
+ self.canvas.blit(self.ax.bbox)
2145
+ else:
2146
+ self.canvas.draw_idle()
2147
+
2148
+
2149
+ class MultiCursor(Widget):
2150
+ """
2151
+ Provide a vertical (default) and/or horizontal line cursor shared between
2152
+ multiple Axes.
2153
+
2154
+ Call signatures::
2155
+
2156
+ MultiCursor(axes, *, ...)
2157
+ MultiCursor(canvas, axes, *, ...) # deprecated
2158
+
2159
+ For the cursor to remain responsive you must keep a reference to it.
2160
+
2161
+ Parameters
2162
+ ----------
2163
+ canvas : object
2164
+ This parameter is entirely unused.
2165
+
2166
+ .. deprecated:: 3.11
2167
+
2168
+ axes : list of `~matplotlib.axes.Axes`
2169
+ The `~.axes.Axes` to attach the cursor to.
2170
+
2171
+ useblit : bool, default: True
2172
+ Use blitting for faster drawing if supported by the backend.
2173
+ See the tutorial :ref:`blitting`
2174
+ for details.
2175
+
2176
+ horizOn : bool, default: False
2177
+ Whether to draw the horizontal line.
2178
+
2179
+ vertOn : bool, default: True
2180
+ Whether to draw the vertical line.
2181
+
2182
+ Other Parameters
2183
+ ----------------
2184
+ **lineprops
2185
+ `.Line2D` properties that control the appearance of the lines.
2186
+ See also `~.Axes.axhline`.
2187
+
2188
+ Examples
2189
+ --------
2190
+ See :doc:`/gallery/widgets/multicursor`.
2191
+ """
2192
+
2193
+ def __init__(self, *args, useblit=True, horizOn=False, vertOn=True,
2194
+ **lineprops):
2195
+ # Deprecation of canvas as the first attribute. When the deprecation expires:
2196
+ # - change the signature to __init__(self, axes, *, ...)
2197
+ # - delete the "Call signatures" block in the docstring
2198
+ # - delete this block
2199
+ kwargs = {k: lineprops.pop(k)
2200
+ for k in list(lineprops) if k in ("canvas", "axes")}
2201
+ params = _api.select_matching_signature(
2202
+ [lambda axes: locals(), lambda canvas, axes: locals()], *args, **kwargs)
2203
+ if "canvas" in params:
2204
+ _api.warn_deprecated(
2205
+ "3.11",
2206
+ message="The canvas parameter in MultiCursor is unused and deprecated "
2207
+ "since %(since)s. Please remove it and call MultiCursor(axes) "
2208
+ "instead of MultiCursor(canvas, axes). The latter will start raising "
2209
+ "an error in %(removal)s"
2210
+ )
2211
+ axes = params["axes"]
2212
+
2213
+ self.axes = axes
2214
+ self.horizOn = horizOn
2215
+ self.vertOn = vertOn
2216
+
2217
+ self._canvas_infos = {
2218
+ ax.get_figure(root=True).canvas:
2219
+ {"cids": [], "background": None} for ax in axes}
2220
+
2221
+ xmin, xmax = axes[-1].get_xlim()
2222
+ ymin, ymax = axes[-1].get_ylim()
2223
+ xmid = 0.5 * (xmin + xmax)
2224
+ ymid = 0.5 * (ymin + ymax)
2225
+
2226
+ self.visible = True
2227
+ self.useblit = (
2228
+ useblit
2229
+ and all(canvas.supports_blit for canvas in self._canvas_infos))
2230
+ # TODO: make dynamic
2231
+
2232
+ if self.useblit:
2233
+ lineprops['animated'] = True
2234
+
2235
+ self.vlines = [ax.axvline(xmid, visible=False, **lineprops)
2236
+ for ax in axes]
2237
+ self.hlines = [ax.axhline(ymid, visible=False, **lineprops)
2238
+ for ax in axes]
2239
+
2240
+ self.connect()
2241
+
2242
+ def connect(self):
2243
+ """Connect events."""
2244
+ for canvas, info in self._canvas_infos.items():
2245
+ info["cids"] = [
2246
+ canvas.mpl_connect('motion_notify_event', self.onmove),
2247
+ canvas.mpl_connect('draw_event', self.clear),
2248
+ ]
2249
+
2250
+ def disconnect(self):
2251
+ """Disconnect events."""
2252
+ for canvas, info in self._canvas_infos.items():
2253
+ for cid in info["cids"]:
2254
+ canvas.mpl_disconnect(cid)
2255
+ info["cids"].clear()
2256
+
2257
+ def clear(self, event):
2258
+ """Clear the cursor."""
2259
+ if self.ignore(event):
2260
+ return
2261
+ if self.useblit:
2262
+ for canvas, info in self._canvas_infos.items():
2263
+ # someone has switched the canvas on us! This happens if
2264
+ # `savefig` needs to save to a format the previous backend did
2265
+ # not support (e.g. saving a figure using an Agg based backend
2266
+ # saved to a vector format).
2267
+ if canvas is not canvas.figure.canvas:
2268
+ continue
2269
+ info["background"] = canvas.copy_from_bbox(canvas.figure.bbox)
2270
+
2271
+ def onmove(self, event):
2272
+ axs = [ax for ax in self.axes if ax.contains(event)[0]]
2273
+ if self.ignore(event) or not axs or not event.canvas.widgetlock.available(self):
2274
+ return
2275
+ ax = cbook._topmost_artist(axs)
2276
+ xdata, ydata = ((event.xdata, event.ydata) if event.inaxes is ax
2277
+ else ax.transData.inverted().transform((event.x, event.y)))
2278
+ for line in self.vlines:
2279
+ line.set_xdata((xdata, xdata))
2280
+ line.set_visible(self.visible and self.vertOn)
2281
+ for line in self.hlines:
2282
+ line.set_ydata((ydata, ydata))
2283
+ line.set_visible(self.visible and self.horizOn)
2284
+ if not (self.visible and (self.vertOn or self.horizOn)):
2285
+ return
2286
+ # Redraw.
2287
+ if self.useblit:
2288
+ for canvas, info in self._canvas_infos.items():
2289
+ if info["background"]:
2290
+ canvas.restore_region(info["background"])
2291
+ if self.vertOn:
2292
+ for ax, line in zip(self.axes, self.vlines):
2293
+ ax.draw_artist(line)
2294
+ if self.horizOn:
2295
+ for ax, line in zip(self.axes, self.hlines):
2296
+ ax.draw_artist(line)
2297
+ for canvas in self._canvas_infos:
2298
+ canvas.blit()
2299
+ else:
2300
+ for canvas in self._canvas_infos:
2301
+ canvas.draw_idle()
2302
+
2303
+
2304
+ class _SelectorWidget(AxesWidget):
2305
+ """
2306
+ The base class for selector widgets.
2307
+
2308
+ This class provides common functionality for selector widgets,
2309
+ such as handling mouse and keyboard events, managing state modifier keys, etc.
2310
+
2311
+ The class itself is private and may be changed or removed without prior warning.
2312
+ However, the public API it provides to subclasses is stable and considered
2313
+ public on the subclasses.
2314
+ """
2315
+
2316
+ def __init__(self, ax, onselect=None, useblit=False, button=None,
2317
+ state_modifier_keys=None, use_data_coordinates=False):
2318
+ super().__init__(ax)
2319
+
2320
+ self._visible = True
2321
+ if onselect is None:
2322
+ self.onselect = lambda *args: None
2323
+ else:
2324
+ self.onselect = onselect
2325
+ self._useblit = useblit
2326
+ self.connect_default_events()
2327
+
2328
+ self._state_modifier_keys = dict(move=' ', clear='escape',
2329
+ square='shift', center='control',
2330
+ rotate='r')
2331
+ self._state_modifier_keys.update(state_modifier_keys or {})
2332
+ self._use_data_coordinates = use_data_coordinates
2333
+
2334
+ if isinstance(button, Integral):
2335
+ self.validButtons = [button]
2336
+ else:
2337
+ self.validButtons = button
2338
+
2339
+ # Set to True when a selection is completed, otherwise is False
2340
+ self._selection_completed = False
2341
+
2342
+ # will save the data (position at mouseclick)
2343
+ self._eventpress = None
2344
+ # will save the data (pos. at mouserelease)
2345
+ self._eventrelease = None
2346
+ self._prev_event = None
2347
+ self._state = set()
2348
+
2349
+ @property
2350
+ def useblit(self):
2351
+ """Return whether blitting is used (requested and supported by canvas)."""
2352
+ return self._useblit and self.canvas.supports_blit
2353
+
2354
+ def set_active(self, active):
2355
+ super().set_active(active)
2356
+ if active:
2357
+ self.update_background(None)
2358
+
2359
+ def _get_animated_artists(self):
2360
+ """
2361
+ Convenience method to get all animated artists of the figure containing
2362
+ this widget, excluding those already present in self.artists.
2363
+ The returned tuple is not sorted by 'z_order': z_order sorting is
2364
+ valid only when considering all artists and not only a subset of all
2365
+ artists.
2366
+ """
2367
+ return tuple(a for ax_ in self.ax.get_figure().get_axes()
2368
+ for a in ax_.get_children()
2369
+ if a.get_animated() and a not in self.artists)
2370
+
2371
+ def update_background(self, event):
2372
+ """Force an update of the background."""
2373
+ # If you add a call to `ignore` here, you'll want to check edge case:
2374
+ # `release` can call a draw event even when `ignore` is True.
2375
+ if not self.useblit:
2376
+ return
2377
+ if self.canvas.is_saving():
2378
+ return # saving does not use blitting
2379
+ # Make sure that widget artists don't get accidentally included in the
2380
+ # background, by re-rendering the background if needed (and then
2381
+ # re-re-rendering the canvas with the visible widget artists).
2382
+ # We need to remove all artists which will be drawn when updating
2383
+ # the selector: if we have animated artists in the figure, it is safer
2384
+ # to redrawn by default, in case they have updated by the callback
2385
+ # zorder needs to be respected when redrawing
2386
+ artists = sorted(self.artists + self._get_animated_artists(),
2387
+ key=lambda a: a.get_zorder())
2388
+ needs_redraw = any(artist.get_visible() for artist in artists)
2389
+ with ExitStack() as stack:
2390
+ if needs_redraw:
2391
+ for artist in artists:
2392
+ stack.enter_context(artist._cm_set(visible=False))
2393
+ self.canvas.draw()
2394
+ self._save_blit_background(self.canvas.copy_from_bbox(self.ax.bbox))
2395
+ if needs_redraw:
2396
+ for artist in artists:
2397
+ self.ax.draw_artist(artist)
2398
+
2399
+ def connect_default_events(self):
2400
+ """Connect the major canvas events to methods."""
2401
+ self.connect_event('motion_notify_event', self.onmove)
2402
+ self.connect_event('button_press_event', self.press)
2403
+ self.connect_event('button_release_event', self.release)
2404
+ self.connect_event('draw_event', self.update_background)
2405
+ self.connect_event('key_press_event', self.on_key_press)
2406
+ self.connect_event('key_release_event', self.on_key_release)
2407
+ self.connect_event('scroll_event', self.on_scroll)
2408
+
2409
+ def ignore(self, event):
2410
+ # docstring inherited
2411
+ if super().ignore(event):
2412
+ return True
2413
+ if not self.ax.get_visible():
2414
+ return True
2415
+ # If canvas was locked
2416
+ if not self.canvas.widgetlock.available(self):
2417
+ return True
2418
+ if not hasattr(event, 'button'):
2419
+ event.button = None
2420
+ # Only do rectangle selection if event was triggered
2421
+ # with a desired button
2422
+ if (self.validButtons is not None
2423
+ and event.button not in self.validButtons):
2424
+ return True
2425
+ # If no button was pressed yet ignore the event if it was out of the Axes.
2426
+ if self._eventpress is None:
2427
+ return not self.ax.contains(event)[0]
2428
+ # If a button was pressed, check if the release-button is the same.
2429
+ if event.button == self._eventpress.button:
2430
+ return False
2431
+ # If a button was pressed, check if the release-button is the same.
2432
+ return (not self.ax.contains(event)[0] or
2433
+ event.button != self._eventpress.button)
2434
+
2435
+ def update(self):
2436
+ """Draw using blit() or draw_idle(), depending on ``self.useblit``."""
2437
+ if (not self.ax.get_visible() or
2438
+ self.ax.get_figure(root=True)._get_renderer() is None):
2439
+ return
2440
+ if self.useblit:
2441
+ background = self._load_blit_background()
2442
+ if background is not None:
2443
+ self.canvas.restore_region(background)
2444
+ else:
2445
+ self.update_background(None)
2446
+ # We need to draw all artists, which are not included in the
2447
+ # background, therefore we also draw self._get_animated_artists()
2448
+ # and we make sure that we respect z_order
2449
+ artists = sorted(self.artists + self._get_animated_artists(),
2450
+ key=lambda a: a.get_zorder())
2451
+ for artist in artists:
2452
+ self.ax.draw_artist(artist)
2453
+ self.canvas.blit(self.ax.bbox)
2454
+ else:
2455
+ self.canvas.draw_idle()
2456
+
2457
+ def _get_data(self, event):
2458
+ """Get the xdata and ydata for event, with limits."""
2459
+ if event.xdata is None:
2460
+ return None, None
2461
+ xdata = np.clip(event.xdata, *self.ax.get_xbound())
2462
+ ydata = np.clip(event.ydata, *self.ax.get_ybound())
2463
+ return xdata, ydata
2464
+
2465
+ def _clean_event(self, event):
2466
+ """
2467
+ Preprocess an event:
2468
+
2469
+ - Replace *event* by the previous event if *event* has no ``xdata``.
2470
+ - Get ``xdata`` and ``ydata`` from this widget's Axes, and clip them to the axes
2471
+ limits.
2472
+ - Update the previous event.
2473
+ """
2474
+ if event.xdata is None:
2475
+ event = self._prev_event
2476
+ else:
2477
+ event = copy.copy(event)
2478
+ event.xdata, event.ydata = self._get_data(event)
2479
+ self._prev_event = event
2480
+ return event
2481
+
2482
+ @_call_with_reparented_event
2483
+ def press(self, event):
2484
+ """Button press handler and validator."""
2485
+ if not self.ignore(event):
2486
+ event = self._clean_event(event)
2487
+ self._eventpress = event
2488
+ self._prev_event = event
2489
+ key = event.key or ''
2490
+ key = key.replace('ctrl', 'control')
2491
+ # move state is locked in on a button press
2492
+ if key == self._state_modifier_keys['move']:
2493
+ self._state.add('move')
2494
+ self._press(event)
2495
+ return True
2496
+ return False
2497
+
2498
+ def _press(self, event):
2499
+ """Button press event handler."""
2500
+
2501
+ @_call_with_reparented_event
2502
+ def release(self, event):
2503
+ """Button release event handler and validator."""
2504
+ if not self.ignore(event) and self._eventpress:
2505
+ event = self._clean_event(event)
2506
+ self._eventrelease = event
2507
+ self._release(event)
2508
+ self._eventpress = None
2509
+ self._eventrelease = None
2510
+ self._state.discard('move')
2511
+ return True
2512
+ return False
2513
+
2514
+ def _release(self, event):
2515
+ """Button release event handler."""
2516
+
2517
+ @_call_with_reparented_event
2518
+ def onmove(self, event):
2519
+ """Cursor move event handler and validator."""
2520
+ if not self.ignore(event) and self._eventpress:
2521
+ event = self._clean_event(event)
2522
+ self._onmove(event)
2523
+ return True
2524
+ return False
2525
+
2526
+ def _onmove(self, event):
2527
+ """Cursor move event handler."""
2528
+
2529
+ @_call_with_reparented_event
2530
+ def on_scroll(self, event):
2531
+ """Mouse scroll event handler and validator."""
2532
+ if not self.ignore(event):
2533
+ self._on_scroll(event)
2534
+
2535
+ def _on_scroll(self, event):
2536
+ """Mouse scroll event handler."""
2537
+
2538
+ @_call_with_reparented_event
2539
+ def on_key_press(self, event):
2540
+ """Key press event handler and validator for all selection widgets."""
2541
+ if self.active:
2542
+ key = event.key or ''
2543
+ key = key.replace('ctrl', 'control')
2544
+ if key == self._state_modifier_keys['clear']:
2545
+ self.clear()
2546
+ return
2547
+ for (state, modifier) in self._state_modifier_keys.items():
2548
+ if modifier in key.split('+'):
2549
+ # 'rotate' is changing _state on press and is not removed
2550
+ # from _state when releasing
2551
+ if state == 'rotate':
2552
+ if state in self._state:
2553
+ self._state.discard(state)
2554
+ else:
2555
+ self._state.add(state)
2556
+ else:
2557
+ self._state.add(state)
2558
+ self._on_key_press(event)
2559
+
2560
+ def _on_key_press(self, event):
2561
+ """Key press event handler - for widget-specific key press actions."""
2562
+
2563
+ @_call_with_reparented_event
2564
+ def on_key_release(self, event):
2565
+ """Key release event handler and validator."""
2566
+ if self.active:
2567
+ key = event.key or ''
2568
+ for (state, modifier) in self._state_modifier_keys.items():
2569
+ # 'rotate' is changing _state on press and is not removed
2570
+ # from _state when releasing
2571
+ if modifier in key.split('+') and state != 'rotate':
2572
+ self._state.discard(state)
2573
+ self._on_key_release(event)
2574
+
2575
+ def _on_key_release(self, event):
2576
+ """Key release event handler."""
2577
+
2578
+ def set_visible(self, visible):
2579
+ """Set the visibility of the selector artists."""
2580
+ self._visible = visible
2581
+ for artist in self.artists:
2582
+ artist.set_visible(visible)
2583
+
2584
+ def get_visible(self):
2585
+ """Get the visibility of the selector artists."""
2586
+ return self._visible
2587
+
2588
+ def clear(self):
2589
+ """Clear the selection and set the selector ready to make a new one."""
2590
+ self._clear_without_update()
2591
+ self.update()
2592
+
2593
+ def _clear_without_update(self):
2594
+ self._selection_completed = False
2595
+ self.set_visible(False)
2596
+
2597
+ @property
2598
+ def artists(self):
2599
+ """Tuple of the artists of the selector."""
2600
+ handles_artists = getattr(self, '_handles_artists', ())
2601
+ return (self._selection_artist,) + handles_artists
2602
+
2603
+ def set_props(self, **props):
2604
+ """
2605
+ Set the properties of the selector artist.
2606
+
2607
+ See the *props* argument in the selector docstring to know which properties are
2608
+ supported.
2609
+ """
2610
+ artist = self._selection_artist
2611
+ props = cbook.normalize_kwargs(props, artist)
2612
+ artist.set(**props)
2613
+ if self.useblit:
2614
+ self.update()
2615
+
2616
+ def set_handle_props(self, **handle_props):
2617
+ """
2618
+ Set the properties of the handles selector artist. See the
2619
+ *handle_props* argument in the selector docstring to know which
2620
+ properties are supported.
2621
+ """
2622
+ if not hasattr(self, '_handles_artists'):
2623
+ raise NotImplementedError("This selector doesn't have handles.")
2624
+
2625
+ artist = self._handles_artists[0]
2626
+ handle_props = cbook.normalize_kwargs(handle_props, artist)
2627
+ for handle in self._handles_artists:
2628
+ handle.set(**handle_props)
2629
+ if self.useblit:
2630
+ self.update()
2631
+ self._handle_props.update(handle_props)
2632
+
2633
+ def _validate_state(self, state):
2634
+ supported_state = [
2635
+ key for key, value in self._state_modifier_keys.items()
2636
+ if key != 'clear' and value != 'not-applicable'
2637
+ ]
2638
+ _api.check_in_list(supported_state, state=state)
2639
+
2640
+ def add_state(self, state):
2641
+ """
2642
+ Add a state to define the widget's behavior. See the
2643
+ *state_modifier_keys* parameter in the constructor of the concrete
2644
+ selector class for details.
2645
+
2646
+ Parameters
2647
+ ----------
2648
+ state : str
2649
+ Must be a supported state of the selector. See the
2650
+ *state_modifier_keys* parameter in the constructor of the concrete
2651
+ selector class for details.
2652
+
2653
+ Raises
2654
+ ------
2655
+ ValueError
2656
+ When the state is not supported by the selector.
2657
+
2658
+ """
2659
+ self._validate_state(state)
2660
+ self._state.add(state)
2661
+
2662
+ def remove_state(self, state):
2663
+ """
2664
+ Remove a state to define the widget's behavior. See the
2665
+ *state_modifier_keys* parameter in the constructor of the concrete
2666
+ selector class for details.
2667
+
2668
+ Parameters
2669
+ ----------
2670
+ state : str
2671
+ Must be a supported state of the selector. See the
2672
+ *state_modifier_keys* parameter in the constructor of the concrete
2673
+ selector class for details.
2674
+
2675
+ Raises
2676
+ ------
2677
+ ValueError
2678
+ When the state is not supported by the selector.
2679
+
2680
+ """
2681
+ self._validate_state(state)
2682
+ self._state.remove(state)
2683
+
2684
+
2685
+ class SpanSelector(_SelectorWidget):
2686
+ """
2687
+ Visually select a min/max range on a single axis and call a function with
2688
+ those values.
2689
+
2690
+ To guarantee that the selector remains responsive, keep a reference to it.
2691
+
2692
+ In order to turn off the SpanSelector, set ``span_selector.active`` to
2693
+ False. To turn it back on, set it to True.
2694
+
2695
+ Press and release events triggered at the same coordinates outside the
2696
+ selection will clear the selector, except when
2697
+ ``ignore_event_outside=True``.
2698
+
2699
+ Parameters
2700
+ ----------
2701
+ ax : `~matplotlib.axes.Axes`
2702
+
2703
+ onselect : callable with signature ``func(min: float, max: float)``
2704
+ A callback function that is called after a release event and the
2705
+ selection is created, changed or removed.
2706
+
2707
+ direction : {"horizontal", "vertical"}
2708
+ The direction along which to draw the span selector.
2709
+
2710
+ minspan : float, default: 0
2711
+ If selection is less than or equal to *minspan*, the selection is
2712
+ removed (when already existing) or cancelled.
2713
+
2714
+ useblit : bool, default: False
2715
+ If True, use the backend-dependent blitting features for faster
2716
+ canvas updates. See the tutorial :ref:`blitting` for details.
2717
+
2718
+ props : dict, default: {'facecolor': 'red', 'alpha': 0.5}
2719
+ Dictionary of `.Patch` properties.
2720
+
2721
+ onmove_callback : callable with signature ``func(min: float, max: float)``, optional
2722
+ Called on mouse move while the span is being selected.
2723
+
2724
+ interactive : bool, default: False
2725
+ Whether to draw a set of handles that allow interaction with the
2726
+ widget after it is drawn.
2727
+
2728
+ button : `.MouseButton` or list of `.MouseButton`, default: all buttons
2729
+ The mouse buttons which activate the span selector.
2730
+
2731
+ handle_props : dict, default: None
2732
+ Properties of the handle lines at the edges of the span. Only used
2733
+ when *interactive* is True. See `.Line2D` for valid properties.
2734
+
2735
+ grab_range : float, default: 10
2736
+ Distance in pixels within which the interactive tool handles can be activated.
2737
+
2738
+ state_modifier_keys : dict, optional
2739
+ Keyboard modifiers which affect the widget's behavior. Values
2740
+ amend the defaults, which are:
2741
+
2742
+ - "clear": Clear the current shape, default: "escape".
2743
+
2744
+ drag_from_anywhere : bool, default: False
2745
+ If `True`, the widget can be moved by clicking anywhere within its bounds.
2746
+
2747
+ ignore_event_outside : bool, default: False
2748
+ If `True`, the event triggered outside the span selector will be ignored.
2749
+
2750
+ snap_values : 1D array-like, optional
2751
+ Snap the selector edges to the given values.
2752
+
2753
+ Examples
2754
+ --------
2755
+ >>> import matplotlib.pyplot as plt
2756
+ >>> import matplotlib.widgets as mwidgets
2757
+ >>> fig, ax = plt.subplots()
2758
+ >>> ax.plot([1, 2, 3], [10, 50, 100])
2759
+ >>> def onselect(vmin, vmax):
2760
+ ... print(vmin, vmax)
2761
+ >>> span = mwidgets.SpanSelector(ax, onselect, 'horizontal',
2762
+ ... props=dict(facecolor='blue', alpha=0.5))
2763
+ >>> fig.show()
2764
+
2765
+ See also: :doc:`/gallery/widgets/span_selector`
2766
+ """
2767
+
2768
+ def __init__(self, ax, onselect, direction, *, minspan=0, useblit=False,
2769
+ props=None, onmove_callback=None, interactive=False,
2770
+ button=None, handle_props=None, grab_range=10,
2771
+ state_modifier_keys=None, drag_from_anywhere=False,
2772
+ ignore_event_outside=False, snap_values=None):
2773
+
2774
+ if state_modifier_keys is None:
2775
+ state_modifier_keys = dict(clear='escape',
2776
+ square='not-applicable',
2777
+ center='not-applicable',
2778
+ rotate='not-applicable')
2779
+ super().__init__(ax, onselect, useblit=useblit, button=button,
2780
+ state_modifier_keys=state_modifier_keys)
2781
+
2782
+ if props is None:
2783
+ props = dict(facecolor='red', alpha=0.5)
2784
+
2785
+ # Note: We set this based on the user setting during ínitialization,
2786
+ # not on the actual capability of blitting. But the value is
2787
+ # irrelevant if the backend does not support blitting, so that
2788
+ # we don't have to dynamically update this on the backend.
2789
+ # This relies on the current behavior that the request for
2790
+ # useblit is fixed during initialization and cannot be changed
2791
+ # afterwards.
2792
+ props['animated'] = self._useblit
2793
+
2794
+ self.direction = direction
2795
+ self._extents_on_press = None
2796
+ self.snap_values = snap_values
2797
+
2798
+ self.onmove_callback = onmove_callback
2799
+ self.minspan = minspan
2800
+
2801
+ self.grab_range = grab_range
2802
+ self._interactive = interactive
2803
+ self._edge_handles = None
2804
+ self.drag_from_anywhere = drag_from_anywhere
2805
+ self.ignore_event_outside = ignore_event_outside
2806
+
2807
+ self.new_axes(ax, _props=props, _init=True)
2808
+
2809
+ # Setup handles
2810
+ self._handle_props = {
2811
+ 'color': props.get('facecolor', 'r'),
2812
+ **cbook.normalize_kwargs(handle_props, Line2D)}
2813
+
2814
+ if self._interactive:
2815
+ self._edge_order = ['min', 'max']
2816
+ self._setup_edge_handles(self._handle_props)
2817
+
2818
+ self._active_handle = None
2819
+
2820
+ def new_axes(self, ax, *, _props=None, _init=False):
2821
+ """Set SpanSelector to operate on a new Axes."""
2822
+ reconnect = False
2823
+ if _init or self.canvas is not ax.get_figure(root=True).canvas:
2824
+ if self.canvas is not None:
2825
+ self.disconnect_events()
2826
+ reconnect = True
2827
+ self.ax = ax
2828
+ if reconnect:
2829
+ self.connect_default_events()
2830
+
2831
+ # Reset
2832
+ self._selection_completed = False
2833
+
2834
+ if self.direction == 'horizontal':
2835
+ trans = ax.get_xaxis_transform()
2836
+ w, h = 0, 1
2837
+ else:
2838
+ trans = ax.get_yaxis_transform()
2839
+ w, h = 1, 0
2840
+ rect_artist = Rectangle((0, 0), w, h, transform=trans, visible=False)
2841
+ if _props is not None:
2842
+ rect_artist.update(_props)
2843
+ elif self._selection_artist is not None:
2844
+ rect_artist.update_from(self._selection_artist)
2845
+
2846
+ self.ax.add_patch(rect_artist)
2847
+ self._selection_artist = rect_artist
2848
+
2849
+ def _setup_edge_handles(self, props):
2850
+ # Define initial position using the axis bounds to keep the same bounds
2851
+ if self.direction == 'horizontal':
2852
+ positions = self.ax.get_xbound()
2853
+ else:
2854
+ positions = self.ax.get_ybound()
2855
+ self._edge_handles = ToolLineHandles(self.ax, positions,
2856
+ direction=self.direction,
2857
+ line_props=props,
2858
+ useblit=self._useblit)
2859
+
2860
+ @property
2861
+ def _handles_artists(self):
2862
+ if self._edge_handles is not None:
2863
+ return self._edge_handles.artists
2864
+ else:
2865
+ return ()
2866
+
2867
+ def _set_span_cursor(self, *, enabled):
2868
+ """Update the canvas cursor based on direction of the selector."""
2869
+ if enabled:
2870
+ cursor = (backend_tools.Cursors.RESIZE_HORIZONTAL
2871
+ if self.direction == 'horizontal' else
2872
+ backend_tools.Cursors.RESIZE_VERTICAL)
2873
+ else:
2874
+ cursor = backend_tools.Cursors.POINTER
2875
+
2876
+ self._set_cursor(cursor)
2877
+
2878
+ def connect_default_events(self):
2879
+ # docstring inherited
2880
+ super().connect_default_events()
2881
+ if getattr(self, '_interactive', False):
2882
+ self.connect_event('motion_notify_event', self._hover)
2883
+
2884
+ def _press(self, event):
2885
+ """Button press event handler."""
2886
+ self._set_span_cursor(enabled=True)
2887
+ if self._interactive and self._selection_artist.get_visible():
2888
+ self._set_active_handle(event)
2889
+ else:
2890
+ self._active_handle = None
2891
+
2892
+ if self._active_handle is None or not self._interactive:
2893
+ # Clear previous rectangle before drawing new rectangle.
2894
+ self.update()
2895
+
2896
+ v = event.xdata if self.direction == 'horizontal' else event.ydata
2897
+
2898
+ if self._active_handle is None and not self.ignore_event_outside:
2899
+ # when the press event outside the span, we initially set the
2900
+ # visibility to False and extents to (v, v)
2901
+ # update will be called when setting the extents
2902
+ self._visible = False
2903
+ self._set_extents((v, v))
2904
+ # We need to set the visibility back, so the span selector will be
2905
+ # drawn when necessary (span width > 0)
2906
+ self._visible = True
2907
+ else:
2908
+ self.set_visible(True)
2909
+
2910
+ return False
2911
+
2912
+ @property
2913
+ def direction(self):
2914
+ """Direction of the span selector: 'vertical' or 'horizontal'."""
2915
+ return self._direction
2916
+
2917
+ @direction.setter
2918
+ def direction(self, direction):
2919
+ """Set the direction of the span selector."""
2920
+ _api.check_in_list(['horizontal', 'vertical'], direction=direction)
2921
+ if hasattr(self, '_direction') and direction != self._direction:
2922
+ # remove previous artists
2923
+ self._selection_artist.remove()
2924
+ if self._interactive:
2925
+ self._edge_handles.remove()
2926
+ self._direction = direction
2927
+ self.new_axes(self.ax)
2928
+ if self._interactive:
2929
+ self._setup_edge_handles(self._handle_props)
2930
+ else:
2931
+ self._direction = direction
2932
+
2933
+ @_call_with_reparented_event
2934
+ def _release(self, event):
2935
+ """Button release event handler."""
2936
+ self._set_span_cursor(enabled=False)
2937
+
2938
+ if not self._interactive:
2939
+ self._selection_artist.set_visible(False)
2940
+
2941
+ if (self._active_handle is None and self._selection_completed and
2942
+ self.ignore_event_outside):
2943
+ return
2944
+
2945
+ vmin, vmax = self.extents
2946
+ span = vmax - vmin
2947
+
2948
+ if span <= self.minspan:
2949
+ # Remove span and set self._selection_completed = False
2950
+ self.set_visible(False)
2951
+ if self._selection_completed:
2952
+ # Call onselect, only when the span is already existing
2953
+ self.onselect(vmin, vmax)
2954
+ self._selection_completed = False
2955
+ else:
2956
+ self.onselect(vmin, vmax)
2957
+ self._selection_completed = True
2958
+
2959
+ self.update()
2960
+
2961
+ self._active_handle = None
2962
+
2963
+ return False
2964
+
2965
+ @_call_with_reparented_event
2966
+ def _hover(self, event):
2967
+ """Update the canvas cursor if it's over a handle."""
2968
+ if self.ignore(event):
2969
+ return
2970
+
2971
+ if self._active_handle is not None or not self._selection_completed:
2972
+ # Do nothing if button is pressed and a handle is active, which may
2973
+ # occur with drag_from_anywhere=True.
2974
+ # Do nothing if selection is not completed, which occurs when
2975
+ # a selector has been cleared
2976
+ return
2977
+
2978
+ _, e_dist = self._edge_handles.closest(event.x, event.y)
2979
+ self._set_span_cursor(enabled=e_dist <= self.grab_range)
2980
+
2981
+ def _onmove(self, event):
2982
+ """Motion notify event handler."""
2983
+
2984
+ if self.direction == 'horizontal':
2985
+ v = event.xdata
2986
+ vpress = self._eventpress.xdata
2987
+ else:
2988
+ v = event.ydata
2989
+ vpress = self._eventpress.ydata
2990
+
2991
+ # move existing span
2992
+ # When "dragging from anywhere", `self._active_handle` is set to 'C'
2993
+ # (match notation used in the RectangleSelector)
2994
+ if self._active_handle == 'C' and self._extents_on_press is not None:
2995
+ vmin, vmax = self._extents_on_press
2996
+ dv = v - vpress
2997
+ vmin += dv
2998
+ vmax += dv
2999
+
3000
+ # resize an existing shape
3001
+ elif self._active_handle and self._active_handle != 'C':
3002
+ vmin, vmax = self._extents_on_press
3003
+ if self._active_handle == 'min':
3004
+ vmin = v
3005
+ else:
3006
+ vmax = v
3007
+ # new shape
3008
+ else:
3009
+ # Don't create a new span if there is already one when
3010
+ # ignore_event_outside=True
3011
+ if self.ignore_event_outside and self._selection_completed:
3012
+ return
3013
+ vmin, vmax = vpress, v
3014
+ if vmin > vmax:
3015
+ vmin, vmax = vmax, vmin
3016
+
3017
+ self._set_extents((vmin, vmax))
3018
+
3019
+ if self.onmove_callback is not None:
3020
+ self.onmove_callback(vmin, vmax)
3021
+
3022
+ return False
3023
+
3024
+ def _draw_shape(self, vmin, vmax):
3025
+ if vmin > vmax:
3026
+ vmin, vmax = vmax, vmin
3027
+ if self.direction == 'horizontal':
3028
+ self._selection_artist.set_x(vmin)
3029
+ self._selection_artist.set_width(vmax - vmin)
3030
+ else:
3031
+ self._selection_artist.set_y(vmin)
3032
+ self._selection_artist.set_height(vmax - vmin)
3033
+
3034
+ def _set_active_handle(self, event):
3035
+ """Set active handle based on the location of the mouse event."""
3036
+ # Note: event.xdata/ydata in data coordinates, event.x/y in pixels
3037
+ e_idx, e_dist = self._edge_handles.closest(event.x, event.y)
3038
+
3039
+ # Prioritise center handle over other handles
3040
+ # Use 'C' to match the notation used in the RectangleSelector
3041
+ if 'move' in self._state:
3042
+ self._active_handle = 'C'
3043
+ elif e_dist > self.grab_range:
3044
+ # Not close to any handles
3045
+ self._active_handle = None
3046
+ if self.drag_from_anywhere and self._contains(event):
3047
+ # Check if we've clicked inside the region
3048
+ self._active_handle = 'C'
3049
+ self._extents_on_press = self.extents
3050
+ else:
3051
+ self._active_handle = None
3052
+ return
3053
+ else:
3054
+ # Closest to an edge handle
3055
+ self._active_handle = self._edge_order[e_idx]
3056
+
3057
+ # Save coordinates of rectangle at the start of handle movement.
3058
+ self._extents_on_press = self.extents
3059
+
3060
+ def _contains(self, event):
3061
+ """Return True if event is within the patch."""
3062
+ return self._selection_artist.contains(event, radius=0)[0]
3063
+
3064
+ @staticmethod
3065
+ def _snap(values, snap_values):
3066
+ """Snap values to a given array values (snap_values)."""
3067
+ # take into account machine precision
3068
+ eps = np.min(np.abs(np.diff(snap_values))) * 1e-12
3069
+ return tuple(
3070
+ snap_values[np.abs(snap_values - v + np.sign(v) * eps).argmin()]
3071
+ for v in values)
3072
+
3073
+ @property
3074
+ def extents(self):
3075
+ """
3076
+ (float, float)
3077
+ The values, in data coordinates, for the start and end points of the current
3078
+ selection. If there is no selection then the start and end values will be
3079
+ the same.
3080
+ """
3081
+ if self.direction == 'horizontal':
3082
+ vmin = self._selection_artist.get_x()
3083
+ vmax = vmin + self._selection_artist.get_width()
3084
+ else:
3085
+ vmin = self._selection_artist.get_y()
3086
+ vmax = vmin + self._selection_artist.get_height()
3087
+ return vmin, vmax
3088
+
3089
+ @extents.setter
3090
+ def extents(self, extents):
3091
+ self._set_extents(extents)
3092
+ self._selection_completed = True
3093
+
3094
+ def _set_extents(self, extents):
3095
+ # Update displayed shape
3096
+ if self.snap_values is not None:
3097
+ extents = tuple(self._snap(extents, self.snap_values))
3098
+ self._draw_shape(*extents)
3099
+ if self._interactive:
3100
+ # Update displayed handles
3101
+ self._edge_handles.set_data(self.extents)
3102
+ self.set_visible(self._visible)
3103
+ self.update()
3104
+
3105
+
3106
+ class ToolLineHandles:
3107
+ """
3108
+ Control handles for canvas tools.
3109
+
3110
+ Parameters
3111
+ ----------
3112
+ ax : `~matplotlib.axes.Axes`
3113
+ Matplotlib Axes where tool handles are displayed.
3114
+ positions : 1D array
3115
+ Positions of handles in data coordinates.
3116
+ direction : {"horizontal", "vertical"}
3117
+ Direction of handles, either 'vertical' or 'horizontal'
3118
+ line_props : dict, optional
3119
+ Additional line properties. See `.Line2D`.
3120
+ useblit : bool, default: True
3121
+ Whether to use blitting for faster drawing (if supported by the
3122
+ backend). See the tutorial :ref:`blitting`
3123
+ for details.
3124
+ """
3125
+
3126
+ def __init__(self, ax, positions, direction, *, line_props=None,
3127
+ useblit=True):
3128
+ self.ax = ax
3129
+
3130
+ _api.check_in_list(['horizontal', 'vertical'], direction=direction)
3131
+ self._direction = direction
3132
+
3133
+ line_props = {
3134
+ **(line_props if line_props is not None else {}),
3135
+ 'visible': False,
3136
+ 'animated': useblit,
3137
+ }
3138
+
3139
+ line_fun = ax.axvline if self.direction == 'horizontal' else ax.axhline
3140
+
3141
+ self._artists = [line_fun(p, **line_props) for p in positions]
3142
+
3143
+ @property
3144
+ def artists(self):
3145
+ return tuple(self._artists)
3146
+
3147
+ @property
3148
+ def positions(self):
3149
+ """Positions of the handle in data coordinates."""
3150
+ method = 'get_xdata' if self.direction == 'horizontal' else 'get_ydata'
3151
+ return [getattr(line, method)()[0] for line in self.artists]
3152
+
3153
+ @property
3154
+ def direction(self):
3155
+ """Direction of the handle: 'vertical' or 'horizontal'."""
3156
+ return self._direction
3157
+
3158
+ def set_data(self, positions):
3159
+ """
3160
+ Set x- or y-positions of handles, depending on if the lines are
3161
+ vertical or horizontal.
3162
+
3163
+ Parameters
3164
+ ----------
3165
+ positions : tuple of length 2
3166
+ Set the positions of the handle in data coordinates
3167
+ """
3168
+ method = 'set_xdata' if self.direction == 'horizontal' else 'set_ydata'
3169
+ for line, p in zip(self.artists, positions):
3170
+ getattr(line, method)([p, p])
3171
+
3172
+ def set_visible(self, value):
3173
+ """Set the visibility state of the handles artist."""
3174
+ for artist in self.artists:
3175
+ artist.set_visible(value)
3176
+
3177
+ def set_animated(self, value):
3178
+ """Set the animated state of the handles artist."""
3179
+ for artist in self.artists:
3180
+ artist.set_animated(value)
3181
+
3182
+ def remove(self):
3183
+ """Remove the handles artist from the figure."""
3184
+ for artist in self._artists:
3185
+ artist.remove()
3186
+
3187
+ def closest(self, x, y):
3188
+ """
3189
+ Return index and pixel distance to closest handle.
3190
+
3191
+ Parameters
3192
+ ----------
3193
+ x, y : float
3194
+ x, y position from which the distance will be calculated to
3195
+ determinate the closest handle
3196
+
3197
+ Returns
3198
+ -------
3199
+ index, distance : index of the handle and its distance from
3200
+ position x, y
3201
+ """
3202
+ if self.direction == 'horizontal':
3203
+ p_pts = np.array([
3204
+ self.ax.transData.transform((p, 0))[0] for p in self.positions
3205
+ ])
3206
+ dist = abs(p_pts - x)
3207
+ else:
3208
+ p_pts = np.array([
3209
+ self.ax.transData.transform((0, p))[1] for p in self.positions
3210
+ ])
3211
+ dist = abs(p_pts - y)
3212
+ index = np.argmin(dist)
3213
+ return index, dist[index]
3214
+
3215
+
3216
+ class ToolHandles:
3217
+ """
3218
+ Control handles for canvas tools.
3219
+
3220
+ Parameters
3221
+ ----------
3222
+ ax : `~matplotlib.axes.Axes`
3223
+ Matplotlib Axes where tool handles are displayed.
3224
+ x, y : 1D arrays
3225
+ Coordinates of control handles.
3226
+ marker : str, default: 'o'
3227
+ Shape of marker used to display handle. See `~.pyplot.plot`.
3228
+ marker_props : dict, optional
3229
+ Additional marker properties. See `.Line2D`.
3230
+ useblit : bool, default: True
3231
+ Whether to use blitting for faster drawing (if supported by the
3232
+ backend). See the tutorial :ref:`blitting`
3233
+ for details.
3234
+ """
3235
+
3236
+ def __init__(self, ax, x, y, *, marker='o', marker_props=None, useblit=True):
3237
+ self.ax = ax
3238
+ props = {'marker': marker, 'markersize': 7, 'markerfacecolor': 'w',
3239
+ 'linestyle': 'none', 'alpha': 0.5, 'visible': False,
3240
+ 'label': '_nolegend_',
3241
+ **cbook.normalize_kwargs(marker_props, Line2D)}
3242
+ self._markers = Line2D(x, y, animated=useblit, **props)
3243
+ self.ax.add_line(self._markers)
3244
+
3245
+ @property
3246
+ def x(self):
3247
+ return self._markers.get_xdata()
3248
+
3249
+ @property
3250
+ def y(self):
3251
+ return self._markers.get_ydata()
3252
+
3253
+ @property
3254
+ def artists(self):
3255
+ return (self._markers, )
3256
+
3257
+ def set_data(self, pts, y=None):
3258
+ """Set x and y positions of handles."""
3259
+ if y is not None:
3260
+ x = pts
3261
+ pts = np.array([x, y])
3262
+ self._markers.set_data(pts)
3263
+
3264
+ def set_visible(self, val):
3265
+ self._markers.set_visible(val)
3266
+
3267
+ def set_animated(self, val):
3268
+ self._markers.set_animated(val)
3269
+
3270
+ def closest(self, x, y):
3271
+ """Return index and pixel distance to closest index."""
3272
+ pts = np.column_stack([self.x, self.y])
3273
+ # Transform data coordinates to pixel coordinates.
3274
+ pts = self.ax.transData.transform(pts)
3275
+ diff = pts - [x, y]
3276
+ dist = np.hypot(*diff.T)
3277
+ min_index = np.argmin(dist)
3278
+ return min_index, dist[min_index]
3279
+
3280
+
3281
+ _RECTANGLESELECTOR_PARAMETERS_DOCSTRING = \
3282
+ r"""
3283
+ Parameters
3284
+ ----------
3285
+ ax : `~matplotlib.axes.Axes`
3286
+ The parent Axes for the widget.
3287
+
3288
+ onselect : function, optional
3289
+ A callback function that is called after a release event and the
3290
+ selection is created, changed or removed.
3291
+ It must have the signature::
3292
+
3293
+ def onselect(eclick: MouseEvent, erelease: MouseEvent)
3294
+
3295
+ where *eclick* and *erelease* are the mouse click and release
3296
+ `.MouseEvent`\s that start and complete the selection.
3297
+
3298
+ minspanx : float, default: 0
3299
+ Selections with an x-span less than or equal to *minspanx* are removed
3300
+ (when already existing) or cancelled.
3301
+
3302
+ minspany : float, default: 0
3303
+ Selections with a y-span less than or equal to *minspanx* are removed
3304
+ (when already existing) or cancelled.
3305
+
3306
+ useblit : bool, default: False
3307
+ Whether to use blitting for faster drawing (if supported by the
3308
+ backend). See the tutorial :ref:`blitting`
3309
+ for details.
3310
+
3311
+ props : dict, optional
3312
+ Properties with which the __ARTIST_NAME__ is drawn. See
3313
+ `.Patch` for valid properties.
3314
+ Default:
3315
+
3316
+ ``dict(facecolor='red', edgecolor='black', alpha=0.2, fill=True)``
3317
+
3318
+ spancoords : {"data", "pixels"}, default: "data"
3319
+ Whether to interpret *minspanx* and *minspany* in data or in pixel
3320
+ coordinates.
3321
+
3322
+ button : `.MouseButton`, list of `.MouseButton`, default: all buttons
3323
+ Button(s) that trigger rectangle selection.
3324
+
3325
+ grab_range : float, default: 10
3326
+ Distance in pixels within which the interactive tool handles can be
3327
+ activated.
3328
+
3329
+ handle_props : dict, optional
3330
+ Properties with which the interactive handles (marker artists) are
3331
+ drawn. See the marker arguments in `.Line2D` for valid
3332
+ properties. Default values are defined in ``mpl.rcParams`` except for
3333
+ the default value of ``markeredgecolor`` which will be the same as the
3334
+ ``edgecolor`` property in *props*.
3335
+
3336
+ interactive : bool, default: False
3337
+ Whether to draw a set of handles that allow interaction with the
3338
+ widget after it is drawn.
3339
+
3340
+ state_modifier_keys : dict, optional
3341
+ Keyboard modifiers which affect the widget's behavior. Values
3342
+ amend the defaults, which are:
3343
+
3344
+ - "move": Move the existing shape, default: no modifier.
3345
+ - "clear": Clear the current shape, default: "escape".
3346
+ - "square": Make the shape square, default: "shift".
3347
+ - "center": change the shape around its center, default: "ctrl".
3348
+ - "rotate": Rotate the shape around its center between -45° and 45°,
3349
+ default: "r".
3350
+
3351
+ "square" and "center" can be combined. The square shape can be defined
3352
+ in data or display coordinates as determined by the
3353
+ ``use_data_coordinates`` argument specified when creating the selector.
3354
+
3355
+ drag_from_anywhere : bool, default: False
3356
+ If `True`, the widget can be moved by clicking anywhere within
3357
+ its bounds.
3358
+
3359
+ ignore_event_outside : bool, default: False
3360
+ If `True`, the event triggered outside the span selector will be
3361
+ ignored.
3362
+
3363
+ use_data_coordinates : bool, default: False
3364
+ If `True`, the "square" shape of the selector is defined in
3365
+ data coordinates instead of display coordinates.
3366
+ """
3367
+
3368
+
3369
+ class _RectangleSelectorAction(enum.Enum):
3370
+ ROTATE = enum.auto()
3371
+ MOVE = enum.auto()
3372
+ RESIZE = enum.auto()
3373
+ CREATE = enum.auto()
3374
+
3375
+
3376
+ @_docstring.Substitution(_RECTANGLESELECTOR_PARAMETERS_DOCSTRING.replace(
3377
+ '__ARTIST_NAME__', 'rectangle'))
3378
+ class RectangleSelector(_SelectorWidget):
3379
+ """
3380
+ Select a rectangular region of an Axes.
3381
+
3382
+ For the cursor to remain responsive you must keep a reference to it.
3383
+
3384
+ Press and release events triggered at the same coordinates outside the
3385
+ selection will clear the selector, except when
3386
+ ``ignore_event_outside=True``.
3387
+
3388
+ %s
3389
+
3390
+ Examples
3391
+ --------
3392
+ >>> import matplotlib.pyplot as plt
3393
+ >>> import matplotlib.widgets as mwidgets
3394
+ >>> fig, ax = plt.subplots()
3395
+ >>> ax.plot([1, 2, 3], [10, 50, 100])
3396
+ >>> def onselect(eclick, erelease):
3397
+ ... print(eclick.xdata, eclick.ydata)
3398
+ ... print(erelease.xdata, erelease.ydata)
3399
+ >>> props = dict(facecolor='blue', alpha=0.5)
3400
+ >>> rect = mwidgets.RectangleSelector(ax, onselect, interactive=True,
3401
+ ... props=props)
3402
+ >>> fig.show()
3403
+ >>> rect.add_state('square')
3404
+
3405
+ See also: :doc:`/gallery/widgets/rectangle_selector`
3406
+ """
3407
+
3408
+ def __init__(self, ax, onselect=None, *, minspanx=0,
3409
+ minspany=0, useblit=False,
3410
+ props=None, spancoords='data', button=None, grab_range=10,
3411
+ handle_props=None, interactive=False,
3412
+ state_modifier_keys=None, drag_from_anywhere=False,
3413
+ ignore_event_outside=False, use_data_coordinates=False):
3414
+ super().__init__(ax, onselect, useblit=useblit, button=button,
3415
+ state_modifier_keys=state_modifier_keys,
3416
+ use_data_coordinates=use_data_coordinates)
3417
+
3418
+ self._interactive = interactive
3419
+ self.drag_from_anywhere = drag_from_anywhere
3420
+ self.ignore_event_outside = ignore_event_outside
3421
+ self._rotation = 0.0
3422
+ self._aspect_ratio_correction = 1.0
3423
+
3424
+ # State to allow the option of an interactive selector that can't be
3425
+ # interactively drawn. This is used in PolygonSelector as an
3426
+ # interactive bounding box to allow the polygon to be easily resized
3427
+ self._allow_creation = True
3428
+
3429
+ if props is None:
3430
+ props = dict(facecolor='red', edgecolor='black',
3431
+ alpha=0.2, fill=True)
3432
+ props = {**props, 'animated': self._useblit}
3433
+ self._visible = props.pop('visible', self._visible)
3434
+ to_draw = self._init_shape(**props)
3435
+ self.ax.add_patch(to_draw)
3436
+
3437
+ self._selection_artist = to_draw
3438
+ self._set_aspect_ratio_correction()
3439
+
3440
+ self.minspanx = minspanx
3441
+ self.minspany = minspany
3442
+
3443
+ _api.check_in_list(['data', 'pixels'], spancoords=spancoords)
3444
+ self.spancoords = spancoords
3445
+
3446
+ self.grab_range = grab_range
3447
+
3448
+ if self._interactive:
3449
+ self._handle_props = {
3450
+ 'markeredgecolor': (props or {}).get('edgecolor', 'black'),
3451
+ **cbook.normalize_kwargs(handle_props, Line2D)}
3452
+
3453
+ self._corner_order = ['SW', 'SE', 'NE', 'NW']
3454
+ xc, yc = self.corners
3455
+ self._corner_handles = ToolHandles(self.ax, xc, yc,
3456
+ marker_props=self._handle_props,
3457
+ useblit=self._useblit)
3458
+
3459
+ self._edge_order = ['W', 'S', 'E', 'N']
3460
+ xe, ye = self.edge_centers
3461
+ self._edge_handles = ToolHandles(self.ax, xe, ye, marker='s',
3462
+ marker_props=self._handle_props,
3463
+ useblit=self._useblit)
3464
+
3465
+ xc, yc = self.center
3466
+ self._center_handle = ToolHandles(self.ax, [xc], [yc], marker='s',
3467
+ marker_props=self._handle_props,
3468
+ useblit=self._useblit)
3469
+
3470
+ self._active_handle = None
3471
+
3472
+ self._extents_on_press = None
3473
+
3474
+ @property
3475
+ def _handles_artists(self):
3476
+ return (*self._center_handle.artists, *self._corner_handles.artists,
3477
+ *self._edge_handles.artists)
3478
+
3479
+ def _init_shape(self, **props):
3480
+ return Rectangle((0, 0), 0, 1, visible=False,
3481
+ rotation_point='center', **props)
3482
+
3483
+ def _press(self, event):
3484
+ """Button press event handler."""
3485
+ # make the drawn box/line visible get the click-coordinates, button, ...
3486
+ if self._interactive and self._selection_artist.get_visible():
3487
+ self._set_active_handle(event)
3488
+ else:
3489
+ self._active_handle = None
3490
+
3491
+ if ((self._active_handle is None or not self._interactive) and
3492
+ self._allow_creation):
3493
+ # Clear previous rectangle before drawing new rectangle.
3494
+ self.update()
3495
+
3496
+ if (self._active_handle is None and not self.ignore_event_outside and
3497
+ self._allow_creation):
3498
+ self._visible = False
3499
+ self.extents = event.xdata, event.xdata, event.ydata, event.ydata
3500
+ self._visible = True
3501
+ else:
3502
+ self.set_visible(True)
3503
+
3504
+ self._extents_on_press = self.extents
3505
+ self._rotation_on_press = self._rotation
3506
+ self._set_aspect_ratio_correction()
3507
+
3508
+ match self._get_action():
3509
+ case _RectangleSelectorAction.ROTATE:
3510
+ # TODO: set to a rotate cursor if possible?
3511
+ pass
3512
+ case _RectangleSelectorAction.MOVE:
3513
+ self._set_cursor(backend_tools.cursors.MOVE)
3514
+ case _RectangleSelectorAction.RESIZE:
3515
+ # TODO: set to a resize cursor if possible?
3516
+ pass
3517
+ case _RectangleSelectorAction.CREATE:
3518
+ self._set_cursor(backend_tools.cursors.SELECT_REGION)
3519
+
3520
+ return False
3521
+
3522
+ @_call_with_reparented_event
3523
+ def _release(self, event):
3524
+ """Button release event handler."""
3525
+ self._set_cursor(backend_tools.Cursors.POINTER)
3526
+ if not self._interactive:
3527
+ self._selection_artist.set_visible(False)
3528
+
3529
+ if (self._active_handle is None and self._selection_completed and
3530
+ self.ignore_event_outside):
3531
+ return
3532
+
3533
+ # update the eventpress and eventrelease with the resulting extents
3534
+ x0, x1, y0, y1 = self.extents
3535
+ self._eventpress.xdata = x0
3536
+ self._eventpress.ydata = y0
3537
+ xy0 = self.ax.transData.transform([x0, y0])
3538
+ self._eventpress.x, self._eventpress.y = xy0
3539
+
3540
+ self._eventrelease.xdata = x1
3541
+ self._eventrelease.ydata = y1
3542
+ xy1 = self.ax.transData.transform([x1, y1])
3543
+ self._eventrelease.x, self._eventrelease.y = xy1
3544
+
3545
+ # calculate dimensions of box or line
3546
+ if self.spancoords == 'data':
3547
+ spanx = abs(self._eventpress.xdata - self._eventrelease.xdata)
3548
+ spany = abs(self._eventpress.ydata - self._eventrelease.ydata)
3549
+ elif self.spancoords == 'pixels':
3550
+ spanx = abs(self._eventpress.x - self._eventrelease.x)
3551
+ spany = abs(self._eventpress.y - self._eventrelease.y)
3552
+ else:
3553
+ _api.check_in_list(['data', 'pixels'],
3554
+ spancoords=self.spancoords)
3555
+ # check if drawn distance (if it exists) is not too small in
3556
+ # either x or y-direction
3557
+ if spanx <= self.minspanx or spany <= self.minspany:
3558
+ if self._selection_completed:
3559
+ # Call onselect, only when the selection is already existing
3560
+ self.onselect(self._eventpress, self._eventrelease)
3561
+ self._clear_without_update()
3562
+ else:
3563
+ self.onselect(self._eventpress, self._eventrelease)
3564
+ self._selection_completed = True
3565
+
3566
+ self.update()
3567
+ self._active_handle = None
3568
+ self._extents_on_press = None
3569
+ return False
3570
+
3571
+ def _get_action(self):
3572
+ state = self._state
3573
+ if 'rotate' in state and self._active_handle in self._corner_order:
3574
+ return _RectangleSelectorAction.ROTATE
3575
+ elif self._active_handle == 'C':
3576
+ return _RectangleSelectorAction.MOVE
3577
+ elif self._active_handle:
3578
+ return _RectangleSelectorAction.RESIZE
3579
+
3580
+ return _RectangleSelectorAction.CREATE
3581
+
3582
+
3583
+ def _onmove(self, event):
3584
+ """
3585
+ Motion notify event handler.
3586
+
3587
+ This can do one of four things:
3588
+ - Translate
3589
+ - Rotate
3590
+ - Re-size
3591
+ - Continue the creation of a new shape
3592
+ """
3593
+ eventpress = self._eventpress
3594
+ # The calculations are done for rotation at zero: we apply inverse
3595
+ # transformation to events except when we rotate and move
3596
+ state = self._state
3597
+ action = self._get_action()
3598
+
3599
+ xdata, ydata = event.xdata, event.ydata
3600
+ if action == _RectangleSelectorAction.RESIZE:
3601
+ inv_tr = self._get_rotation_transform().inverted()
3602
+ xdata, ydata = inv_tr.transform([xdata, ydata])
3603
+ eventpress.xdata, eventpress.ydata = inv_tr.transform(
3604
+ (eventpress.xdata, eventpress.ydata))
3605
+
3606
+ dx = xdata - eventpress.xdata
3607
+ dy = ydata - eventpress.ydata
3608
+ # refmax is used when moving the corner handle with the square state
3609
+ # and is the maximum between refx and refy
3610
+ refmax = None
3611
+ if self._use_data_coordinates:
3612
+ refx, refy = dx, dy
3613
+ else:
3614
+ # Get dx/dy in display coordinates
3615
+ refx = event.x - eventpress.x
3616
+ refy = event.y - eventpress.y
3617
+
3618
+ x0, x1, y0, y1 = self._extents_on_press
3619
+ # rotate an existing shape
3620
+ if action == _RectangleSelectorAction.ROTATE:
3621
+ # calculate angle abc
3622
+ a = (eventpress.xdata, eventpress.ydata)
3623
+ b = self.center
3624
+ c = (xdata, ydata)
3625
+ angle = (np.arctan2(c[1]-b[1], c[0]-b[0]) -
3626
+ np.arctan2(a[1]-b[1], a[0]-b[0]))
3627
+ self.rotation = np.rad2deg(self._rotation_on_press + angle)
3628
+
3629
+ elif action == _RectangleSelectorAction.RESIZE:
3630
+ size_on_press = [x1 - x0, y1 - y0]
3631
+ center = (x0 + size_on_press[0] / 2, y0 + size_on_press[1] / 2)
3632
+
3633
+ # Keeping the center fixed
3634
+ if 'center' in state:
3635
+ # hh, hw are half-height and half-width
3636
+ if 'square' in state:
3637
+ # when using a corner, find which reference to use
3638
+ if self._active_handle in self._corner_order:
3639
+ refmax = max(refx, refy, key=abs)
3640
+ if self._active_handle in ['E', 'W'] or refmax == refx:
3641
+ hw = xdata - center[0]
3642
+ hh = hw / self._aspect_ratio_correction
3643
+ else:
3644
+ hh = ydata - center[1]
3645
+ hw = hh * self._aspect_ratio_correction
3646
+ else:
3647
+ hw = size_on_press[0] / 2
3648
+ hh = size_on_press[1] / 2
3649
+ # cancel changes in perpendicular direction
3650
+ if self._active_handle in ['E', 'W'] + self._corner_order:
3651
+ hw = abs(xdata - center[0])
3652
+ if self._active_handle in ['N', 'S'] + self._corner_order:
3653
+ hh = abs(ydata - center[1])
3654
+
3655
+ x0, x1, y0, y1 = (center[0] - hw, center[0] + hw,
3656
+ center[1] - hh, center[1] + hh)
3657
+
3658
+ else:
3659
+ # change sign of relative changes to simplify calculation
3660
+ # Switch variables so that x1 and/or y1 are updated on move
3661
+ if 'W' in self._active_handle:
3662
+ x0 = x1
3663
+ if 'S' in self._active_handle:
3664
+ y0 = y1
3665
+ if self._active_handle in ['E', 'W'] + self._corner_order:
3666
+ x1 = xdata
3667
+ if self._active_handle in ['N', 'S'] + self._corner_order:
3668
+ y1 = ydata
3669
+ if 'square' in state:
3670
+ # when using a corner, find which reference to use
3671
+ if self._active_handle in self._corner_order:
3672
+ refmax = max(refx, refy, key=abs)
3673
+ if self._active_handle in ['E', 'W'] or refmax == refx:
3674
+ sign = np.sign(ydata - y0)
3675
+ y1 = y0 + sign * abs(x1 - x0) / self._aspect_ratio_correction
3676
+ else:
3677
+ sign = np.sign(xdata - x0)
3678
+ x1 = x0 + sign * abs(y1 - y0) * self._aspect_ratio_correction
3679
+
3680
+ elif action == _RectangleSelectorAction.MOVE:
3681
+ x0, x1, y0, y1 = self._extents_on_press
3682
+ dx = xdata - eventpress.xdata
3683
+ dy = ydata - eventpress.ydata
3684
+ x0 += dx
3685
+ x1 += dx
3686
+ y0 += dy
3687
+ y1 += dy
3688
+
3689
+ else:
3690
+ # Create a new shape
3691
+ self._rotation = 0
3692
+ # Don't create a new rectangle if there is already one when
3693
+ # ignore_event_outside=True
3694
+ if ((self.ignore_event_outside and self._selection_completed) or
3695
+ not self._allow_creation):
3696
+ return
3697
+ center = [eventpress.xdata, eventpress.ydata]
3698
+ dx = (xdata - center[0]) / 2
3699
+ dy = (ydata - center[1]) / 2
3700
+
3701
+ # square shape
3702
+ if 'square' in state:
3703
+ refmax = max(refx, refy, key=abs)
3704
+ if refmax == refx:
3705
+ dy = np.sign(dy) * abs(dx) / self._aspect_ratio_correction
3706
+ else:
3707
+ dx = np.sign(dx) * abs(dy) * self._aspect_ratio_correction
3708
+
3709
+ # from center
3710
+ if 'center' in state:
3711
+ dx *= 2
3712
+ dy *= 2
3713
+
3714
+ # from corner
3715
+ else:
3716
+ center[0] += dx
3717
+ center[1] += dy
3718
+
3719
+ x0, x1, y0, y1 = (center[0] - dx, center[0] + dx,
3720
+ center[1] - dy, center[1] + dy)
3721
+
3722
+ self.extents = x0, x1, y0, y1
3723
+
3724
+ @property
3725
+ def _rect_bbox(self):
3726
+ return self._selection_artist.get_bbox().bounds
3727
+
3728
+ def _set_aspect_ratio_correction(self):
3729
+ aspect_ratio = self.ax._get_aspect_ratio()
3730
+ self._selection_artist._aspect_ratio_correction = aspect_ratio
3731
+ if self._use_data_coordinates:
3732
+ self._aspect_ratio_correction = 1
3733
+ else:
3734
+ self._aspect_ratio_correction = aspect_ratio
3735
+
3736
+ def _get_rotation_transform(self):
3737
+ aspect_ratio = self.ax._get_aspect_ratio()
3738
+ return Affine2D().translate(-self.center[0], -self.center[1]) \
3739
+ .scale(1, aspect_ratio) \
3740
+ .rotate(self._rotation) \
3741
+ .scale(1, 1 / aspect_ratio) \
3742
+ .translate(*self.center)
3743
+
3744
+ @property
3745
+ def corners(self):
3746
+ """
3747
+ Corners of rectangle in data coordinates from lower left,
3748
+ moving clockwise.
3749
+ """
3750
+ x0, y0, width, height = self._rect_bbox
3751
+ xc = x0, x0 + width, x0 + width, x0
3752
+ yc = y0, y0, y0 + height, y0 + height
3753
+ transform = self._get_rotation_transform()
3754
+ coords = transform.transform(np.array([xc, yc]).T).T
3755
+ return coords[0], coords[1]
3756
+
3757
+ @property
3758
+ def edge_centers(self):
3759
+ """
3760
+ Midpoint of rectangle edges in data coordinates from left,
3761
+ moving anti-clockwise.
3762
+ """
3763
+ x0, y0, width, height = self._rect_bbox
3764
+ w = width / 2.
3765
+ h = height / 2.
3766
+ xe = x0, x0 + w, x0 + width, x0 + w
3767
+ ye = y0 + h, y0, y0 + h, y0 + height
3768
+ transform = self._get_rotation_transform()
3769
+ coords = transform.transform(np.array([xe, ye]).T).T
3770
+ return coords[0], coords[1]
3771
+
3772
+ @property
3773
+ def center(self):
3774
+ """Center of rectangle in data coordinates."""
3775
+ x0, y0, width, height = self._rect_bbox
3776
+ return x0 + width / 2., y0 + height / 2.
3777
+
3778
+ @property
3779
+ def extents(self):
3780
+ """
3781
+ Return (xmin, xmax, ymin, ymax) in data coordinates as defined by the
3782
+ bounding box before rotation.
3783
+ """
3784
+ x0, y0, width, height = self._rect_bbox
3785
+ xmin, xmax = sorted([x0, x0 + width])
3786
+ ymin, ymax = sorted([y0, y0 + height])
3787
+ return xmin, xmax, ymin, ymax
3788
+
3789
+ @extents.setter
3790
+ def extents(self, extents):
3791
+ # Update displayed shape
3792
+ self._draw_shape(extents)
3793
+ if self._interactive:
3794
+ # Update displayed handles
3795
+ self._corner_handles.set_data(*self.corners)
3796
+ self._edge_handles.set_data(*self.edge_centers)
3797
+ x, y = self.center
3798
+ self._center_handle.set_data([x], [y])
3799
+ self.set_visible(self._visible)
3800
+ self.update()
3801
+
3802
+ @property
3803
+ def rotation(self):
3804
+ """
3805
+ Rotation in degree in interval [-45°, 45°]. The rotation is limited in
3806
+ range to keep the implementation simple.
3807
+ """
3808
+ return np.rad2deg(self._rotation)
3809
+
3810
+ @rotation.setter
3811
+ def rotation(self, value):
3812
+ # Restrict to a limited range of rotation [-45°, 45°] to avoid changing
3813
+ # order of handles
3814
+ if -45 <= value and value <= 45:
3815
+ self._rotation = np.deg2rad(value)
3816
+ # call extents setter to draw shape and update handles positions
3817
+ self.extents = self.extents
3818
+
3819
+ def _draw_shape(self, extents):
3820
+ x0, x1, y0, y1 = extents
3821
+ xmin, xmax = sorted([x0, x1])
3822
+ ymin, ymax = sorted([y0, y1])
3823
+ xlim = sorted(self.ax.get_xlim())
3824
+ ylim = sorted(self.ax.get_ylim())
3825
+
3826
+ xmin = max(xlim[0], xmin)
3827
+ ymin = max(ylim[0], ymin)
3828
+ xmax = min(xmax, xlim[1])
3829
+ ymax = min(ymax, ylim[1])
3830
+
3831
+ self._selection_artist.set_x(xmin)
3832
+ self._selection_artist.set_y(ymin)
3833
+ self._selection_artist.set_width(xmax - xmin)
3834
+ self._selection_artist.set_height(ymax - ymin)
3835
+ self._selection_artist.set_angle(self.rotation)
3836
+
3837
+ def _set_active_handle(self, event):
3838
+ """Set active handle based on the location of the mouse event."""
3839
+ # Note: event.xdata/ydata in data coordinates, event.x/y in pixels
3840
+ c_idx, c_dist = self._corner_handles.closest(event.x, event.y)
3841
+ e_idx, e_dist = self._edge_handles.closest(event.x, event.y)
3842
+ m_idx, m_dist = self._center_handle.closest(event.x, event.y)
3843
+
3844
+ if 'move' in self._state:
3845
+ self._active_handle = 'C'
3846
+ # Set active handle as closest handle, if mouse click is close enough.
3847
+ elif m_dist < self.grab_range * 2:
3848
+ # Prioritise center handle over other handles
3849
+ self._active_handle = 'C'
3850
+ elif c_dist > self.grab_range and e_dist > self.grab_range:
3851
+ # Not close to any handles
3852
+ if self.drag_from_anywhere and self._contains(event):
3853
+ # Check if we've clicked inside the region
3854
+ self._active_handle = 'C'
3855
+ else:
3856
+ self._active_handle = None
3857
+ return
3858
+ elif c_dist < e_dist:
3859
+ # Closest to a corner handle
3860
+ self._active_handle = self._corner_order[c_idx]
3861
+ else:
3862
+ # Closest to an edge handle
3863
+ self._active_handle = self._edge_order[e_idx]
3864
+
3865
+ def _contains(self, event):
3866
+ """Return True if event is within the patch."""
3867
+ return self._selection_artist.contains(event, radius=0)[0]
3868
+
3869
+ @property
3870
+ def geometry(self):
3871
+ """
3872
+ Return an array of shape (2, 5) containing the
3873
+ x (``RectangleSelector.geometry[1, :]``) and
3874
+ y (``RectangleSelector.geometry[0, :]``) data coordinates of the four
3875
+ corners of the rectangle starting and ending in the top left corner.
3876
+ """
3877
+ if hasattr(self._selection_artist, 'get_verts'):
3878
+ xfm = self.ax.transData.inverted()
3879
+ y, x = xfm.transform(self._selection_artist.get_verts()).T
3880
+ return np.array([x, y])
3881
+ else:
3882
+ return np.array(self._selection_artist.get_data())
3883
+
3884
+
3885
+ @_docstring.Substitution(_RECTANGLESELECTOR_PARAMETERS_DOCSTRING.replace(
3886
+ '__ARTIST_NAME__', 'ellipse'))
3887
+ class EllipseSelector(RectangleSelector):
3888
+ """
3889
+ Select an elliptical region of an Axes.
3890
+
3891
+ For the cursor to remain responsive you must keep a reference to it.
3892
+
3893
+ Press and release events triggered at the same coordinates outside the
3894
+ selection will clear the selector, except when
3895
+ ``ignore_event_outside=True``.
3896
+
3897
+ %s
3898
+
3899
+ Examples
3900
+ --------
3901
+ :doc:`/gallery/widgets/rectangle_selector`
3902
+ """
3903
+ def _init_shape(self, **props):
3904
+ return Ellipse((0, 0), 0, 1, visible=False, **props)
3905
+
3906
+ def _draw_shape(self, extents):
3907
+ x0, x1, y0, y1 = extents
3908
+ xmin, xmax = sorted([x0, x1])
3909
+ ymin, ymax = sorted([y0, y1])
3910
+ center = [x0 + (x1 - x0) / 2., y0 + (y1 - y0) / 2.]
3911
+ a = (xmax - xmin) / 2.
3912
+ b = (ymax - ymin) / 2.
3913
+
3914
+ self._selection_artist.center = center
3915
+ self._selection_artist.width = 2 * a
3916
+ self._selection_artist.height = 2 * b
3917
+ self._selection_artist.angle = self.rotation
3918
+
3919
+ @property
3920
+ def _rect_bbox(self):
3921
+ x, y = self._selection_artist.center
3922
+ width = self._selection_artist.width
3923
+ height = self._selection_artist.height
3924
+ return x - width / 2., y - height / 2., width, height
3925
+
3926
+
3927
+ class LassoSelector(_SelectorWidget):
3928
+ """
3929
+ Selection curve of an arbitrary shape.
3930
+
3931
+ For the selector to remain responsive you must keep a reference to it.
3932
+
3933
+ The selected path can be used in conjunction with `~.Path.contains_point`
3934
+ to select data points from an image.
3935
+
3936
+ In contrast to `Lasso`, `LassoSelector` is written with an interface
3937
+ similar to `RectangleSelector` and `SpanSelector`, and will continue to
3938
+ interact with the Axes until disconnected.
3939
+
3940
+ Example usage::
3941
+
3942
+ ax = plt.subplot()
3943
+ ax.plot(x, y)
3944
+
3945
+ def onselect(verts):
3946
+ print(verts)
3947
+ lasso = LassoSelector(ax, onselect)
3948
+
3949
+ Parameters
3950
+ ----------
3951
+ ax : `~matplotlib.axes.Axes`
3952
+ The parent Axes for the widget.
3953
+ onselect : function, optional
3954
+ Whenever the lasso is released, the *onselect* function is called and
3955
+ passed the vertices of the selected path.
3956
+ useblit : bool, default: True
3957
+ Whether to use blitting for faster drawing (if supported by the
3958
+ backend). See the tutorial :ref:`blitting`
3959
+ for details.
3960
+ props : dict, optional
3961
+ Properties with which the line is drawn, see `.Line2D`
3962
+ for valid properties. Default values are defined in ``mpl.rcParams``.
3963
+ button : `.MouseButton` or list of `.MouseButton`, optional
3964
+ The mouse buttons used for rectangle selection. Default is ``None``,
3965
+ which corresponds to all buttons.
3966
+ """
3967
+
3968
+ def __init__(self, ax, onselect=None, *, useblit=True, props=None, button=None):
3969
+ super().__init__(ax, onselect, useblit=useblit, button=button)
3970
+ self.verts = None
3971
+ props = {
3972
+ **(props if props is not None else {}),
3973
+ # Note that self.useblit may be != useblit, if the canvas doesn't
3974
+ # support blitting.
3975
+ 'animated': self._useblit, 'visible': False,
3976
+ }
3977
+ line = Line2D([], [], **props)
3978
+ self.ax.add_line(line)
3979
+ self._selection_artist = line
3980
+
3981
+ def _press(self, event):
3982
+ self.verts = [self._get_data(event)]
3983
+ self._selection_artist.set_visible(True)
3984
+
3985
+ @_call_with_reparented_event
3986
+ def _release(self, event):
3987
+ if self.verts is not None:
3988
+ self.verts.append(self._get_data(event))
3989
+ self.onselect(self.verts)
3990
+ self._selection_artist.set_data([[], []])
3991
+ self._selection_artist.set_visible(False)
3992
+ self.verts = None
3993
+
3994
+ def _onmove(self, event):
3995
+ if self.verts is None:
3996
+ return
3997
+ self.verts.append(self._get_data(event))
3998
+ self._selection_artist.set_data(list(zip(*self.verts)))
3999
+
4000
+ self.update()
4001
+
4002
+
4003
+ class PolygonSelector(_SelectorWidget):
4004
+ """
4005
+ Select a polygon region of an Axes.
4006
+
4007
+ Place vertices with each mouse click, and make the selection by completing
4008
+ the polygon (clicking on the first vertex). Once drawn individual vertices
4009
+ can be moved by clicking and dragging with the left mouse button, or
4010
+ removed by clicking the right mouse button.
4011
+
4012
+ In addition, the following modifier keys can be used:
4013
+
4014
+ - Hold *ctrl* and click and drag a vertex to reposition it before the
4015
+ polygon has been completed.
4016
+ - Hold the *shift* key and click and drag anywhere in the Axes to move
4017
+ all vertices.
4018
+ - Press the *esc* key to start a new polygon.
4019
+
4020
+ For the selector to remain responsive you must keep a reference to it.
4021
+
4022
+ Parameters
4023
+ ----------
4024
+ ax : `~matplotlib.axes.Axes`
4025
+ The parent Axes for the widget.
4026
+
4027
+ onselect : function, optional
4028
+ When a polygon is completed or modified after completion,
4029
+ the *onselect* function is called and passed a list of the vertices as
4030
+ ``(xdata, ydata)`` tuples.
4031
+
4032
+ useblit : bool, default: False
4033
+ Whether to use blitting for faster drawing (if supported by the
4034
+ backend). See the tutorial :ref:`blitting`
4035
+ for details.
4036
+
4037
+ props : dict, optional
4038
+ Properties with which the line is drawn, see `.Line2D` for valid properties.
4039
+ Default::
4040
+
4041
+ dict(color='k', linestyle='-', linewidth=2, alpha=0.5)
4042
+
4043
+ handle_props : dict, optional
4044
+ Artist properties for the markers drawn at the vertices of the polygon.
4045
+ See the marker arguments in `.Line2D` for valid
4046
+ properties. Default values are defined in ``mpl.rcParams`` except for
4047
+ the default value of ``markeredgecolor`` which will be the same as the
4048
+ ``color`` property in *props*.
4049
+
4050
+ grab_range : float, default: 10
4051
+ A vertex is selected (to complete the polygon or to move a vertex) if
4052
+ the mouse click is within *grab_range* pixels of the vertex.
4053
+
4054
+ draw_bounding_box : bool, optional
4055
+ If `True`, a bounding box will be drawn around the polygon selector
4056
+ once it is complete. This box can be used to move and resize the
4057
+ selector.
4058
+
4059
+ box_handle_props : dict, optional
4060
+ Properties to set for the box handles. See the documentation for the
4061
+ *handle_props* argument to `RectangleSelector` for more info.
4062
+
4063
+ box_props : dict, optional
4064
+ Properties to set for the box. See the documentation for the *props*
4065
+ argument to `RectangleSelector` for more info.
4066
+
4067
+ Examples
4068
+ --------
4069
+ :doc:`/gallery/widgets/polygon_selector_simple`
4070
+ :doc:`/gallery/widgets/polygon_selector_demo`
4071
+
4072
+ Notes
4073
+ -----
4074
+ If only one point remains after removing points, the selector reverts to an
4075
+ incomplete state and you can start drawing a new polygon from the existing
4076
+ point.
4077
+ """
4078
+
4079
+ def __init__(self, ax, onselect=None, *, useblit=False,
4080
+ props=None, handle_props=None, grab_range=10,
4081
+ draw_bounding_box=False, box_handle_props=None,
4082
+ box_props=None):
4083
+ # The state modifiers 'move', 'square', and 'center' are expected by
4084
+ # _SelectorWidget but are not supported by PolygonSelector
4085
+ # Note: could not use the existing 'move' state modifier in-place of
4086
+ # 'move_all' because _SelectorWidget automatically discards 'move'
4087
+ # from the state on button release.
4088
+ state_modifier_keys = dict(clear='escape', move_vertex='control',
4089
+ move_all='shift', move='not-applicable',
4090
+ square='not-applicable',
4091
+ center='not-applicable',
4092
+ rotate='not-applicable')
4093
+ super().__init__(ax, onselect, useblit=useblit,
4094
+ state_modifier_keys=state_modifier_keys)
4095
+
4096
+ self._xys = [(0, 0)]
4097
+
4098
+ if props is None:
4099
+ props = dict(color='k', linestyle='-', linewidth=2, alpha=0.5)
4100
+ props = {**props, 'animated': self._useblit}
4101
+ self._selection_artist = line = Line2D([], [], **props)
4102
+ self.ax.add_line(line)
4103
+
4104
+ if handle_props is None:
4105
+ handle_props = dict(markeredgecolor='k',
4106
+ markerfacecolor=props.get('color', 'k'))
4107
+ self._handle_props = handle_props
4108
+ self._polygon_handles = ToolHandles(self.ax, [], [],
4109
+ useblit=self._useblit,
4110
+ marker_props=self._handle_props)
4111
+
4112
+ self._active_handle_idx = -1
4113
+ self.grab_range = grab_range
4114
+
4115
+ self.set_visible(True)
4116
+ self._draw_box = draw_bounding_box
4117
+ self._box = None
4118
+
4119
+ if box_handle_props is None:
4120
+ box_handle_props = {}
4121
+ self._box_handle_props = {**self._handle_props, **box_handle_props}
4122
+ self._box_props = box_props
4123
+
4124
+ def _get_bbox(self):
4125
+ return self._selection_artist.get_bbox()
4126
+
4127
+ def _add_box(self):
4128
+ self._box = RectangleSelector(self.ax,
4129
+ useblit=self._useblit,
4130
+ grab_range=self.grab_range,
4131
+ handle_props=self._box_handle_props,
4132
+ props=self._box_props,
4133
+ interactive=True)
4134
+ self._box._state_modifier_keys.pop('rotate')
4135
+ self._box.connect_event('motion_notify_event', self._scale_polygon)
4136
+ self._update_box()
4137
+ # Set state that prevents the RectangleSelector from being created
4138
+ # by the user
4139
+ self._box._allow_creation = False
4140
+ self._box._selection_completed = True
4141
+ self._draw_polygon()
4142
+
4143
+ def _remove_box(self):
4144
+ if self._box is not None:
4145
+ self._box.set_visible(False)
4146
+ self._box = None
4147
+
4148
+ def _update_box(self):
4149
+ # Update selection box extents to the extents of the polygon
4150
+ if self._box is not None:
4151
+ bbox = self._get_bbox()
4152
+ self._box.extents = [bbox.x0, bbox.x1, bbox.y0, bbox.y1]
4153
+ # Save a copy
4154
+ self._old_box_extents = self._box.extents
4155
+
4156
+ @_call_with_reparented_event
4157
+ def _scale_polygon(self, event):
4158
+ """
4159
+ Scale the polygon selector points when the bounding box is moved or
4160
+ scaled.
4161
+
4162
+ This is set as a callback on the bounding box RectangleSelector.
4163
+ """
4164
+ if not self._selection_completed:
4165
+ return
4166
+
4167
+ if self._old_box_extents == self._box.extents:
4168
+ return
4169
+
4170
+ # Create transform from old box to new box
4171
+ x1, y1, w1, h1 = self._box._rect_bbox
4172
+ old_bbox = self._get_bbox()
4173
+ t = (transforms.Affine2D()
4174
+ .translate(-old_bbox.x0, -old_bbox.y0)
4175
+ .scale(1 / old_bbox.width, 1 / old_bbox.height)
4176
+ .scale(w1, h1)
4177
+ .translate(x1, y1))
4178
+
4179
+ # Update polygon verts. Must be a list of tuples for consistency.
4180
+ new_verts = [(x, y) for x, y in t.transform(np.array(self.verts))]
4181
+ self._xys = [*new_verts, new_verts[0]]
4182
+ self._draw_polygon()
4183
+ self._old_box_extents = self._box.extents
4184
+
4185
+ @property
4186
+ def _handles_artists(self):
4187
+ return self._polygon_handles.artists
4188
+
4189
+ def _remove_vertex(self, i):
4190
+ """Remove vertex with index i."""
4191
+ if (len(self._xys) > 2 and
4192
+ self._selection_completed and
4193
+ i in (0, len(self._xys) - 1)):
4194
+ # If selecting the first or final vertex, remove both first and
4195
+ # last vertex as they are the same for a closed polygon
4196
+ self._xys.pop(0)
4197
+ self._xys.pop(-1)
4198
+ # Close the polygon again by appending the new first vertex to the
4199
+ # end
4200
+ self._xys.append(self._xys[0])
4201
+ else:
4202
+ self._xys.pop(i)
4203
+ if len(self._xys) <= 2:
4204
+ # If only one point left, return to incomplete state to let user
4205
+ # start drawing again
4206
+ self._selection_completed = False
4207
+ self._remove_box()
4208
+
4209
+ def _press(self, event):
4210
+ """Button press event handler."""
4211
+ # Check for selection of a tool handle.
4212
+ if ((self._selection_completed or 'move_vertex' in self._state)
4213
+ and len(self._xys) > 0):
4214
+ h_idx, h_dist = self._polygon_handles.closest(event.x, event.y)
4215
+ if h_dist < self.grab_range:
4216
+ self._active_handle_idx = h_idx
4217
+ # Save the vertex positions at the time of the press event (needed to
4218
+ # support the 'move_all' state modifier).
4219
+ self._xys_at_press = self._xys.copy()
4220
+
4221
+ @_call_with_reparented_event
4222
+ def _release(self, event):
4223
+ """Button release event handler."""
4224
+ # Release active tool handle.
4225
+ if self._active_handle_idx >= 0:
4226
+ if event.button == 3:
4227
+ self._remove_vertex(self._active_handle_idx)
4228
+ self._draw_polygon()
4229
+ self._active_handle_idx = -1
4230
+
4231
+ # Complete the polygon.
4232
+ elif len(self._xys) > 3 and self._xys[-1] == self._xys[0]:
4233
+ self._selection_completed = True
4234
+ if self._draw_box and self._box is None:
4235
+ self._add_box()
4236
+
4237
+ # Place new vertex.
4238
+ elif (not self._selection_completed
4239
+ and 'move_all' not in self._state
4240
+ and 'move_vertex' not in self._state):
4241
+ self._xys.insert(-1, (event.xdata, event.ydata))
4242
+
4243
+ if self._selection_completed:
4244
+ self.onselect(self.verts)
4245
+
4246
+ @_call_with_reparented_event
4247
+ def onmove(self, event):
4248
+ """Cursor move event handler and validator."""
4249
+ # Method overrides _SelectorWidget.onmove because the polygon selector
4250
+ # needs to process the move callback even if there is no button press.
4251
+ # _SelectorWidget.onmove include logic to ignore move event if
4252
+ # _eventpress is None.
4253
+ if self.ignore(event):
4254
+ # Hide the cursor when interactive zoom/pan is active
4255
+ if not self.canvas.widgetlock.available(self) and self._xys:
4256
+ self._xys[-1] = (np.nan, np.nan)
4257
+ self._draw_polygon()
4258
+ return False
4259
+
4260
+ else:
4261
+ event = self._clean_event(event)
4262
+ self._onmove(event)
4263
+ return True
4264
+
4265
+ def _onmove(self, event):
4266
+ """Cursor move event handler."""
4267
+ # Move the active vertex (ToolHandle).
4268
+ if self._active_handle_idx >= 0:
4269
+ idx = self._active_handle_idx
4270
+ self._xys[idx] = (event.xdata, event.ydata)
4271
+ # Also update the end of the polygon line if the first vertex is
4272
+ # the active handle and the polygon is completed.
4273
+ if idx == 0 and self._selection_completed:
4274
+ self._xys[-1] = (event.xdata, event.ydata)
4275
+
4276
+ # Move all vertices.
4277
+ elif 'move_all' in self._state and self._eventpress:
4278
+ dx = event.xdata - self._eventpress.xdata
4279
+ dy = event.ydata - self._eventpress.ydata
4280
+ for k in range(len(self._xys)):
4281
+ x_at_press, y_at_press = self._xys_at_press[k]
4282
+ self._xys[k] = x_at_press + dx, y_at_press + dy
4283
+
4284
+ # Do nothing if completed or waiting for a move.
4285
+ elif (self._selection_completed
4286
+ or 'move_vertex' in self._state or 'move_all' in self._state):
4287
+ return
4288
+
4289
+ # Position pending vertex.
4290
+ else:
4291
+ # Calculate distance to the start vertex.
4292
+ x0, y0 = \
4293
+ self._selection_artist.get_transform().transform(self._xys[0])
4294
+ v0_dist = np.hypot(x0 - event.x, y0 - event.y)
4295
+ # Lock on to the start vertex if near it and ready to complete.
4296
+ if len(self._xys) > 3 and v0_dist < self.grab_range:
4297
+ self._xys[-1] = self._xys[0]
4298
+ else:
4299
+ self._xys[-1] = (event.xdata, event.ydata)
4300
+
4301
+ self._draw_polygon()
4302
+
4303
+ def _on_key_press(self, event):
4304
+ """Key press event handler."""
4305
+ # Remove the pending vertex if entering the 'move_vertex' or
4306
+ # 'move_all' mode
4307
+ if (not self._selection_completed
4308
+ and ('move_vertex' in self._state or
4309
+ 'move_all' in self._state)):
4310
+ self._xys.pop()
4311
+ self._draw_polygon()
4312
+
4313
+ def _on_key_release(self, event):
4314
+ """Key release event handler."""
4315
+ # Add back the pending vertex if leaving the 'move_vertex' or
4316
+ # 'move_all' mode (by checking the released key)
4317
+ if (not self._selection_completed
4318
+ and
4319
+ (event.key == self._state_modifier_keys.get('move_vertex')
4320
+ or event.key == self._state_modifier_keys.get('move_all'))):
4321
+ self._xys.append((event.xdata, event.ydata))
4322
+ self._draw_polygon()
4323
+ # Reset the polygon if the released key is the 'clear' key.
4324
+ elif event.key == self._state_modifier_keys.get('clear'):
4325
+ event = self._clean_event(event)
4326
+ self._xys = [(event.xdata, event.ydata)]
4327
+ self._selection_completed = False
4328
+ self._remove_box()
4329
+ self.set_visible(True)
4330
+
4331
+ def _draw_polygon_without_update(self):
4332
+ """Redraw the polygon based on new vertex positions, no update()."""
4333
+ xs, ys = zip(*self._xys) if self._xys else ([], [])
4334
+ self._selection_artist.set_data(xs, ys)
4335
+ self._update_box()
4336
+ # Only show one tool handle at the start and end vertex of the polygon
4337
+ # if the polygon is completed or the user is locked on to the start
4338
+ # vertex.
4339
+ if (self._selection_completed
4340
+ or (len(self._xys) > 3
4341
+ and self._xys[-1] == self._xys[0])):
4342
+ self._polygon_handles.set_data(xs[:-1], ys[:-1])
4343
+ else:
4344
+ self._polygon_handles.set_data(xs, ys)
4345
+
4346
+ def _draw_polygon(self):
4347
+ """Redraw the polygon based on the new vertex positions."""
4348
+ self._draw_polygon_without_update()
4349
+ self.update()
4350
+
4351
+ @property
4352
+ def verts(self):
4353
+ """The polygon vertices, as a list of ``(x, y)`` pairs."""
4354
+ return self._xys[:-1]
4355
+
4356
+ @verts.setter
4357
+ def verts(self, xys):
4358
+ """
4359
+ Set the polygon vertices.
4360
+
4361
+ This will remove any preexisting vertices, creating a complete polygon
4362
+ with the new vertices.
4363
+ """
4364
+ self._xys = [*xys, xys[0]]
4365
+ self._selection_completed = True
4366
+ self.set_visible(True)
4367
+ if self._draw_box and self._box is None:
4368
+ self._add_box()
4369
+ self._draw_polygon()
4370
+
4371
+ def _clear_without_update(self):
4372
+ self._selection_completed = False
4373
+ self._xys = [(0, 0)]
4374
+ self._draw_polygon_without_update()
4375
+
4376
+
4377
+ class Lasso(AxesWidget):
4378
+ """
4379
+ Selection curve of an arbitrary shape.
4380
+
4381
+ The selected path can be used in conjunction with
4382
+ `~matplotlib.path.Path.contains_point` to select data points from an image.
4383
+
4384
+ Unlike `LassoSelector`, this must be initialized with a starting
4385
+ point *xy*, and the `Lasso` events are destroyed upon release.
4386
+
4387
+ Parameters
4388
+ ----------
4389
+ ax : `~matplotlib.axes.Axes`
4390
+ The parent Axes for the widget.
4391
+ xy : (float, float)
4392
+ Coordinates of the start of the lasso.
4393
+ callback : callable
4394
+ Whenever the lasso is released, the *callback* function is called and
4395
+ passed the vertices of the selected path.
4396
+ useblit : bool, default: True
4397
+ Whether to use blitting for faster drawing (if supported by the
4398
+ backend). See the tutorial :ref:`blitting`
4399
+ for details.
4400
+ props: dict, optional
4401
+ Lasso line properties. See `.Line2D` for valid properties.
4402
+ Default *props* are::
4403
+
4404
+ {'linestyle' : '-', 'color' : 'black', 'lw' : 2}
4405
+
4406
+ .. versionadded:: 3.9
4407
+ """
4408
+ def __init__(self, ax, xy, callback, *, useblit=True, props=None):
4409
+ super().__init__(ax)
4410
+
4411
+ self.useblit = useblit and self.canvas.supports_blit # TODO: Make dynamic
4412
+ if self.useblit:
4413
+ self.background = self.canvas.copy_from_bbox(self.ax.bbox)
4414
+
4415
+ style = {'linestyle': '-', 'color': 'black', 'lw': 2}
4416
+
4417
+ if props is not None:
4418
+ style.update(props)
4419
+
4420
+ x, y = xy
4421
+ self.verts = [(x, y)]
4422
+ self.line = Line2D([x], [y], **style)
4423
+ self.ax.add_line(self.line)
4424
+ self.callback = callback
4425
+ self.connect_event('button_release_event', self.onrelease)
4426
+ self.connect_event('motion_notify_event', self.onmove)
4427
+
4428
+ @_call_with_reparented_event
4429
+ def onrelease(self, event):
4430
+ if self.ignore(event):
4431
+ return
4432
+ if self.verts is not None:
4433
+ self.verts.append((event.xdata, event.ydata))
4434
+ if len(self.verts) > 2:
4435
+ self.callback(self.verts)
4436
+ self.line.remove()
4437
+ self.verts = None
4438
+ self.disconnect_events()
4439
+
4440
+ @_call_with_reparented_event
4441
+ def onmove(self, event):
4442
+ if (self.ignore(event)
4443
+ or self.verts is None
4444
+ or event.button != 1
4445
+ or not self.ax.contains(event)[0]):
4446
+ return
4447
+ self.verts.append((event.xdata, event.ydata))
4448
+ self.line.set_data(list(zip(*self.verts)))
4449
+
4450
+ if self.useblit:
4451
+ self.canvas.restore_region(self.background)
4452
+ self.ax.draw_artist(self.line)
4453
+ self.canvas.blit(self.ax.bbox)
4454
+ else:
4455
+ self.canvas.draw_idle()