matplotlib-rs 0.0.8__cp315-cp315-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.cp315-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,1480 @@
1
+ # Vendored from matplotlib 3.11 (see licenses/LICENSE_MATPLOTLIB), adapted for matplotlib_rs.
2
+ """
3
+ The legend module defines the Legend class, which is responsible for
4
+ drawing legends associated with Axes and/or figures.
5
+
6
+ .. important::
7
+
8
+ It is unlikely that you would ever create a Legend instance manually.
9
+ Most users would normally create a legend via the `~.Axes.legend`
10
+ function. For more details on legends there is also a :ref:`legend guide
11
+ <legend_guide>`.
12
+
13
+ The `Legend` class is a container of legend handles and legend texts.
14
+
15
+ The legend handler map specifies how to create legend handles from artists
16
+ (lines, patches, etc.) in the Axes or figures. Default legend handlers are
17
+ defined in the :mod:`~matplotlib.legend_handler` module. While not all artist
18
+ types are covered by the default legend handlers, custom legend handlers can be
19
+ defined to support arbitrary objects.
20
+
21
+ See the :ref`<legend_guide>` for more
22
+ information.
23
+ """
24
+
25
+ import itertools
26
+ import logging
27
+ import numbers
28
+ import time
29
+
30
+ import numpy as np
31
+
32
+ import matplotlib_rs as mpl
33
+ from matplotlib_rs import _api, _docstring, _path, cbook, colors, offsetbox
34
+ from matplotlib_rs.artist import Artist, allow_rasterization
35
+ from matplotlib_rs.cbook import silent_list
36
+ from matplotlib_rs.font_manager import FontProperties
37
+ from matplotlib_rs.lines import Line2D
38
+ from matplotlib_rs.patches import (Patch, Rectangle, Shadow, FancyBboxPatch,
39
+ StepPatch)
40
+ from matplotlib_rs.collections import (
41
+ Collection, CircleCollection, LineCollection, PatchCollection, PathCollection,
42
+ PolyCollection, RegularPolyCollection)
43
+ from matplotlib_rs.text import Text
44
+ from matplotlib_rs.transforms import Bbox, BboxBase, TransformedBbox
45
+ from matplotlib_rs.transforms import BboxTransformTo, BboxTransformFrom
46
+ from matplotlib_rs.offsetbox import (
47
+ AnchoredOffsetbox, DraggableOffsetBox,
48
+ HPacker, VPacker,
49
+ DrawingArea, TextArea,
50
+ )
51
+ from matplotlib_rs.container import ErrorbarContainer, BarContainer, StemContainer
52
+ from . import legend_handler
53
+
54
+
55
+ class DraggableLegend(DraggableOffsetBox):
56
+ def __init__(self, legend, use_blit=False, update="loc"):
57
+ """
58
+ Wrapper around a `.Legend` to support mouse dragging.
59
+
60
+ Parameters
61
+ ----------
62
+ legend : `.Legend`
63
+ The `.Legend` instance to wrap.
64
+ use_blit : bool, optional
65
+ Use blitting for faster image composition. For details see
66
+ :ref:`func-animation`.
67
+ update : {'loc', 'bbox'}, optional
68
+ If "loc", update the *loc* parameter of the legend upon finalizing.
69
+ If "bbox", update the *bbox_to_anchor* parameter.
70
+ """
71
+ self.legend = legend
72
+
73
+ _api.check_in_list(["loc", "bbox"], update=update)
74
+ self._update = update
75
+
76
+ super().__init__(legend, legend._legend_box, use_blit=use_blit)
77
+
78
+ def finalize_offset(self):
79
+ if self._update == "loc":
80
+ self._update_loc(self.get_loc_in_canvas())
81
+ elif self._update == "bbox":
82
+ self._update_bbox_to_anchor(self.get_loc_in_canvas())
83
+
84
+ def _update_loc(self, loc_in_canvas):
85
+ bbox = self.legend.get_bbox_to_anchor()
86
+ # if bbox has zero width or height, the transformation is
87
+ # ill-defined. Fall back to the default bbox_to_anchor.
88
+ if bbox.width == 0 or bbox.height == 0:
89
+ self.legend.set_bbox_to_anchor(None)
90
+ bbox = self.legend.get_bbox_to_anchor()
91
+ _bbox_transform = BboxTransformFrom(bbox)
92
+ self.legend._loc = tuple(_bbox_transform.transform(loc_in_canvas))
93
+
94
+ def _update_bbox_to_anchor(self, loc_in_canvas):
95
+ loc_in_bbox = self.legend.axes.transAxes.transform(loc_in_canvas)
96
+ self.legend.set_bbox_to_anchor(loc_in_bbox)
97
+
98
+
99
+ _legend_kw_doc_base = """
100
+ bbox_to_anchor : `.BboxBase`, 2-tuple, or 4-tuple of floats
101
+ Box that is used to position the legend in conjunction with *loc*.
102
+ This is an advanced option for free placement of the legend. For
103
+ most use cases, *loc* alone is sufficient.
104
+
105
+ Defaults to ``axes.bbox`` (if called as a method to `.Axes.legend`) or
106
+ ``figure.bbox`` (if ``figure.legend``).
107
+
108
+ Bbox coordinates are interpreted in the coordinate system given by
109
+ *bbox_transform*, with the default transform
110
+ Axes or Figure coordinates, depending on which ``legend`` is called.
111
+
112
+ If a 4-tuple or `.BboxBase` is given, then it specifies the bbox
113
+ ``(x, y, width, height)`` that the legend is placed in.
114
+ To put the legend in the best location in the bottom right
115
+ quadrant of the Axes (or figure)::
116
+
117
+ loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5)
118
+
119
+ A 2-tuple ``(x, y)`` places the corner of the legend specified by *loc* at
120
+ x, y. For example, to put the legend's upper right-hand corner in the
121
+ center of the Axes (or figure) the following keywords can be used::
122
+
123
+ loc='upper right', bbox_to_anchor=(0.5, 0.5)
124
+
125
+ For more details on legend positioning, see the
126
+ :ref:`legend_guide`.
127
+
128
+ ncols : int, default: 1
129
+ The number of columns that the legend has.
130
+
131
+ For backward compatibility, the spelling *ncol* is also supported
132
+ but it is discouraged. If both are given, *ncols* takes precedence.
133
+
134
+ prop : None or `~matplotlib.font_manager.FontProperties` or dict
135
+ The font properties of the legend. If None (default), the current
136
+ :data:`matplotlib.rcParams` will be used.
137
+
138
+ fontsize : int or {'xx-small', 'x-small', 'small', 'medium', 'large', \
139
+ 'x-large', 'xx-large'}
140
+ The font size of the legend. If the value is numeric the size will be the
141
+ absolute font size in points. String values are relative to the current
142
+ default font size. This argument is only used if *prop* is not specified.
143
+
144
+ labelcolor : str or list, default: :rc:`legend.labelcolor`
145
+ The color of the text in the legend. Either a valid color string
146
+ (for example, 'red'), or a list of color strings. The labelcolor can
147
+ also be made to match the color of the line or marker using 'linecolor',
148
+ 'markerfacecolor' (or 'mfc'), or 'markeredgecolor' (or 'mec').
149
+
150
+ Labelcolor can be set globally using :rc:`legend.labelcolor`. If None,
151
+ use :rc:`text.color`.
152
+
153
+ numpoints : int, default: :rc:`legend.numpoints`
154
+ The number of marker points in the legend when creating a legend
155
+ entry for a `.Line2D` (line).
156
+
157
+ scatterpoints : int, default: :rc:`legend.scatterpoints`
158
+ The number of marker points in the legend when creating
159
+ a legend entry for a `.PathCollection` (scatter plot).
160
+
161
+ scatteryoffsets : iterable of floats, default: ``[0.375, 0.5, 0.3125]``
162
+ The vertical offset (relative to the font size) for the markers
163
+ created for a scatter plot legend entry. 0.0 is at the base the
164
+ legend text, and 1.0 is at the top. To draw all markers at the
165
+ same height, set to ``[0.5]``.
166
+
167
+ markerscale : float, default: :rc:`legend.markerscale`
168
+ The relative size of legend markers compared to the originally drawn ones.
169
+
170
+ markerfirst : bool, default: True
171
+ If *True*, legend marker is placed to the left of the legend label.
172
+ If *False*, legend marker is placed to the right of the legend label.
173
+
174
+ reverse : bool, default: False
175
+ If *True*, the legend labels are displayed in reverse order from the input.
176
+ If *False*, the legend labels are displayed in the same order as the input.
177
+
178
+ .. versionadded:: 3.7
179
+
180
+ frameon : bool, default: :rc:`legend.frameon`
181
+ Whether the legend should be drawn on a patch (frame).
182
+
183
+ fancybox : bool, default: :rc:`legend.fancybox`
184
+ Whether round edges should be enabled around the `.FancyBboxPatch` which
185
+ makes up the legend's background.
186
+
187
+ shadow : None, bool or dict, default: :rc:`legend.shadow`
188
+ Whether to draw a shadow behind the legend.
189
+ The shadow can be configured using `.Patch` keywords.
190
+ Customization via :rc:`legend.shadow` is currently not supported.
191
+
192
+ framealpha : float, default: :rc:`legend.framealpha`
193
+ The alpha transparency of the legend's background.
194
+ If *shadow* is activated and *framealpha* is ``None``, the default value is
195
+ ignored.
196
+
197
+ facecolor : "inherit" or color, default: :rc:`legend.facecolor`
198
+ The legend's background color.
199
+ If ``"inherit"``, use :rc:`axes.facecolor`.
200
+
201
+ edgecolor : "inherit" or color, default: :rc:`legend.edgecolor`
202
+ The legend's background patch edge color.
203
+ If ``"inherit"``, use :rc:`axes.edgecolor`.
204
+
205
+ linewidth : float or None, default: :rc:`legend.linewidth`
206
+ The legend's background patch edge linewidth.
207
+ If ``None``, use :rc:`patch.linewidth`.
208
+
209
+ .. versionadded:: 3.11
210
+
211
+ mode : {"expand", None}
212
+ If *mode* is set to ``"expand"`` the legend will be horizontally
213
+ expanded to fill the Axes area (or *bbox_to_anchor* if defines
214
+ the legend's size).
215
+
216
+ bbox_transform : None or `~matplotlib.transforms.Transform`
217
+ The transform for the bounding box (*bbox_to_anchor*). For a value
218
+ of ``None`` (default) the Axes'
219
+ :data:`!matplotlib.axes.Axes.transAxes` transform will be used.
220
+
221
+ title : str or None
222
+ The legend's title. Default is no title (``None``).
223
+
224
+ title_fontproperties : None or `~matplotlib.font_manager.FontProperties` or dict
225
+ The font properties of the legend's title. If None (default), the
226
+ *title_fontsize* argument will be used if present; if *title_fontsize* is
227
+ also None, the current :rc:`legend.title_fontsize` will be used.
228
+
229
+ title_fontsize : int or {'xx-small', 'x-small', 'small', 'medium', 'large', \
230
+ 'x-large', 'xx-large'}, default: :rc:`legend.title_fontsize`
231
+ The font size of the legend's title.
232
+ Note: This cannot be combined with *title_fontproperties*. If you want
233
+ to set the fontsize alongside other font properties, use the *size*
234
+ parameter in *title_fontproperties*.
235
+
236
+ alignment : {'center', 'left', 'right'}, default: 'center'
237
+ The alignment of the legend title and the box of entries. The entries
238
+ are aligned as a single block, so that markers always lined up.
239
+
240
+ borderpad : float, default: :rc:`legend.borderpad`
241
+ The fractional whitespace inside the legend border, in font-size units.
242
+
243
+ labelspacing : float, default: :rc:`legend.labelspacing`
244
+ The vertical space between the legend entries, in font-size units.
245
+
246
+ handlelength : float, default: :rc:`legend.handlelength`
247
+ The length of the legend handles, in font-size units.
248
+
249
+ handleheight : float, default: :rc:`legend.handleheight`
250
+ The height of the legend handles, in font-size units.
251
+
252
+ handletextpad : float, default: :rc:`legend.handletextpad`
253
+ The pad between the legend handle and text, in font-size units.
254
+
255
+ borderaxespad : float, default: :rc:`legend.borderaxespad`
256
+ The pad between the Axes and legend border, in font-size units.
257
+
258
+ columnspacing : float, default: :rc:`legend.columnspacing`
259
+ The spacing between columns, in font-size units.
260
+
261
+ handler_map : dict or None
262
+ The custom dictionary mapping instances or types to a legend
263
+ handler. This *handler_map* updates the default handler map
264
+ found at `matplotlib.legend.Legend.get_legend_handler_map`.
265
+
266
+ draggable : bool, default: False
267
+ Whether the legend can be dragged with the mouse.
268
+ """
269
+
270
+ _loc_doc_base = """
271
+ loc : str or pair of floats, default: {default}
272
+ The location of the legend.
273
+
274
+ The string locations place the legend at the corresponding position
275
+ within the bounding box, which by default is the full {parent} area.
276
+ The bounding box can be changed via *bbox_to_anchor*.
277
+
278
+ The positions are visualized below::
279
+
280
+ +--------------+--------------+---------------+
281
+ | 'upper left' |'upper center'| 'upper right' |
282
+ +--------------+--------------+---------------+
283
+ |'center left' | 'center' |'center right' |
284
+ +--------------+--------------+---------------+
285
+ | 'lower left' |'lower center'| 'lower right' |
286
+ +--------------+--------------+---------------+
287
+ {best}
288
+ The location can also be a 2-tuple giving the coordinates of the lower-left
289
+ corner of the legend in {parent} coordinates (in which case *bbox_to_anchor*
290
+ will be ignored).
291
+
292
+ For back-compatibility, ``'center right'`` (but no other location) can also
293
+ be spelled ``'right'``, and each "string" location can also be given as a
294
+ numeric value:
295
+
296
+ ================== =============
297
+ Location String Location Code
298
+ ================== =============
299
+ 'best' (Axes only) 0
300
+ 'upper right' 1
301
+ 'upper left' 2
302
+ 'lower left' 3
303
+ 'lower right' 4
304
+ 'right' 5
305
+ 'center left' 6
306
+ 'center right' 7
307
+ 'lower center' 8
308
+ 'upper center' 9
309
+ 'center' 10
310
+ ================== =============
311
+ {outside}"""
312
+
313
+ _loc_doc_best = """
314
+ The string ``'best'`` places the legend at the location, among the nine
315
+ locations defined so far, with the minimum overlap with other drawn
316
+ artists. This currently takes into account most, but not all, artists
317
+ added to the Axes via plotting functions. In particular it does not consider
318
+ inset axes, titles, or axis labels.
319
+
320
+ The computation of the best position can be expensive for plots with large
321
+ amounts of data. If speed becomes a concern, you may may benefit from
322
+ providing a specific location.
323
+ """
324
+
325
+ _legend_kw_axes_st = (
326
+ _loc_doc_base.format(parent='axes', default=':rc:`legend.loc`',
327
+ best=_loc_doc_best, outside='') +
328
+ _legend_kw_doc_base)
329
+ _docstring.interpd.register(_legend_kw_axes=_legend_kw_axes_st)
330
+
331
+ _outside_doc = """
332
+ If a figure is using the constrained layout manager, the string codes
333
+ of the *loc* keyword argument can get better layout behaviour using the
334
+ prefix 'outside'. There is ambiguity at the corners, so 'outside
335
+ upper right' will make space for the legend above the rest of the
336
+ axes in the layout, and 'outside right upper' will make space on the
337
+ right side of the layout. In addition to the values of *loc*
338
+ listed above, we have 'outside right upper', 'outside right lower',
339
+ 'outside left upper', and 'outside left lower'. See
340
+ :ref:`legend_guide` for more details.
341
+ """
342
+
343
+ _legend_kw_figure_st = (
344
+ _loc_doc_base.format(parent='figure', default="'upper right'",
345
+ best='', outside=_outside_doc) +
346
+ _legend_kw_doc_base)
347
+ _docstring.interpd.register(_legend_kw_figure=_legend_kw_figure_st)
348
+
349
+ _legend_kw_both_st = (
350
+ _loc_doc_base.format(parent='axes/figure',
351
+ default=":rc:`legend.loc` for Axes, 'upper right' for Figure",
352
+ best=_loc_doc_best, outside=_outside_doc) +
353
+ _legend_kw_doc_base)
354
+ _docstring.interpd.register(_legend_kw_doc=_legend_kw_both_st)
355
+
356
+ _legend_kw_set_loc_st = (
357
+ _loc_doc_base.format(parent='axes/figure',
358
+ default=":rc:`legend.loc` for Axes, 'upper right' for Figure",
359
+ best=_loc_doc_best, outside=_outside_doc))
360
+ _docstring.interpd.register(_legend_kw_set_loc_doc=_legend_kw_set_loc_st)
361
+
362
+
363
+ class Legend(Artist):
364
+ """
365
+ Place a legend on the figure/axes.
366
+ """
367
+
368
+ # 'best' is only implemented for Axes legends
369
+ codes = {'best': 0, **AnchoredOffsetbox.codes}
370
+ zorder = 5
371
+
372
+ def __str__(self):
373
+ return "Legend"
374
+
375
+ @_docstring.interpd
376
+ def __init__(
377
+ self, parent, handles, labels,
378
+ *,
379
+ loc=None,
380
+ numpoints=None, # number of points in the legend line
381
+ markerscale=None, # relative size of legend markers vs. original
382
+ markerfirst=True, # left/right ordering of legend marker and label
383
+ reverse=False, # reverse ordering of legend marker and label
384
+ scatterpoints=None, # number of scatter points
385
+ scatteryoffsets=None,
386
+ prop=None, # properties for the legend texts
387
+ fontsize=None, # keyword to set font size directly
388
+ labelcolor=None, # keyword to set the text color
389
+
390
+ # spacing & pad defined as a fraction of the font-size
391
+ borderpad=None, # whitespace inside the legend border
392
+ labelspacing=None, # vertical space between the legend entries
393
+ handlelength=None, # length of the legend handles
394
+ handleheight=None, # height of the legend handles
395
+ handletextpad=None, # pad between the legend handle and text
396
+ borderaxespad=None, # pad between the Axes and legend border
397
+ columnspacing=None, # spacing between columns
398
+
399
+ ncols=1, # number of columns
400
+ mode=None, # horizontal distribution of columns: None or "expand"
401
+
402
+ fancybox=None, # True: fancy box, False: rounded box, None: rcParam
403
+ shadow=None,
404
+ title=None, # legend title
405
+ title_fontsize=None, # legend title font size
406
+ framealpha=None, # set frame alpha
407
+ edgecolor=None, # frame patch edgecolor
408
+ facecolor=None, # frame patch facecolor
409
+ linewidth=None, # frame patch linewidth
410
+
411
+ bbox_to_anchor=None, # bbox to which the legend will be anchored
412
+ bbox_transform=None, # transform for the bbox
413
+ frameon=None, # draw frame
414
+ handler_map=None,
415
+ title_fontproperties=None, # properties for the legend title
416
+ alignment="center", # control the alignment within the legend box
417
+ ncol=1, # synonym for ncols (backward compatibility)
418
+ draggable=False # whether the legend can be dragged with the mouse
419
+ ):
420
+ """
421
+ Parameters
422
+ ----------
423
+ parent : `~matplotlib.axes.Axes` or `.Figure`
424
+ The artist that contains the legend.
425
+
426
+ handles : list of (`.Artist` or tuple of `.Artist`)
427
+ A list of Artists (lines, patches) to be added to the legend.
428
+
429
+ labels : list of str
430
+ A list of labels to show next to the artists. The length of handles
431
+ and labels should be the same. If they are not, they are truncated
432
+ to the length of the shorter list.
433
+
434
+ Other Parameters
435
+ ----------------
436
+ %(_legend_kw_doc)s
437
+
438
+ Attributes
439
+ ----------
440
+ legend_handles
441
+ List of `.Artist` objects added as legend entries.
442
+
443
+ .. versionadded:: 3.7
444
+ """
445
+ # local import only to avoid circularity
446
+ from matplotlib_rs.axes import Axes
447
+ from matplotlib_rs.figure import FigureBase
448
+
449
+ super().__init__()
450
+
451
+ if prop is None:
452
+ self.prop = FontProperties(size=mpl._val_or_rc(fontsize, "legend.fontsize"))
453
+ else:
454
+ self.prop = FontProperties._from_any(prop)
455
+ if isinstance(prop, dict) and "size" not in prop:
456
+ self.prop.set_size(mpl.rcParams["legend.fontsize"])
457
+
458
+ self._fontsize = self.prop.get_size_in_points()
459
+
460
+ self.texts = []
461
+ self.legend_handles = []
462
+ self._legend_title_box = None
463
+
464
+ #: A dictionary with the extra handler mappings for this Legend
465
+ #: instance.
466
+ self._custom_handler_map = handler_map
467
+
468
+ self.numpoints = mpl._val_or_rc(numpoints, 'legend.numpoints')
469
+ self.markerscale = mpl._val_or_rc(markerscale, 'legend.markerscale')
470
+ self.scatterpoints = mpl._val_or_rc(scatterpoints, 'legend.scatterpoints')
471
+ self.borderpad = mpl._val_or_rc(borderpad, 'legend.borderpad')
472
+ self.labelspacing = mpl._val_or_rc(labelspacing, 'legend.labelspacing')
473
+ self.handlelength = mpl._val_or_rc(handlelength, 'legend.handlelength')
474
+ self.handleheight = mpl._val_or_rc(handleheight, 'legend.handleheight')
475
+ self.handletextpad = mpl._val_or_rc(handletextpad, 'legend.handletextpad')
476
+ self.borderaxespad = mpl._val_or_rc(borderaxespad, 'legend.borderaxespad')
477
+ self.columnspacing = mpl._val_or_rc(columnspacing, 'legend.columnspacing')
478
+ self.shadow = mpl._val_or_rc(shadow, 'legend.shadow')
479
+
480
+ if reverse:
481
+ labels = [*reversed(labels)]
482
+ handles = [*reversed(handles)]
483
+
484
+ handles = list(handles)
485
+ if len(handles) < 2:
486
+ ncols = 1
487
+ self._ncols = ncols if ncols != 1 else ncol
488
+
489
+ if self.numpoints <= 0:
490
+ raise ValueError("numpoints must be > 0; it was %d" % numpoints)
491
+
492
+ # introduce y-offset for handles of the scatter plot
493
+ if scatteryoffsets is None:
494
+ self._scatteryoffsets = np.array([3. / 8., 4. / 8., 2.5 / 8.])
495
+ else:
496
+ self._scatteryoffsets = np.asarray(scatteryoffsets)
497
+ reps = self.scatterpoints // len(self._scatteryoffsets) + 1
498
+ self._scatteryoffsets = np.tile(self._scatteryoffsets,
499
+ reps)[:self.scatterpoints]
500
+
501
+ # _legend_box is a VPacker instance that contains all
502
+ # legend items and will be initialized from _init_legend_box()
503
+ # method.
504
+ self._legend_box = None
505
+
506
+ if isinstance(parent, Axes):
507
+ self.isaxes = True
508
+ self.axes = parent
509
+ self.set_figure(parent.get_figure(root=False))
510
+ elif isinstance(parent, FigureBase):
511
+ self.isaxes = False
512
+ self.set_figure(parent)
513
+ else:
514
+ raise TypeError(
515
+ "Legend needs either Axes or FigureBase as parent"
516
+ )
517
+ self.parent = parent
518
+
519
+ self._mode = mode
520
+ self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)
521
+
522
+ # Figure out if self.shadow is valid
523
+ # If shadow was None, rcParams loads False
524
+ # So it shouldn't be None here
525
+
526
+ self._shadow_props = {'ox': 2, 'oy': -2} # default location offsets
527
+ if isinstance(self.shadow, dict):
528
+ self._shadow_props.update(self.shadow)
529
+ self.shadow = True
530
+ elif self.shadow in (0, 1, True, False):
531
+ self.shadow = bool(self.shadow)
532
+ else:
533
+ raise ValueError(
534
+ 'Legend shadow must be a dict or bool, not '
535
+ f'{self.shadow!r} of type {type(self.shadow)}.'
536
+ )
537
+
538
+ # We use FancyBboxPatch to draw a legend frame. The location
539
+ # and size of the box will be updated during the drawing time.
540
+
541
+ facecolor = mpl._val_or_rc(facecolor, "legend.facecolor")
542
+ if facecolor == 'inherit':
543
+ facecolor = mpl.rcParams["axes.facecolor"]
544
+
545
+ edgecolor = mpl._val_or_rc(edgecolor, "legend.edgecolor")
546
+ if edgecolor == 'inherit':
547
+ edgecolor = mpl.rcParams["axes.edgecolor"]
548
+
549
+ fancybox = mpl._val_or_rc(fancybox, "legend.fancybox")
550
+
551
+ linewidth = mpl._val_or_rc(linewidth, "legend.linewidth")
552
+
553
+ self.legendPatch = FancyBboxPatch(
554
+ xy=(0, 0), width=1, height=1,
555
+ facecolor=facecolor, edgecolor=edgecolor,
556
+ linewidth=linewidth,
557
+ # If shadow is used, default to alpha=1 (#8943).
558
+ alpha=(framealpha if framealpha is not None
559
+ else 1 if shadow
560
+ else mpl.rcParams["legend.framealpha"]),
561
+ # The width and height of the legendPatch will be set (in draw())
562
+ # to the length that includes the padding. Thus we set pad=0 here.
563
+ boxstyle=("round,pad=0,rounding_size=0.2" if fancybox
564
+ else "square,pad=0"),
565
+ mutation_scale=self._fontsize,
566
+ snap=True,
567
+ visible=mpl._val_or_rc(frameon, "legend.frameon")
568
+ )
569
+ self._set_artist_props(self.legendPatch)
570
+
571
+ _api.check_in_list(["center", "left", "right"], alignment=alignment)
572
+ self._alignment = alignment
573
+
574
+ # init with null renderer
575
+ self._init_legend_box(handles, labels, markerfirst)
576
+
577
+ # Set legend location
578
+ self.set_loc(loc)
579
+
580
+ # figure out title font properties:
581
+ if title_fontsize is not None and title_fontproperties is not None:
582
+ raise ValueError(
583
+ "title_fontsize and title_fontproperties can't be specified "
584
+ "at the same time. Only use one of them. ")
585
+ title_prop_fp = FontProperties._from_any(title_fontproperties)
586
+ if isinstance(title_fontproperties, dict):
587
+ if "size" not in title_fontproperties:
588
+ title_fontsize = mpl.rcParams["legend.title_fontsize"]
589
+ title_prop_fp.set_size(title_fontsize)
590
+ elif title_fontsize is not None:
591
+ title_prop_fp.set_size(title_fontsize)
592
+ elif not isinstance(title_fontproperties, FontProperties):
593
+ title_fontsize = mpl.rcParams["legend.title_fontsize"]
594
+ title_prop_fp.set_size(title_fontsize)
595
+
596
+ self.set_title(title, prop=title_prop_fp)
597
+
598
+ self._draggable = None
599
+ self.set_draggable(state=draggable)
600
+
601
+ # set the text color
602
+
603
+ color_getters = { # getter function depends on line or patch
604
+ 'linecolor': ['get_markerfacecolor',
605
+ 'get_facecolor',
606
+ 'get_markeredgecolor',
607
+ 'get_edgecolor',
608
+ 'get_color'],
609
+ 'markerfacecolor': ['get_markerfacecolor', 'get_facecolor'],
610
+ 'mfc': ['get_markerfacecolor', 'get_facecolor'],
611
+ 'markeredgecolor': ['get_markeredgecolor', 'get_edgecolor'],
612
+ 'mec': ['get_markeredgecolor', 'get_edgecolor'],
613
+ }
614
+ labelcolor = mpl._val_or_rc(mpl._val_or_rc(labelcolor, 'legend.labelcolor'),
615
+ 'text.color')
616
+ if isinstance(labelcolor, str) and labelcolor in color_getters:
617
+ getter_names = color_getters[labelcolor]
618
+ for handle, text in zip(self.legend_handles, self.texts):
619
+ try:
620
+ if handle.get_array() is not None:
621
+ continue
622
+ except AttributeError:
623
+ pass
624
+ for getter_name in getter_names:
625
+ try:
626
+ color = getattr(handle, getter_name)()
627
+ except AttributeError:
628
+ continue
629
+ if isinstance(color, np.ndarray):
630
+ if color.size == 0:
631
+ continue
632
+ elif (color.shape[0] == 1 or np.isclose(color, color[0]).all()):
633
+ text.set_color(color[0])
634
+ else:
635
+ pass
636
+ elif cbook._str_lower_equal(color, 'none'):
637
+ continue
638
+ elif mpl.colors.to_rgba(color)[3] == 0:
639
+ continue
640
+ else:
641
+ text.set_color(color)
642
+ break
643
+ elif cbook._str_equal(labelcolor, 'none'):
644
+ for text in self.texts:
645
+ text.set_color(labelcolor)
646
+ elif np.iterable(labelcolor):
647
+ for text, color in zip(self.texts,
648
+ itertools.cycle(
649
+ colors.to_rgba_array(labelcolor))):
650
+ text.set_color(color)
651
+ else:
652
+ raise ValueError(f"Invalid labelcolor: {labelcolor!r}")
653
+
654
+ def _set_artist_props(self, a):
655
+ """
656
+ Set the boilerplate props for artists added to Axes.
657
+ """
658
+ a.set_figure(self.get_figure(root=False))
659
+ if self.isaxes:
660
+ a.axes = self.axes
661
+
662
+ a.set_transform(self.get_transform())
663
+
664
+ @_docstring.interpd
665
+ def set_loc(self, loc=None):
666
+ """
667
+ Set the location of the legend.
668
+
669
+ .. versionadded:: 3.8
670
+
671
+ Parameters
672
+ ----------
673
+ %(_legend_kw_set_loc_doc)s
674
+ """
675
+ loc0 = loc
676
+ self._loc_used_default = loc is None
677
+ if loc is None:
678
+ loc = mpl.rcParams["legend.loc"]
679
+ if not self.isaxes and loc in [0, 'best']:
680
+ loc = 'upper right'
681
+
682
+ type_err_message = ("loc must be string, coordinate tuple, or"
683
+ f" an integer 0-10, not {loc!r}")
684
+
685
+ # handle outside legends:
686
+ self._outside_loc = None
687
+ if isinstance(loc, str):
688
+ if loc.split()[0] == 'outside':
689
+ # strip outside:
690
+ loc = loc.split('outside ')[1]
691
+ # strip "center" at the beginning
692
+ self._outside_loc = loc.replace('center ', '')
693
+ # strip first
694
+ self._outside_loc = self._outside_loc.split()[0]
695
+ locs = loc.split()
696
+ if len(locs) > 1 and locs[0] in ('right', 'left'):
697
+ # locs doesn't accept "left upper", etc, so swap
698
+ if locs[0] != 'center':
699
+ locs = locs[::-1]
700
+ loc = locs[0] + ' ' + locs[1]
701
+ # check that loc is in acceptable strings
702
+ loc = _api.getitem_checked(self.codes, loc=loc)
703
+ elif np.iterable(loc):
704
+ # coerce iterable into tuple
705
+ loc = tuple(loc)
706
+ # validate the tuple represents Real coordinates
707
+ if len(loc) != 2 or not all(isinstance(e, numbers.Real) for e in loc):
708
+ raise ValueError(type_err_message)
709
+ elif isinstance(loc, int):
710
+ # validate the integer represents a string numeric value
711
+ if loc < 0 or loc > 10:
712
+ raise ValueError(type_err_message)
713
+ else:
714
+ # all other cases are invalid values of loc
715
+ raise ValueError(type_err_message)
716
+
717
+ if self.isaxes and self._outside_loc:
718
+ raise ValueError(
719
+ f"'outside' option for loc='{loc0}' keyword argument only "
720
+ "works for figure legends")
721
+
722
+ if not self.isaxes and loc == 0:
723
+ raise ValueError(
724
+ "Automatic legend placement (loc='best') not implemented for "
725
+ "figure legend")
726
+
727
+ tmp = self._loc_used_default
728
+ self._set_loc(loc)
729
+ self._loc_used_default = tmp # ignore changes done by _set_loc
730
+
731
+ def _set_loc(self, loc):
732
+ # find_offset function will be provided to _legend_box and
733
+ # _legend_box will draw itself at the location of the return
734
+ # value of the find_offset.
735
+ self._loc_used_default = False
736
+ self._loc_real = loc
737
+ self.stale = True
738
+ self._legend_box.set_offset(self._findoffset)
739
+
740
+ def set_ncols(self, ncols):
741
+ """Set the number of columns."""
742
+ self._ncols = ncols
743
+
744
+ def _get_loc(self):
745
+ return self._loc_real
746
+
747
+ _loc = property(_get_loc, _set_loc)
748
+
749
+ def _findoffset(self, width, height, xdescent, ydescent, renderer):
750
+ """Helper function to locate the legend."""
751
+
752
+ if self._loc == 0: # "best".
753
+ x, y = self._find_best_position(width, height, renderer)
754
+ elif self._loc in Legend.codes.values(): # Fixed location.
755
+ bbox = Bbox.from_bounds(0, 0, width, height)
756
+ x, y = self._get_anchored_bbox(self._loc, bbox,
757
+ self.get_bbox_to_anchor(),
758
+ renderer)
759
+ else: # Axes or figure coordinates.
760
+ fx, fy = self._loc
761
+ bbox = self.get_bbox_to_anchor()
762
+ x, y = bbox.x0 + bbox.width * fx, bbox.y0 + bbox.height * fy
763
+
764
+ return x + xdescent, y + ydescent
765
+
766
+ @allow_rasterization
767
+ def draw(self, renderer):
768
+ # docstring inherited
769
+ if not self.get_visible():
770
+ return
771
+
772
+ renderer.open_group('legend', gid=self.get_gid())
773
+
774
+ fontsize = renderer.points_to_pixels(self._fontsize)
775
+
776
+ # if mode == fill, set the width of the legend_box to the
777
+ # width of the parent (minus pads)
778
+ if self._mode in ["expand"]:
779
+ pad = 2 * (self.borderaxespad + self.borderpad) * fontsize
780
+ self._legend_box.set_width(self.get_bbox_to_anchor().width - pad)
781
+
782
+ # matplotlib_rs: the extent and the draw of the box below both look
783
+ # for the best position, with the same Axes contents; the second one
784
+ # takes the result of the first (see _find_best_position). The
785
+ # extents of the boxes are computed once too (see offsetbox).
786
+ self._rs_best_found = {}
787
+ outer_extents = getattr(offsetbox._rs_kept, "extents", None)
788
+ offsetbox._rs_kept.extents = {}
789
+ try:
790
+ # update the location and size of the legend. This needs to
791
+ # be done in any case to clip the figure right.
792
+ bbox = self._legend_box.get_window_extent(renderer)
793
+ self.legendPatch.set_bounds(bbox.bounds)
794
+ self.legendPatch.set_mutation_scale(fontsize)
795
+
796
+ # self.shadow is validated in __init__
797
+ # So by here it is a bool and self._shadow_props contains any
798
+ # configs
799
+
800
+ if self.shadow:
801
+ Shadow(self.legendPatch, **self._shadow_props).draw(renderer)
802
+
803
+ self.legendPatch.draw(renderer)
804
+ self._legend_box.draw(renderer)
805
+ finally:
806
+ del self._rs_best_found
807
+ offsetbox._rs_kept.extents = outer_extents
808
+
809
+ renderer.close_group('legend')
810
+ self.stale = False
811
+
812
+ # _default_handler_map defines the default mapping between plot
813
+ # elements and the legend handlers.
814
+
815
+ _default_handler_map = {
816
+ StemContainer: legend_handler.HandlerStem(),
817
+ ErrorbarContainer: legend_handler.HandlerErrorbar(),
818
+ Line2D: legend_handler.HandlerLine2D(),
819
+ Patch: legend_handler.HandlerPatch(),
820
+ StepPatch: legend_handler.HandlerStepPatch(),
821
+ LineCollection: legend_handler.HandlerLineCollection(),
822
+ RegularPolyCollection: legend_handler.HandlerRegularPolyCollection(),
823
+ CircleCollection: legend_handler.HandlerCircleCollection(),
824
+ BarContainer: legend_handler.HandlerPatch(
825
+ update_func=legend_handler.update_from_first_child),
826
+ tuple: legend_handler.HandlerTuple(),
827
+ PatchCollection: legend_handler.HandlerPolyCollection(),
828
+ PathCollection: legend_handler.HandlerPathCollection(),
829
+ PolyCollection: legend_handler.HandlerPolyCollection()
830
+ }
831
+
832
+ # (get|set|update)_default_handler_maps are public interfaces to
833
+ # modify the default handler map.
834
+
835
+ @classmethod
836
+ def get_default_handler_map(cls):
837
+ """Return the global default handler map, shared by all legends."""
838
+ return cls._default_handler_map
839
+
840
+ @classmethod
841
+ def set_default_handler_map(cls, handler_map):
842
+ """Set the global default handler map, shared by all legends."""
843
+ cls._default_handler_map = handler_map
844
+
845
+ @classmethod
846
+ def update_default_handler_map(cls, handler_map):
847
+ """Update the global default handler map, shared by all legends."""
848
+ cls._default_handler_map.update(handler_map)
849
+
850
+ def get_legend_handler_map(self):
851
+ """Return this legend instance's handler map."""
852
+ default_handler_map = self.get_default_handler_map()
853
+ return ({**default_handler_map, **self._custom_handler_map}
854
+ if self._custom_handler_map else default_handler_map)
855
+
856
+ @staticmethod
857
+ def get_legend_handler(legend_handler_map, orig_handle):
858
+ """
859
+ Return a legend handler from *legend_handler_map* that
860
+ corresponds to *orig_handler*.
861
+
862
+ *legend_handler_map* should be a dictionary object (that is
863
+ returned by the get_legend_handler_map method).
864
+
865
+ It first checks if the *orig_handle* itself is a key in the
866
+ *legend_handler_map* and return the associated value.
867
+ Otherwise, it checks for each of the classes in its
868
+ method-resolution-order. If no matching key is found, it
869
+ returns ``None``.
870
+ """
871
+ try:
872
+ return legend_handler_map[orig_handle]
873
+ except (TypeError, KeyError): # TypeError if unhashable.
874
+ pass
875
+ for handle_type in type(orig_handle).mro():
876
+ try:
877
+ return legend_handler_map[handle_type]
878
+ except KeyError:
879
+ pass
880
+ return None
881
+
882
+ def _init_legend_box(self, handles, labels, markerfirst=True):
883
+ """
884
+ Initialize the legend_box. The legend_box is an instance of
885
+ the OffsetBox, which is packed with legend handles and
886
+ texts. Once packed, their location is calculated during the
887
+ drawing time.
888
+ """
889
+
890
+ fontsize = self._fontsize
891
+
892
+ # legend_box is a HPacker, horizontally packed with columns.
893
+ # Each column is a VPacker, vertically packed with legend items.
894
+ # Each legend item is a HPacker packed with:
895
+ # - handlebox: a DrawingArea which contains the legend handle.
896
+ # - labelbox: a TextArea which contains the legend text.
897
+
898
+ text_list = [] # the list of text instances
899
+ handle_list = [] # the list of handle instances
900
+ handles_and_labels = []
901
+
902
+ # The approximate height and descent of text. These values are
903
+ # only used for plotting the legend handle.
904
+ descent = 0.35 * fontsize * (self.handleheight - 0.7) # heuristic.
905
+ height = fontsize * self.handleheight - descent
906
+ # each handle needs to be drawn inside a box of (x, y, w, h) =
907
+ # (0, -descent, width, height). And their coordinates should
908
+ # be given in the display coordinates.
909
+
910
+ # The transformation of each handle will be automatically set
911
+ # to self.get_transform(). If the artist does not use its
912
+ # default transform (e.g., Collections), you need to
913
+ # manually set their transform to the self.get_transform().
914
+ legend_handler_map = self.get_legend_handler_map()
915
+
916
+ for orig_handle, label in zip(handles, labels):
917
+ handler = self.get_legend_handler(legend_handler_map, orig_handle)
918
+ if handler is None:
919
+ _api.warn_external(
920
+ "Legend does not support handles for "
921
+ f"{type(orig_handle).__name__} "
922
+ "instances.\nA proxy artist may be used "
923
+ "instead.\nSee: https://matplotlib.org/"
924
+ "stable/users/explain/axes/legend_guide.html"
925
+ "#controlling-the-legend-entries")
926
+ # No handle for this artist, so we just defer to None.
927
+ handle_list.append(None)
928
+ else:
929
+ textbox = TextArea(label, multilinebaseline=True,
930
+ textprops=dict(
931
+ verticalalignment='baseline',
932
+ horizontalalignment='left',
933
+ fontproperties=self.prop))
934
+ handlebox = DrawingArea(width=self.handlelength * fontsize,
935
+ height=height,
936
+ xdescent=0., ydescent=descent)
937
+
938
+ text_list.append(textbox._text)
939
+ # Create the artist for the legend which represents the
940
+ # original artist/handle.
941
+ handle_list.append(handler.legend_artist(self, orig_handle,
942
+ fontsize, handlebox))
943
+ handles_and_labels.append((handlebox, textbox))
944
+
945
+ columnbox = []
946
+ # array_split splits n handles_and_labels into ncols columns, with the
947
+ # first n%ncols columns having an extra entry. filter(len, ...)
948
+ # handles the case where n < ncols: the last ncols-n columns are empty
949
+ # and get filtered out.
950
+ for handles_and_labels_column in filter(
951
+ len, np.array_split(handles_and_labels, self._ncols)):
952
+ # pack handlebox and labelbox into itembox
953
+ itemboxes = [HPacker(pad=0,
954
+ sep=self.handletextpad * fontsize,
955
+ children=[h, t] if markerfirst else [t, h],
956
+ align="baseline")
957
+ for h, t in handles_and_labels_column]
958
+ # pack columnbox
959
+ alignment = "baseline" if markerfirst else "right"
960
+ columnbox.append(VPacker(pad=0,
961
+ sep=self.labelspacing * fontsize,
962
+ align=alignment,
963
+ children=itemboxes))
964
+
965
+ mode = "expand" if self._mode == "expand" else "fixed"
966
+ sep = self.columnspacing * fontsize
967
+ self._legend_handle_box = HPacker(pad=0,
968
+ sep=sep, align="baseline",
969
+ mode=mode,
970
+ children=columnbox)
971
+ self._legend_title_box = TextArea("")
972
+ self._legend_box = VPacker(pad=self.borderpad * fontsize,
973
+ sep=self.labelspacing * fontsize,
974
+ align=self._alignment,
975
+ children=[self._legend_title_box,
976
+ self._legend_handle_box])
977
+ self._legend_box.set_figure(self.get_figure(root=False))
978
+ self._legend_box.axes = self.axes
979
+ self.texts = text_list
980
+ self.legend_handles = handle_list
981
+
982
+ def _auto_legend_data(self, renderer):
983
+ """
984
+ Return display coordinates for hit testing for "best" positioning.
985
+
986
+ Returns
987
+ -------
988
+ bboxes
989
+ List of bounding boxes of all patches.
990
+ lines
991
+ List of `.Path` corresponding to each line.
992
+ offsets
993
+ List of (x, y) offsets of all collection.
994
+ """
995
+ assert self.isaxes # always holds, as this is only called internally
996
+ bboxes = []
997
+ lines = []
998
+ offsets = []
999
+ for artist in self.parent._children:
1000
+ if isinstance(artist, Line2D):
1001
+ lines.append(
1002
+ artist.get_transform().transform_path(artist.get_path()))
1003
+ elif isinstance(artist, Rectangle):
1004
+ bboxes.append(
1005
+ artist.get_bbox().transformed(artist.get_data_transform()))
1006
+ elif isinstance(artist, Patch):
1007
+ lines.append(
1008
+ artist.get_transform().transform_path(artist.get_path()))
1009
+ elif isinstance(artist, PolyCollection):
1010
+ lines.extend(artist.get_transform().transform_path(path)
1011
+ for path in artist.get_paths())
1012
+ elif isinstance(artist, Collection):
1013
+ transform, transOffset, hoffsets, _ = artist._prepare_points()
1014
+ if len(hoffsets):
1015
+ offsets.extend(transOffset.transform(hoffsets))
1016
+ elif isinstance(artist, Text):
1017
+ bboxes.append(artist.get_window_extent(renderer))
1018
+
1019
+ return bboxes, lines, offsets
1020
+
1021
+ def get_children(self):
1022
+ # docstring inherited
1023
+ return [self._legend_box, self.get_frame()]
1024
+
1025
+ def get_frame(self):
1026
+ """Return the `~.patches.Rectangle` used to frame the legend."""
1027
+ return self.legendPatch
1028
+
1029
+ def get_lines(self):
1030
+ r"""Return the list of `~.lines.Line2D`\s in the legend."""
1031
+ return [h for h in self.legend_handles if isinstance(h, Line2D)]
1032
+
1033
+ def get_patches(self):
1034
+ r"""Return the list of `~.patches.Patch`\s in the legend."""
1035
+ return silent_list('Patch',
1036
+ [h for h in self.legend_handles
1037
+ if isinstance(h, Patch)])
1038
+
1039
+ def get_texts(self):
1040
+ r"""Return the list of `~.text.Text`\s in the legend."""
1041
+ return silent_list('Text', self.texts)
1042
+
1043
+ def set_alignment(self, alignment):
1044
+ """
1045
+ Set the alignment of the legend title and the box of entries.
1046
+
1047
+ The entries are aligned as a single block, so that markers always
1048
+ lined up.
1049
+
1050
+ Parameters
1051
+ ----------
1052
+ alignment : {'center', 'left', 'right'}.
1053
+
1054
+ """
1055
+ _api.check_in_list(["center", "left", "right"], alignment=alignment)
1056
+ self._alignment = alignment
1057
+ self._legend_box.align = alignment
1058
+
1059
+ def get_alignment(self):
1060
+ """Get the alignment value of the legend box"""
1061
+ return self._legend_box.align
1062
+
1063
+ def set_title(self, title, prop=None):
1064
+ """
1065
+ Set legend title and title style.
1066
+
1067
+ Parameters
1068
+ ----------
1069
+ title : str
1070
+ The legend title.
1071
+
1072
+ prop : `.font_manager.FontProperties` or `str` or `pathlib.Path`
1073
+ The font properties of the legend title.
1074
+ If a `str`, it is interpreted as a fontconfig pattern parsed by
1075
+ `.FontProperties`. If a `pathlib.Path`, it is interpreted as the
1076
+ absolute path to a font file.
1077
+
1078
+ """
1079
+ self._legend_title_box._text.set_text(title)
1080
+ if title:
1081
+ self._legend_title_box._text.set_visible(True)
1082
+ self._legend_title_box.set_visible(True)
1083
+ else:
1084
+ self._legend_title_box._text.set_visible(False)
1085
+ self._legend_title_box.set_visible(False)
1086
+
1087
+ if prop is not None:
1088
+ self._legend_title_box._text.set_fontproperties(prop)
1089
+
1090
+ self.stale = True
1091
+
1092
+ def get_title(self):
1093
+ """Return the `.Text` instance for the legend title."""
1094
+ return self._legend_title_box._text
1095
+
1096
+ def get_window_extent(self, renderer=None):
1097
+ # docstring inherited
1098
+ if renderer is None:
1099
+ renderer = self.get_figure(root=True)._get_renderer()
1100
+ return self._legend_box.get_window_extent(renderer=renderer)
1101
+
1102
+ def get_tightbbox(self, renderer=None):
1103
+ # docstring inherited
1104
+ return self._legend_box.get_window_extent(renderer)
1105
+
1106
+ def get_frame_on(self):
1107
+ """Get whether the legend box patch is drawn."""
1108
+ return self.legendPatch.get_visible()
1109
+
1110
+ def set_frame_on(self, b):
1111
+ """
1112
+ Set whether the legend box patch is drawn.
1113
+
1114
+ Parameters
1115
+ ----------
1116
+ b : bool
1117
+ """
1118
+ self.legendPatch.set_visible(b)
1119
+ self.stale = True
1120
+
1121
+ draw_frame = set_frame_on # Backcompat alias.
1122
+
1123
+ def get_bbox_to_anchor(self):
1124
+ """Return the bbox that the legend will be anchored to."""
1125
+ if self._bbox_to_anchor is None:
1126
+ return self.parent.bbox
1127
+ else:
1128
+ return self._bbox_to_anchor
1129
+
1130
+ def set_bbox_to_anchor(self, bbox, transform=None):
1131
+ """
1132
+ Set the bbox that the legend will be anchored to.
1133
+
1134
+ Parameters
1135
+ ----------
1136
+ bbox : `~matplotlib.transforms.BboxBase` or tuple
1137
+ The bounding box can be specified in the following ways:
1138
+
1139
+ - A `.BboxBase` instance
1140
+ - A tuple of ``(left, bottom, width, height)`` in the given
1141
+ transform (normalized axes coordinate if None)
1142
+ - A tuple of ``(left, bottom)`` where the width and height will be
1143
+ assumed to be zero.
1144
+ - *None*, to remove the bbox anchoring, and use the parent bbox.
1145
+
1146
+ transform : `~matplotlib.transforms.Transform`, optional
1147
+ A transform to apply to the bounding box. If not specified, this
1148
+ will use a transform to the bounding box of the parent.
1149
+ """
1150
+ if bbox is None:
1151
+ self._bbox_to_anchor = None
1152
+ return
1153
+ elif isinstance(bbox, BboxBase):
1154
+ self._bbox_to_anchor = bbox
1155
+ else:
1156
+ try:
1157
+ l = len(bbox)
1158
+ except TypeError as err:
1159
+ raise ValueError(f"Invalid bbox: {bbox}") from err
1160
+
1161
+ if l == 2:
1162
+ bbox = [bbox[0], bbox[1], 0, 0]
1163
+
1164
+ self._bbox_to_anchor = Bbox.from_bounds(*bbox)
1165
+
1166
+ if transform is None:
1167
+ transform = BboxTransformTo(self.parent.bbox)
1168
+
1169
+ self._bbox_to_anchor = TransformedBbox(self._bbox_to_anchor,
1170
+ transform)
1171
+ self.stale = True
1172
+
1173
+ def _get_anchored_bbox(self, loc, bbox, parentbbox, renderer):
1174
+ """
1175
+ Place the *bbox* inside the *parentbbox* according to a given
1176
+ location code. Return the (x, y) coordinate of the bbox.
1177
+
1178
+ Parameters
1179
+ ----------
1180
+ loc : int
1181
+ A location code in range(1, 11). This corresponds to the possible
1182
+ values for ``self._loc``, excluding "best".
1183
+ bbox : `~matplotlib.transforms.Bbox`
1184
+ bbox to be placed, in display coordinates.
1185
+ parentbbox : `~matplotlib.transforms.Bbox`
1186
+ A parent box which will contain the bbox, in display coordinates.
1187
+ """
1188
+ pad = self.borderaxespad * renderer.points_to_pixels(self._fontsize)
1189
+ return offsetbox._get_anchored_bbox(
1190
+ loc, bbox, parentbbox,
1191
+ pad, pad)
1192
+
1193
+ def _rs_best_position(self, bbox, width, height, renderer,
1194
+ bboxes, lines, offsets):
1195
+ """
1196
+ The position the loop of `_find_best_position` chooses, with the
1197
+ badness of all candidates computed by one call into the Rust core;
1198
+ None if the arguments are not arrays it takes (the loop then
1199
+ decides).
1200
+
1201
+ The loop stops at the first candidate without badness and otherwise
1202
+ takes the first one with the least: both are the first candidate
1203
+ with the least badness.
1204
+ """
1205
+ try:
1206
+ if len(offsets):
1207
+ offsets = np.asarray(offsets)
1208
+ if (offsets.ndim != 2 or offsets.shape[1] != 2
1209
+ or offsets.dtype.kind not in "fiu"):
1210
+ return None
1211
+ offsets = np.ascontiguousarray(offsets, dtype=float)
1212
+ else:
1213
+ offsets = np.zeros((0, 2))
1214
+ if len(bboxes):
1215
+ bboxes = np.asarray([np.array(x) for x in bboxes],
1216
+ dtype=float).reshape(-1, 2, 2)
1217
+ else:
1218
+ bboxes = np.zeros((0, 2, 2))
1219
+ positions = []
1220
+ boxes = []
1221
+ for idx in range(1, len(self.codes)):
1222
+ l, b = self._get_anchored_bbox(idx, bbox,
1223
+ self.get_bbox_to_anchor(),
1224
+ renderer)
1225
+ positions.append((l, b))
1226
+ boxes.append(Bbox.from_bounds(l, b, width, height).extents)
1227
+ badness = _path.legend_badness(
1228
+ np.asarray(boxes, dtype=float).reshape(-1, 4),
1229
+ list(lines), offsets, bboxes)
1230
+ except (TypeError, ValueError):
1231
+ return None
1232
+ return positions[min(range(len(badness)), key=badness.__getitem__)]
1233
+
1234
+ def _find_best_position(self, width, height, renderer):
1235
+ """Determine the best location to place the legend."""
1236
+ assert self.isaxes # always holds, as this is only called internally
1237
+
1238
+ # matplotlib_rs: within one Legend.draw (see there).
1239
+ found = self.__dict__.get("_rs_best_found")
1240
+ key = (width, height, id(renderer))
1241
+ if found is not None and key in found:
1242
+ return found[key]
1243
+
1244
+ start_time = time.perf_counter()
1245
+
1246
+ bboxes, lines, offsets = self._auto_legend_data(renderer)
1247
+
1248
+ bbox = Bbox.from_bounds(0, 0, width, height)
1249
+
1250
+ # matplotlib_rs: the badness of every candidate in one call.
1251
+ best = self._rs_best_position(bbox, width, height, renderer,
1252
+ bboxes, lines, offsets)
1253
+ if best is not None:
1254
+ l, b = best
1255
+ else:
1256
+ candidates = []
1257
+ for idx in range(1, len(self.codes)):
1258
+ l, b = self._get_anchored_bbox(idx, bbox,
1259
+ self.get_bbox_to_anchor(),
1260
+ renderer)
1261
+ legendBox = Bbox.from_bounds(l, b, width, height)
1262
+ # XXX TODO: If markers are present, it would be good to take
1263
+ # them into account when checking vertex overlaps in the next
1264
+ # line.
1265
+ badness = (sum(legendBox.count_contains(line.vertices)
1266
+ for line in lines)
1267
+ + legendBox.count_contains(offsets)
1268
+ + legendBox.count_overlaps(bboxes)
1269
+ + sum(line.intersects_bbox(legendBox, filled=False)
1270
+ for line in lines))
1271
+ # Include the index to favor lower codes in case of a tie.
1272
+ candidates.append((badness, idx, (l, b)))
1273
+ if badness == 0:
1274
+ break
1275
+
1276
+ _, _, (l, b) = min(candidates)
1277
+
1278
+ if self._loc_used_default and time.perf_counter() - start_time > 1:
1279
+ _api.warn_external(
1280
+ 'Creating legend with loc="best" can be slow with large '
1281
+ 'amounts of data.')
1282
+
1283
+ if found is not None:
1284
+ found[key] = (l, b)
1285
+ return l, b
1286
+
1287
+ def contains(self, mouseevent):
1288
+ return self.legendPatch.contains(mouseevent)
1289
+
1290
+ def set_draggable(self, state, use_blit=False, update='loc'):
1291
+ """
1292
+ Enable or disable mouse dragging support of the legend.
1293
+
1294
+ Parameters
1295
+ ----------
1296
+ state : bool
1297
+ Whether mouse dragging is enabled.
1298
+ use_blit : bool, optional
1299
+ Use blitting for faster image composition. For details see
1300
+ :ref:`func-animation`.
1301
+ update : {'loc', 'bbox'}, optional
1302
+ The legend parameter to be changed when dragged:
1303
+
1304
+ - 'loc': update the *loc* parameter of the legend
1305
+ - 'bbox': update the *bbox_to_anchor* parameter of the legend
1306
+
1307
+ Returns
1308
+ -------
1309
+ `.DraggableLegend` or *None*
1310
+ If *state* is ``True`` this returns the `.DraggableLegend` helper
1311
+ instance. Otherwise this returns *None*.
1312
+ """
1313
+ if state:
1314
+ if self._draggable is None:
1315
+ self._draggable = DraggableLegend(self,
1316
+ use_blit,
1317
+ update=update)
1318
+ else:
1319
+ if self._draggable is not None:
1320
+ self._draggable.disconnect()
1321
+ self._draggable = None
1322
+ return self._draggable
1323
+
1324
+ def get_draggable(self):
1325
+ """Return ``True`` if the legend is draggable, ``False`` otherwise."""
1326
+ return self._draggable is not None
1327
+
1328
+
1329
+ # Helper functions to parse legend arguments for both `figure.legend` and
1330
+ # `axes.legend`:
1331
+ def _get_legend_handles(axs, legend_handler_map=None):
1332
+ """Yield artists that can be used as handles in a legend."""
1333
+ from matplotlib_rs.axes._base_rs import _existing_children, _pending_children
1334
+ handles_original = []
1335
+ for ax in axs:
1336
+ # Of artists not created yet, only those with a label to show are
1337
+ # created (the others would be skipped below).
1338
+ for pending in _pending_children(ax):
1339
+ pending.make_labelled()
1340
+ handles_original += [
1341
+ *(a for a in _existing_children(ax)
1342
+ if isinstance(a, (Line2D, Patch, Collection, Text))),
1343
+ *ax.containers]
1344
+ # support parasite Axes:
1345
+ if hasattr(ax, 'parasites'):
1346
+ for axx in ax.parasites:
1347
+ handles_original += [
1348
+ *(a for a in axx._children
1349
+ if isinstance(a, (Line2D, Patch, Collection, Text))),
1350
+ *axx.containers]
1351
+
1352
+ handler_map = {**Legend.get_default_handler_map(),
1353
+ **(legend_handler_map or {})}
1354
+ has_handler = Legend.get_legend_handler
1355
+ for handle in handles_original:
1356
+ label = handle.get_label()
1357
+ if label != '_nolegend_' and has_handler(handler_map, handle):
1358
+ yield handle
1359
+ elif (label and not label.startswith('_') and
1360
+ not has_handler(handler_map, handle)):
1361
+ _api.warn_external(
1362
+ "Legend does not support handles for "
1363
+ f"{type(handle).__name__} "
1364
+ "instances.\nSee: https://matplotlib.org/stable/"
1365
+ "tutorials/intermediate/legend_guide.html"
1366
+ "#implementing-a-custom-legend-handler")
1367
+ continue
1368
+
1369
+
1370
+ def _get_legend_handles_labels(axs, legend_handler_map=None):
1371
+ """Return handles and labels for legend."""
1372
+ handles = []
1373
+ labels = []
1374
+ for handle in _get_legend_handles(axs, legend_handler_map):
1375
+ label = handle.get_label()
1376
+ if label and not label.startswith('_'):
1377
+ handles.append(handle)
1378
+ labels.append(label)
1379
+ return handles, labels
1380
+
1381
+
1382
+ def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs):
1383
+ """
1384
+ Get the handles and labels from the calls to either ``figure.legend``
1385
+ or ``axes.legend``.
1386
+
1387
+ The parser is a bit involved because we support::
1388
+
1389
+ legend()
1390
+ legend(labels)
1391
+ legend(handles, labels)
1392
+ legend(labels=labels)
1393
+ legend(handles=handles)
1394
+ legend(handles=handles, labels=labels)
1395
+
1396
+ The behavior for a mixture of positional and keyword handles and labels
1397
+ is undefined and raises an error.
1398
+
1399
+ Parameters
1400
+ ----------
1401
+ axs : list of `.Axes`
1402
+ If handles are not given explicitly, the artists in these Axes are
1403
+ used as handles.
1404
+ *args : tuple
1405
+ Positional parameters passed to ``legend()``.
1406
+ handles
1407
+ The value of the keyword argument ``legend(handles=...)``, or *None*
1408
+ if that keyword argument was not used.
1409
+ labels
1410
+ The value of the keyword argument ``legend(labels=...)``, or *None*
1411
+ if that keyword argument was not used.
1412
+ **kwargs
1413
+ All other keyword arguments passed to ``legend()``.
1414
+
1415
+ Returns
1416
+ -------
1417
+ handles : list of (`.Artist` or tuple of `.Artist`)
1418
+ The legend handles.
1419
+ labels : list of str
1420
+ The legend labels.
1421
+ kwargs : dict
1422
+ *kwargs* with keywords handles and labels removed.
1423
+
1424
+ """
1425
+ log = logging.getLogger(__name__)
1426
+
1427
+ handlers = kwargs.get('handler_map')
1428
+
1429
+ if (handles is not None or labels is not None) and args:
1430
+ raise TypeError("When passing handles and labels, they must both be "
1431
+ "passed positionally or both as keywords.")
1432
+
1433
+ if (hasattr(handles, "__len__") and
1434
+ hasattr(labels, "__len__") and
1435
+ len(handles) != len(labels)):
1436
+ _api.warn_external(f"Mismatched number of handles and labels: "
1437
+ f"len(handles) = {len(handles)} "
1438
+ f"len(labels) = {len(labels)}")
1439
+ # if got both handles and labels as kwargs, make same length
1440
+ if handles is not None and labels is not None:
1441
+ handles, labels = zip(*zip(handles, labels))
1442
+
1443
+ elif handles is not None and labels is None:
1444
+ labels = [handle.get_label() for handle in handles]
1445
+
1446
+ elif labels is not None and handles is None:
1447
+ # Get as many handles as there are labels.
1448
+ handles = [handle for handle, label
1449
+ in zip(_get_legend_handles(axs, handlers), labels)]
1450
+
1451
+ elif len(args) == 0: # 0 args: automatically detect labels and handles.
1452
+ handles, labels = _get_legend_handles_labels(axs, handlers)
1453
+ if not handles:
1454
+ _api.warn_external(
1455
+ "No artists with labels found to put in legend. Note that "
1456
+ "artists whose label start with an underscore are ignored "
1457
+ "when legend() is called with no argument.")
1458
+
1459
+ elif len(args) == 1: # 1 arg: user defined labels, automatic handle detection.
1460
+ labels, = args
1461
+ if any(isinstance(l, Artist) for l in labels):
1462
+ raise TypeError("A single argument passed to legend() must be a "
1463
+ "list of labels, but found an Artist in there.")
1464
+
1465
+ # Get as many handles as there are labels.
1466
+ handles = [handle for handle, label
1467
+ in zip(_get_legend_handles(axs, handlers), labels)]
1468
+
1469
+ elif len(args) == 2: # 2 args: user defined handles and labels.
1470
+ handles, labels = args[:2]
1471
+ if (hasattr(handles, "__len__") and hasattr(labels, "__len__")
1472
+ and len(handles) != len(labels)):
1473
+ _api.warn_external(f"Mismatched number of handles and labels: "
1474
+ f"len(handles) = {len(handles)} "
1475
+ f"len(labels) = {len(labels)}")
1476
+
1477
+ else:
1478
+ raise _api.nargs_error('legend', '0-2', len(args))
1479
+
1480
+ return handles, labels, kwargs