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,2711 @@
1
+ # Vendored from matplotlib 3.11 (see licenses/LICENSE_MATPLOTLIB), adapted for matplotlib_rs.
2
+ """
3
+ Classes for the efficient drawing of large collections of objects that
4
+ share most properties, e.g., a large number of line segments or
5
+ polygons.
6
+
7
+ The classes are not meant to be as flexible as their single element
8
+ counterparts (e.g., you may not be able to select all line styles) but
9
+ they are meant to be fast for common use cases (e.g., a large set of solid
10
+ line segments).
11
+ """
12
+
13
+ import itertools
14
+ import functools
15
+ import math
16
+ from numbers import Number, Real
17
+ import warnings
18
+
19
+ import numpy as np
20
+
21
+ import matplotlib_rs as mpl
22
+ from . import (_api, _path, artist, cbook, colorizer as mcolorizer, colors as mcolors,
23
+ _docstring, hatch as mhatch, lines as mlines, path as mpath, transforms)
24
+ from ._enums import JoinStyle, CapStyle
25
+
26
+
27
+ # "color" is excluded; it is a compound setter, and its docstring differs
28
+ # in LineCollection.
29
+ @_api.define_aliases({
30
+ "antialiased": ["antialiaseds", "aa"],
31
+ "edgecolor": ["edgecolors", "ec"],
32
+ "facecolor": ["facecolors", "fc"],
33
+ "linestyle": ["linestyles", "dashes", "ls"],
34
+ "linewidth": ["linewidths", "lw"],
35
+ "offset_transform": ["transOffset"],
36
+ })
37
+ class Collection(mcolorizer.ColorizingArtist):
38
+ r"""
39
+ Base class for Collections. Must be subclassed to be usable.
40
+
41
+ A Collection represents a sequence of `.Patch`\es that can be drawn
42
+ more efficiently together than individually. For example, when a single
43
+ path is being drawn repeatedly at different offsets, the renderer can
44
+ typically execute a ``draw_marker()`` call much more efficiently than a
45
+ series of repeated calls to ``draw_path()`` with the offsets put in
46
+ one-by-one.
47
+
48
+ Most properties of a collection can be configured per-element. Therefore,
49
+ Collections have "plural" versions of many of the properties of a `.Patch`
50
+ (e.g. `.Collection.get_paths` instead of `.Patch.get_path`). Exceptions are
51
+ the *zorder*, *hatch*, *pickradius*, *capstyle* and *joinstyle* properties,
52
+ which can only be set globally for the whole collection.
53
+
54
+ Besides these exceptions, all properties can be specified as single values
55
+ (applying to all elements) or sequences of values. The property of the
56
+ ``i``\th element of the collection is::
57
+
58
+ prop[i % len(prop)]
59
+
60
+ Each Collection can optionally be used as its own `.ScalarMappable` by
61
+ passing the *norm* and *cmap* parameters to its constructor. If the
62
+ Collection's `.ScalarMappable` matrix ``_A`` has been set (via a call
63
+ to `.Collection.set_array`), then at draw time this internal scalar
64
+ mappable will be used to set the ``facecolors`` and ``edgecolors``,
65
+ ignoring those that were manually passed in.
66
+ """
67
+ #: Either a list of 3x3 arrays or an Nx3x3 array (representing N
68
+ #: transforms), suitable for the `all_transforms` argument to
69
+ #: `~matplotlib.backend_bases.RendererBase.draw_path_collection`;
70
+ #: each 3x3 array is used to initialize an
71
+ #: `~matplotlib.transforms.Affine2D` object.
72
+ #: Each kind of collection defines this based on its arguments.
73
+ _transforms = np.empty((0, 3, 3))
74
+
75
+ # Whether to draw an edge by default. Set on a
76
+ # subclass-by-subclass basis.
77
+ _edge_default = False
78
+
79
+ @_docstring.interpd
80
+ def __init__(self, *,
81
+ edgecolors=None,
82
+ facecolors=None,
83
+ hatchcolors=None,
84
+ linewidths=None,
85
+ linestyles='solid',
86
+ capstyle=None,
87
+ joinstyle=None,
88
+ antialiaseds=None,
89
+ offsets=None,
90
+ offset_transform=None,
91
+ norm=None, # optional for ScalarMappable
92
+ cmap=None, # ditto
93
+ colorizer=None,
94
+ pickradius=5.0,
95
+ hatch=None,
96
+ urls=None,
97
+ zorder=1,
98
+ **kwargs
99
+ ):
100
+ """
101
+ Parameters
102
+ ----------
103
+ edgecolors : :mpltype:`color` or list of colors, default: :rc:`patch.edgecolor`
104
+ Edge color for each patch making up the collection. The special
105
+ value 'face' can be passed to make the edgecolor match the
106
+ facecolor.
107
+ facecolors : :mpltype:`color` or list of colors, default: :rc:`patch.facecolor`
108
+ Face color for each patch making up the collection.
109
+ hatchcolors : :mpltype:`color` or list of colors, default: :rc:`hatch.color`
110
+ Hatch color for each patch making up the collection. The color
111
+ can be set to the special value 'edge' to make the hatchcolor match the
112
+ edgecolor.
113
+ linewidths : float or list of floats, default: :rc:`patch.linewidth`
114
+ Line width for each patch making up the collection.
115
+ linestyles : str or tuple or list thereof, default: 'solid'
116
+ Valid strings are ['solid', 'dashed', 'dashdot', 'dotted', '-',
117
+ '--', '-.', ':']. Dash tuples should be of the form::
118
+
119
+ (offset, onoffseq),
120
+
121
+ where *onoffseq* is an even length tuple of on and off ink lengths
122
+ in points. For examples, see
123
+ :doc:`/gallery/lines_bars_and_markers/linestyles`.
124
+ capstyle : `.CapStyle`-like, default: 'butt'
125
+ Style to use for capping lines for all paths in the collection.
126
+ Allowed values are %(CapStyle)s.
127
+ joinstyle : `.JoinStyle`-like, default: 'round'
128
+ Style to use for joining lines for all paths in the collection.
129
+ Allowed values are %(JoinStyle)s.
130
+ antialiaseds : bool or list of bool, default: :rc:`patch.antialiased`
131
+ Whether each patch in the collection should be drawn with
132
+ antialiasing.
133
+ offsets : (float, float) or list thereof, default: (0, 0)
134
+ A vector by which to translate each patch after rendering (default
135
+ is no translation). The translation is performed in screen (pixel)
136
+ coordinates (i.e. after the Artist's transform is applied).
137
+ offset_transform : `~.Transform`, default: `.IdentityTransform`
138
+ A single transform which will be applied to each *offsets* vector
139
+ before it is used.
140
+ cmap, norm
141
+ Data normalization and colormapping parameters. See
142
+ `.ScalarMappable` for a detailed description.
143
+ hatch : str, optional
144
+ Hatching pattern to use in filled paths, if any. Valid strings are
145
+ ['/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*']. See
146
+ :doc:`/gallery/shapes_and_collections/hatch_style_reference` for
147
+ the meaning of each hatch type.
148
+ pickradius : float, default: 5.0
149
+ If ``pickradius <= 0``, then `.Collection.contains` will return
150
+ ``True`` whenever the test point is inside of one of the polygons
151
+ formed by the control points of a Path in the Collection. On the
152
+ other hand, if it is greater than 0, then we instead check if the
153
+ test point is contained in a stroke of width ``2*pickradius``
154
+ following any of the Paths in the Collection.
155
+ urls : list of str, default: None
156
+ A URL for each patch to link to once drawn. Currently only works
157
+ for the SVG backend. See :doc:`/gallery/misc/hyperlinks_sgskip` for
158
+ examples.
159
+ zorder : float, default: 1
160
+ The drawing order, shared by all Patches in the Collection. See
161
+ :doc:`/gallery/misc/zorder_demo` for all defaults and examples.
162
+ **kwargs
163
+ Remaining keyword arguments will be used to set properties as
164
+ ``Collection.set_{key}(val)`` for each key-value pair in *kwargs*.
165
+ """
166
+
167
+ super().__init__(self._get_colorizer(cmap, norm, colorizer))
168
+ # list of un-scaled dash patterns
169
+ # this is needed scaling the dash pattern by linewidth
170
+ self._us_linestyles = [(0, None)]
171
+ # list of dash patterns
172
+ self._linestyles = [(0, None)]
173
+ # list of unbroadcast/scaled linewidths
174
+ self._us_lw = [0]
175
+ self._linewidths = [0]
176
+
177
+ self._gapcolor = None # Currently only used by LineCollection.
178
+
179
+ # Flags set by _set_mappable_flags: are colors from mapping an array?
180
+ self._face_is_mapped = None
181
+ self._edge_is_mapped = None
182
+ self._mapped_colors = None # calculated in update_scalarmappable
183
+ self._hatch_linewidth = mpl.rcParams['hatch.linewidth']
184
+ self.set_facecolor(facecolors)
185
+ self.set_edgecolor(edgecolors)
186
+ self.set_linewidth(linewidths)
187
+ self.set_linestyle(linestyles)
188
+ self.set_antialiased(antialiaseds)
189
+ self.set_pickradius(pickradius)
190
+ self.set_urls(urls)
191
+ self.set_hatch(hatch)
192
+ self.set_hatchcolor(hatchcolors)
193
+ self.set_zorder(zorder)
194
+
195
+ if capstyle:
196
+ self.set_capstyle(capstyle)
197
+ else:
198
+ self._capstyle = None
199
+
200
+ if joinstyle:
201
+ self.set_joinstyle(joinstyle)
202
+ else:
203
+ self._joinstyle = None
204
+
205
+ if offsets is not None:
206
+ offsets = np.asanyarray(offsets, float)
207
+ # Broadcast (2,) -> (1, 2) but nothing else.
208
+ if offsets.shape == (2,):
209
+ offsets = offsets[None, :]
210
+
211
+ self._offsets = offsets
212
+ self._offset_transform = offset_transform
213
+
214
+ self._path_effects = None
215
+ self._internal_update(kwargs)
216
+ self._paths = None
217
+
218
+ def get_paths(self):
219
+ return self._paths
220
+
221
+ def set_paths(self, paths):
222
+ self._paths = paths
223
+ self.stale = True
224
+
225
+ def get_transforms(self):
226
+ return self._transforms
227
+
228
+ def get_offset_transform(self):
229
+ """Return the `.Transform` instance used by this artist offset."""
230
+ if self._offset_transform is None:
231
+ self._offset_transform = transforms.IdentityTransform()
232
+ elif (not isinstance(self._offset_transform, transforms.Transform)
233
+ and hasattr(self._offset_transform, '_as_mpl_transform')):
234
+ self._offset_transform = \
235
+ self._offset_transform._as_mpl_transform(self.axes)
236
+ return self._offset_transform
237
+
238
+ def set_offset_transform(self, offset_transform):
239
+ """
240
+ Set the artist offset transform.
241
+
242
+ Parameters
243
+ ----------
244
+ offset_transform : `.Transform`
245
+ """
246
+ self._offset_transform = offset_transform
247
+
248
+ def get_datalim(self, transData):
249
+ # Calculate the data limits and return them as a `.Bbox`.
250
+ #
251
+ # This operation depends on the transforms for the data in the
252
+ # collection and whether the collection has offsets:
253
+ #
254
+ # 1. offsets = None, transform child of transData: use the paths for
255
+ # the automatic limits (i.e. for LineCollection in streamline).
256
+ # 2. offsets != None: offset_transform is child of transData:
257
+ #
258
+ # a. transform is child of transData: use the path + offset for
259
+ # limits (i.e for bar).
260
+ # b. transform is not a child of transData: just use the offsets
261
+ # for the limits (i.e. for scatter)
262
+ #
263
+ # 3. otherwise return a null Bbox.
264
+
265
+ transform = self.get_transform()
266
+ offset_trf = self.get_offset_transform()
267
+ if not (isinstance(offset_trf, transforms.IdentityTransform)
268
+ or offset_trf.contains_branch(transData)):
269
+ # if the offsets are in some coords other than data,
270
+ # then don't use them for autoscaling.
271
+ return transforms.Bbox.null()
272
+
273
+ paths = self.get_paths()
274
+ if not len(paths):
275
+ # No paths to transform
276
+ return transforms.Bbox.null()
277
+
278
+ if not transform.is_affine:
279
+ paths = [transform.transform_path_non_affine(p) for p in paths]
280
+ # Don't convert transform to transform.get_affine() here because
281
+ # we may have transform.contains_branch(transData) but not
282
+ # transforms.get_affine().contains_branch(transData). But later,
283
+ # be careful to only apply the affine part that remains.
284
+
285
+ offsets = self.get_offsets()
286
+
287
+ if any(transform.contains_branch_separately(transData)):
288
+ # collections that are just in data units (like quiver)
289
+ # can properly have the axes limits set by their shape +
290
+ # offset. LineCollections that have no offsets can
291
+ # also use this algorithm (like streamplot).
292
+ if isinstance(offsets, np.ma.MaskedArray):
293
+ offsets = offsets.filled(np.nan)
294
+ # get_path_collection_extents handles nan but not masked arrays
295
+ data_trf = transform.get_affine() - transData
296
+ if not data_trf.is_affine:
297
+ paths = [data_trf.transform_path_non_affine(p) for p in paths]
298
+ return mpath.get_path_collection_extents(
299
+ data_trf.get_affine(), paths,
300
+ self.get_transforms(),
301
+ offset_trf.transform_non_affine(offsets),
302
+ offset_trf.get_affine().frozen())
303
+
304
+ # NOTE: None is the default case where no offsets were passed in
305
+ if self._offsets is not None:
306
+ # this is for collections that have their paths (shapes)
307
+ # in physical, axes-relative, or figure-relative units
308
+ # (i.e. like scatter). We can't uniquely set limits based on
309
+ # those shapes, so we just set the limits based on their
310
+ # location.
311
+ offsets = (offset_trf - transData).transform(offsets)
312
+ # note A-B means A B^{-1}
313
+ offsets = np.ma.masked_invalid(offsets)
314
+ if not offsets.mask.all():
315
+ bbox = transforms.Bbox.null()
316
+ bbox.update_from_data_xy(offsets)
317
+ return bbox
318
+ return transforms.Bbox.null()
319
+
320
+ def get_window_extent(self, renderer=None):
321
+ # TODO: check to ensure that this does not fail for
322
+ # cases other than scatter plot legend
323
+ return self.get_datalim(transforms.IdentityTransform())
324
+
325
+ def _prepare_points(self):
326
+ # Helper for drawing and hit testing.
327
+
328
+ transform = self.get_transform()
329
+ offset_trf = self.get_offset_transform()
330
+ offsets = self.get_offsets()
331
+ paths = self.get_paths()
332
+
333
+ if self.have_units():
334
+ paths = []
335
+ for path in self.get_paths():
336
+ vertices = path.vertices
337
+ xs, ys = vertices[:, 0], vertices[:, 1]
338
+ xs = self.convert_xunits(xs)
339
+ ys = self.convert_yunits(ys)
340
+ paths.append(mpath.Path(np.column_stack([xs, ys]), path.codes))
341
+ xs = self.convert_xunits(offsets[:, 0])
342
+ ys = self.convert_yunits(offsets[:, 1])
343
+ offsets = np.ma.column_stack([xs, ys])
344
+
345
+ if not transform.is_affine:
346
+ paths = [transform.transform_path_non_affine(path)
347
+ for path in paths]
348
+ transform = transform.get_affine()
349
+ if not offset_trf.is_affine:
350
+ offsets = offset_trf.transform_non_affine(offsets)
351
+ # This might have changed an ndarray into a masked array.
352
+ offset_trf = offset_trf.get_affine()
353
+
354
+ if isinstance(offsets, np.ma.MaskedArray):
355
+ offsets = offsets.filled(np.nan)
356
+ # Changing from a masked array to nan-filled ndarray
357
+ # is probably most efficient at this point.
358
+
359
+ return transform, offset_trf, offsets, paths
360
+
361
+ @artist.allow_rasterization
362
+ def draw(self, renderer):
363
+ if not self.get_visible():
364
+ return
365
+ renderer.open_group(self.__class__.__name__, self.get_gid())
366
+
367
+ # Bail if the collection does not have any offsets (e.g., an empty scatter plot)
368
+ if len(self.get_offsets()) == 0:
369
+ renderer.close_group(self.__class__.__name__)
370
+ self.stale = False
371
+ return
372
+
373
+ self.update_scalarmappable()
374
+
375
+ transform, offset_trf, offsets, paths = self._prepare_points()
376
+
377
+ gc = renderer.new_gc()
378
+ self._set_gc_clip(gc)
379
+ gc.set_snap(self.get_snap())
380
+
381
+ if self._hatch:
382
+ gc.set_hatch(self._hatch)
383
+ gc.set_hatch_linewidth(self._hatch_linewidth)
384
+
385
+ if self.get_sketch_params() is not None:
386
+ gc.set_sketch_params(*self.get_sketch_params())
387
+
388
+ if self.get_path_effects():
389
+ from matplotlib_rs.patheffects import PathEffectRenderer
390
+ renderer = PathEffectRenderer(self.get_path_effects(), renderer)
391
+
392
+ # If the collection is made up of a single shape/color/stroke,
393
+ # it can be rendered once and blitted multiple times, using
394
+ # `draw_markers` rather than `draw_path_collection`. This is
395
+ # *much* faster for Agg, and results in smaller file sizes in
396
+ # PDF/SVG/PS.
397
+
398
+ trans = self.get_transforms()
399
+ facecolors = self.get_facecolor()
400
+ edgecolors = self.get_edgecolor()
401
+ do_single_path_optimization = False
402
+ if (len(paths) == 1 and len(trans) <= 1 and
403
+ len(facecolors) == 1 and len(edgecolors) == 1 and
404
+ len(self._linewidths) == 1 and
405
+ all(ls[1] is None for ls in self._linestyles) and
406
+ len(self._antialiaseds) == 1 and len(self._urls) == 1 and
407
+ self.get_hatch() is None):
408
+ if len(trans):
409
+ combined_transform = transforms.Affine2D(trans[0]) + transform
410
+ else:
411
+ combined_transform = transform
412
+ extents = paths[0].get_extents(combined_transform)
413
+ if (extents.width < self.get_figure(root=True).bbox.width
414
+ and extents.height < self.get_figure(root=True).bbox.height):
415
+ do_single_path_optimization = True
416
+
417
+ if self._joinstyle:
418
+ gc.set_joinstyle(self._joinstyle)
419
+
420
+ if self._capstyle:
421
+ gc.set_capstyle(self._capstyle)
422
+
423
+ if do_single_path_optimization:
424
+ gc.set_foreground(tuple(edgecolors[0]), isRGBA=True)
425
+ gc.set_linewidth(self._linewidths[0])
426
+ gc.set_dashes(*self._linestyles[0])
427
+ gc.set_antialiased(self._antialiaseds[0])
428
+ gc.set_url(self._urls[0])
429
+ renderer.draw_markers(
430
+ gc, paths[0], combined_transform.frozen(),
431
+ mpath.Path(offsets), offset_trf, tuple(facecolors[0]))
432
+ else:
433
+ # The current new API of draw_path_collection() is provisional
434
+ # and will be changed in a future PR.
435
+
436
+ # Find whether renderer.draw_path_collection() takes hatchcolor parameter.
437
+ # Since third-party implementations of draw_path_collection() may not be
438
+ # introspectable, e.g. with inspect.signature, the only way is to try and
439
+ # call this with the hatchcolors parameter.
440
+ hatchcolors_arg_supported = True
441
+ try:
442
+ renderer.draw_path_collection(
443
+ gc, transform.frozen(), [],
444
+ self.get_transforms(), offsets, offset_trf,
445
+ self.get_facecolor(), self.get_edgecolor(),
446
+ self._linewidths, self._linestyles,
447
+ self._antialiaseds, self._urls,
448
+ "screen", hatchcolors=self.get_hatchcolor()
449
+ )
450
+ except TypeError:
451
+ # If the renderer does not support the hatchcolors argument,
452
+ # it will raise a TypeError. In this case, we will
453
+ # iterate over all paths and draw them one by one.
454
+ hatchcolors_arg_supported = False
455
+
456
+ # If the hatchcolors argument is not needed or not passed
457
+ # then we can skip the iteration over paths in case the
458
+ # argument is not supported by the renderer.
459
+ hatchcolors_not_needed = (self.get_hatch() is None or
460
+ self._original_hatchcolor is None)
461
+
462
+ if self._gapcolor is not None:
463
+ # First draw paths within the gaps.
464
+ ipaths, ilinestyles = self._get_inverse_paths_linestyles()
465
+ args = [offsets, offset_trf, [mcolors.to_rgba("none")], self._gapcolor,
466
+ self._linewidths, ilinestyles, self._antialiaseds, self._urls,
467
+ "screen"]
468
+
469
+ if hatchcolors_arg_supported:
470
+ renderer.draw_path_collection(gc, transform.frozen(), ipaths,
471
+ self.get_transforms(), *args,
472
+ hatchcolors=self.get_hatchcolor())
473
+ else:
474
+ if hatchcolors_not_needed:
475
+ renderer.draw_path_collection(gc, transform.frozen(), ipaths,
476
+ self.get_transforms(), *args)
477
+ else:
478
+ path_ids = renderer._iter_collection_raw_paths(
479
+ transform.frozen(), ipaths, self.get_transforms())
480
+ for xo, yo, path_id, gc0, rgbFace in renderer._iter_collection(
481
+ gc, list(path_ids), *args,
482
+ hatchcolors=self.get_hatchcolor(),
483
+ ):
484
+ path, transform = path_id
485
+ if xo != 0 or yo != 0:
486
+ transform = transform.frozen()
487
+ transform.translate(xo, yo)
488
+ renderer.draw_path(gc0, path, transform, rgbFace)
489
+
490
+ args = [offsets, offset_trf, self.get_facecolor(), self.get_edgecolor(),
491
+ self._linewidths, self._linestyles, self._antialiaseds, self._urls,
492
+ "screen"]
493
+
494
+ if hatchcolors_arg_supported:
495
+ renderer.draw_path_collection(gc, transform.frozen(), paths,
496
+ self.get_transforms(), *args,
497
+ hatchcolors=self.get_hatchcolor())
498
+ else:
499
+ if hatchcolors_not_needed:
500
+ renderer.draw_path_collection(gc, transform.frozen(), paths,
501
+ self.get_transforms(), *args)
502
+ else:
503
+ path_ids = renderer._iter_collection_raw_paths(
504
+ transform.frozen(), paths, self.get_transforms())
505
+ for xo, yo, path_id, gc0, rgbFace in renderer._iter_collection(
506
+ gc, list(path_ids), *args, hatchcolors=self.get_hatchcolor(),
507
+ ):
508
+ path, transform = path_id
509
+ if xo != 0 or yo != 0:
510
+ transform = transform.frozen()
511
+ transform.translate(xo, yo)
512
+ renderer.draw_path(gc0, path, transform, rgbFace)
513
+
514
+ gc.restore()
515
+ renderer.close_group(self.__class__.__name__)
516
+ self.stale = False
517
+
518
+ def set_pickradius(self, pickradius):
519
+ """
520
+ Set the pick radius used for containment tests.
521
+
522
+ Parameters
523
+ ----------
524
+ pickradius : float
525
+ Pick radius, in points.
526
+ """
527
+ if not isinstance(pickradius, Real):
528
+ raise ValueError(
529
+ f"pickradius must be a real-valued number, not {pickradius!r}")
530
+ self._pickradius = pickradius
531
+
532
+ def get_pickradius(self):
533
+ return self._pickradius
534
+
535
+ def contains(self, mouseevent):
536
+ """
537
+ Test whether the mouse event occurred in the collection.
538
+
539
+ Returns ``bool, dict(ind=itemlist)``, where every item in itemlist
540
+ contains the event.
541
+ """
542
+ if self._different_canvas(mouseevent) or not self.get_visible():
543
+ return False, {}
544
+ pickradius = (
545
+ float(self._picker)
546
+ if isinstance(self._picker, Number) and
547
+ self._picker is not True # the bool, not just nonzero or 1
548
+ else self._pickradius)
549
+ if self.axes:
550
+ self.axes._unstale_viewLim()
551
+ transform, offset_trf, offsets, paths = self._prepare_points()
552
+ # Tests if the point is contained on one of the polygons formed
553
+ # by the control points of each of the paths. A point is considered
554
+ # "on" a path if it would lie within a stroke of width 2*pickradius
555
+ # following the path. If pickradius <= 0, then we instead simply check
556
+ # if the point is *inside* of the path instead.
557
+ ind = _path.point_in_path_collection(
558
+ mouseevent.x, mouseevent.y, pickradius,
559
+ transform.frozen(), paths, self.get_transforms(),
560
+ offsets, offset_trf, pickradius <= 0)
561
+ return len(ind) > 0, dict(ind=ind)
562
+
563
+ def set_urls(self, urls):
564
+ """
565
+ Parameters
566
+ ----------
567
+ urls : list of str or None
568
+
569
+ Notes
570
+ -----
571
+ URLs are currently only implemented by the SVG backend. They are
572
+ ignored by all other backends.
573
+ """
574
+ self._urls = urls if urls is not None else [None]
575
+ self.stale = True
576
+
577
+ def get_urls(self):
578
+ """
579
+ Return a list of URLs, one for each element of the collection.
580
+
581
+ The list contains *None* for elements without a URL. See
582
+ :doc:`/gallery/misc/hyperlinks_sgskip` for an example.
583
+ """
584
+ return self._urls
585
+
586
+ def set_hatch(self, hatch):
587
+ r"""
588
+ Set the hatching pattern
589
+
590
+ *hatch* can be one of::
591
+
592
+ / - diagonal hatching
593
+ \ - back diagonal
594
+ | - vertical
595
+ - - horizontal
596
+ + - crossed
597
+ x - crossed diagonal
598
+ o - small circle
599
+ O - large circle
600
+ . - dots
601
+ * - stars
602
+
603
+ Letters can be combined, in which case all the specified
604
+ hatchings are done. If same letter repeats, it increases the
605
+ density of hatching of that pattern.
606
+
607
+ Unlike other properties such as linewidth and colors, hatching
608
+ can only be specified for the collection as a whole, not separately
609
+ for each member.
610
+
611
+ Parameters
612
+ ----------
613
+ hatch : {'/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
614
+ """
615
+ # Use validate_hatch(list) after deprecation.
616
+ mhatch._validate_hatch_pattern(hatch)
617
+ self._hatch = hatch
618
+ self.stale = True
619
+
620
+ def get_hatch(self):
621
+ """Return the current hatching pattern."""
622
+ return self._hatch
623
+
624
+ def set_hatch_linewidth(self, lw):
625
+ """Set the hatch linewidth."""
626
+ self._hatch_linewidth = lw
627
+
628
+ def get_hatch_linewidth(self):
629
+ """Return the hatch linewidth."""
630
+ return self._hatch_linewidth
631
+
632
+ def set_offsets(self, offsets):
633
+ """
634
+ Set the offsets for the collection.
635
+
636
+ Parameters
637
+ ----------
638
+ offsets : (N, 2) or (2,) array-like
639
+ """
640
+ offsets = np.asanyarray(offsets)
641
+ if offsets.shape == (2,): # Broadcast (2,) -> (1, 2) but nothing else.
642
+ offsets = offsets[None, :]
643
+ cstack = (np.ma.column_stack if isinstance(offsets, np.ma.MaskedArray)
644
+ else np.column_stack)
645
+ self._offsets = cstack(
646
+ (np.asanyarray(self.convert_xunits(offsets[:, 0]), float),
647
+ np.asanyarray(self.convert_yunits(offsets[:, 1]), float)))
648
+ self.stale = True
649
+
650
+ def get_offsets(self):
651
+ """Return the offsets for the collection."""
652
+ # Default to zeros in the no-offset (None) case
653
+ return np.zeros((1, 2)) if self._offsets is None else self._offsets
654
+
655
+ def _get_default_linewidth(self):
656
+ # This may be overridden in a subclass.
657
+ return mpl.rcParams['patch.linewidth'] # validated as float
658
+
659
+ def set_linewidth(self, lw):
660
+ """
661
+ Set the linewidth(s) for the collection. *lw* can be a scalar
662
+ or a sequence; if it is a sequence the patches will cycle
663
+ through the sequence
664
+
665
+ Parameters
666
+ ----------
667
+ lw : float or list of floats
668
+ """
669
+ if lw is None:
670
+ lw = self._get_default_linewidth()
671
+ # get the un-scaled/broadcast lw
672
+ self._us_lw = np.atleast_1d(lw)
673
+
674
+ # scale all of the dash patterns.
675
+ self._linewidths, self._linestyles = self._bcast_lwls(
676
+ self._us_lw, self._us_linestyles)
677
+ self.stale = True
678
+
679
+ def set_linestyle(self, ls):
680
+ """
681
+ Set the linestyle(s) for the collection.
682
+
683
+ Parameters
684
+ ----------
685
+ ls : {'-', '--', '-.', ':', '', ...} or (offset, on-off-seq) or list thereof
686
+ If a list, the individual elements are assigned to the elements of the
687
+ collection.
688
+
689
+ Possible values:
690
+
691
+ - A string:
692
+
693
+ ======================================================= ================
694
+ linestyle description
695
+ ======================================================= ================
696
+ ``'-'`` or ``'solid'`` solid line
697
+ ``'--'`` or ``'dashed'`` dashed line
698
+ ``'-.'`` or ``'dashdot'`` dash-dotted line
699
+ ``':'`` or ``'dotted'`` dotted line
700
+ ``''`` or ``'none'`` (discouraged: ``'None'``, ``' '``) draw nothing
701
+ ======================================================= ================
702
+
703
+ - A tuple describing the start position and lengths of dashes and spaces:
704
+
705
+ (offset, onoffseq)
706
+
707
+ where
708
+
709
+ - *offset* is a float specifying the offset (in points); i.e. how much
710
+ is the dash pattern shifted.
711
+ - *onoffseq* is a sequence of on and off ink in points. There can be
712
+ arbitrary many pairs of on and off values.
713
+
714
+ Example: The tuple ``(0, (10, 5, 1, 5))`` means that the pattern starts
715
+ at the beginning of the line. It draws a 10 point long dash,
716
+ then a 5 point long space, then a 1 point long dash, followed by a 5 point
717
+ long space, and then the pattern repeats.
718
+
719
+ For examples see :doc:`/gallery/lines_bars_and_markers/linestyles`.
720
+ """
721
+ # get the list of raw 'unscaled' dash patterns
722
+ self._us_linestyles = mlines._get_dash_patterns(ls)
723
+
724
+ # broadcast and scale the lw and dash patterns
725
+ self._linewidths, self._linestyles = self._bcast_lwls(
726
+ self._us_lw, self._us_linestyles)
727
+
728
+ @_docstring.interpd
729
+ def set_capstyle(self, cs):
730
+ """
731
+ Set the `.CapStyle` for the collection (for all its elements).
732
+
733
+ Parameters
734
+ ----------
735
+ cs : `.CapStyle` or %(CapStyle)s
736
+ """
737
+ self._capstyle = CapStyle(cs)
738
+
739
+ @_docstring.interpd
740
+ def get_capstyle(self):
741
+ """
742
+ Return the cap style for the collection (for all its elements).
743
+
744
+ Returns
745
+ -------
746
+ %(CapStyle)s or None
747
+ """
748
+ return self._capstyle.name if self._capstyle else None
749
+
750
+ @_docstring.interpd
751
+ def set_joinstyle(self, js):
752
+ """
753
+ Set the `.JoinStyle` for the collection (for all its elements).
754
+
755
+ Parameters
756
+ ----------
757
+ js : `.JoinStyle` or %(JoinStyle)s
758
+ """
759
+ self._joinstyle = JoinStyle(js)
760
+
761
+ @_docstring.interpd
762
+ def get_joinstyle(self):
763
+ """
764
+ Return the join style for the collection (for all its elements).
765
+
766
+ Returns
767
+ -------
768
+ %(JoinStyle)s or None
769
+ """
770
+ return self._joinstyle.name if self._joinstyle else None
771
+
772
+ @staticmethod
773
+ def _bcast_lwls(linewidths, dashes):
774
+ """
775
+ Internal helper function to broadcast + scale ls/lw
776
+
777
+ In the collection drawing code, the linewidth and linestyle are cycled
778
+ through as circular buffers (via ``v[i % len(v)]``). Thus, if we are
779
+ going to scale the dash pattern at set time (not draw time) we need to
780
+ do the broadcasting now and expand both lists to be the same length.
781
+
782
+ Parameters
783
+ ----------
784
+ linewidths : list
785
+ line widths of collection
786
+ dashes : list
787
+ dash specification (offset, (dash pattern tuple))
788
+
789
+ Returns
790
+ -------
791
+ linewidths, dashes : list
792
+ Will be the same length, dashes are scaled by paired linewidth
793
+ """
794
+ if mpl.rcParams['_internal.classic_mode']:
795
+ return linewidths, dashes
796
+ # make sure they are the same length so we can zip them
797
+ if len(dashes) != len(linewidths):
798
+ l_dashes = len(dashes)
799
+ l_lw = len(linewidths)
800
+ gcd = math.gcd(l_dashes, l_lw)
801
+ dashes = list(dashes) * (l_lw // gcd)
802
+ linewidths = list(linewidths) * (l_dashes // gcd)
803
+
804
+ # scale the dash patterns
805
+ dashes = [mlines._scale_dashes(o, d, lw)
806
+ for (o, d), lw in zip(dashes, linewidths)]
807
+
808
+ return linewidths, dashes
809
+
810
+ def get_antialiased(self):
811
+ """
812
+ Get the antialiasing state for rendering.
813
+
814
+ Returns
815
+ -------
816
+ array of bools
817
+ """
818
+ return self._antialiaseds
819
+
820
+ def set_antialiased(self, aa):
821
+ """
822
+ Set the antialiasing state for rendering.
823
+
824
+ Parameters
825
+ ----------
826
+ aa : bool or list of bools
827
+ """
828
+ if aa is None:
829
+ aa = self._get_default_antialiased()
830
+ self._antialiaseds = np.atleast_1d(np.asarray(aa, bool))
831
+ self.stale = True
832
+
833
+ def _get_default_antialiased(self):
834
+ # This may be overridden in a subclass.
835
+ return mpl.rcParams['patch.antialiased']
836
+
837
+ def set_color(self, c):
838
+ """
839
+ Set the edgecolor, facecolor and hatchcolor.
840
+
841
+ .. versionchanged:: 3.11
842
+ Now sets the hatchcolor as well.
843
+
844
+ Parameters
845
+ ----------
846
+ c : :mpltype:`color` or list of RGBA tuples
847
+
848
+ See Also
849
+ --------
850
+ Collection.set_facecolor, Collection.set_edgecolor, Collection.set_hatchcolor
851
+ For setting the facecolor, edgecolor, and hatchcolor individually.
852
+ """
853
+ self.set_facecolor(c)
854
+ self.set_edgecolor(c)
855
+ self.set_hatchcolor(c)
856
+
857
+ def _get_default_facecolor(self):
858
+ # This may be overridden in a subclass.
859
+ return mpl.rcParams['patch.facecolor']
860
+
861
+ def _set_facecolor(self, c):
862
+ if c is None:
863
+ c = self._get_default_facecolor()
864
+
865
+ self._facecolors = mcolors.to_rgba_array(c, self._alpha)
866
+ self.stale = True
867
+
868
+ def set_facecolor(self, c):
869
+ """
870
+ Set the facecolor(s) of the collection. *c* can be a color (all patches
871
+ have same color), or a sequence of colors; if it is a sequence the
872
+ patches will cycle through the sequence.
873
+
874
+ If *c* is 'none', the patch will not be filled.
875
+
876
+ Parameters
877
+ ----------
878
+ c : :mpltype:`color` or list of :mpltype:`color`
879
+ """
880
+ if isinstance(c, str) and c.lower() in ("none", "face"):
881
+ c = c.lower()
882
+ self._original_facecolor = c
883
+ self._set_facecolor(c)
884
+
885
+ def get_facecolor(self):
886
+ return self._facecolors
887
+
888
+ def get_edgecolor(self):
889
+ if cbook._str_equal(self._edgecolors, 'face'):
890
+ return self.get_facecolor()
891
+ else:
892
+ return self._edgecolors
893
+
894
+ def _get_default_edgecolor(self):
895
+ # This may be overridden in a subclass.
896
+ return mpl.rcParams['patch.edgecolor']
897
+
898
+ def get_hatchcolor(self):
899
+ if cbook._str_equal(self._hatchcolors, 'edge'):
900
+ if len(self.get_edgecolor()) == 0:
901
+ return mpl.colors.to_rgba_array(self._get_default_edgecolor(),
902
+ self._alpha)
903
+ return self.get_edgecolor()
904
+ return self._hatchcolors
905
+
906
+ def _set_edgecolor(self, c):
907
+ if c is None:
908
+ if (mpl.rcParams['patch.force_edgecolor']
909
+ or self._edge_default
910
+ or cbook._str_equal(self._original_facecolor, 'none')):
911
+ c = self._get_default_edgecolor()
912
+ else:
913
+ c = 'none'
914
+ if cbook._str_lower_equal(c, 'face'):
915
+ self._edgecolors = 'face'
916
+ self.stale = True
917
+ return
918
+ self._edgecolors = mcolors.to_rgba_array(c, self._alpha)
919
+ self.stale = True
920
+
921
+ def set_edgecolor(self, c):
922
+ """
923
+ Set the edgecolor(s) of the collection.
924
+
925
+ Parameters
926
+ ----------
927
+ c : :mpltype:`color` or list of :mpltype:`color` or 'face'
928
+ The collection edgecolor(s). If a sequence, the patches cycle
929
+ through it. If 'face', match the facecolor.
930
+ """
931
+ # We pass through a default value for use in LineCollection.
932
+ # This allows us to maintain None as the default indicator in
933
+ # _original_edgecolor.
934
+ if isinstance(c, str) and c.lower() in ("none", "face"):
935
+ c = c.lower()
936
+ self._original_edgecolor = c
937
+ self._set_edgecolor(c)
938
+
939
+ def _set_hatchcolor(self, c):
940
+ c = mpl._val_or_rc(c, 'hatch.color')
941
+ if cbook._str_equal(c, 'edge'):
942
+ self._hatchcolors = 'edge'
943
+ else:
944
+ self._hatchcolors = mcolors.to_rgba_array(c, self._alpha)
945
+ self.stale = True
946
+
947
+ def set_hatchcolor(self, c):
948
+ """
949
+ Set the hatchcolor(s) of the collection.
950
+
951
+ Parameters
952
+ ----------
953
+ c : :mpltype:`color` or list of :mpltype:`color` or 'edge'
954
+ The collection hatchcolor(s). If a sequence, the patches cycle
955
+ through it.
956
+ """
957
+ self._original_hatchcolor = c
958
+ self._set_hatchcolor(c)
959
+
960
+ def set_alpha(self, alpha):
961
+ """
962
+ Set the transparency of the collection.
963
+
964
+ Parameters
965
+ ----------
966
+ alpha : float or array of float or None
967
+ If not None, *alpha* values must be between 0 and 1, inclusive.
968
+ If an array is provided, its length must match the number of
969
+ elements in the collection. Masked values and nans are not
970
+ supported.
971
+ """
972
+ artist.Artist._set_alpha_for_array(self, alpha)
973
+ self._set_facecolor(self._original_facecolor)
974
+ self._set_edgecolor(self._original_edgecolor)
975
+ self._set_hatchcolor(self._original_hatchcolor)
976
+
977
+ set_alpha.__doc__ = artist.Artist._set_alpha_for_array.__doc__
978
+
979
+ def get_linewidth(self):
980
+ return self._linewidths
981
+
982
+ def get_linestyle(self):
983
+ return self._linestyles
984
+
985
+ def _set_mappable_flags(self):
986
+ """
987
+ Determine whether edges and/or faces are color-mapped.
988
+
989
+ This is a helper for update_scalarmappable.
990
+ It sets Boolean flags '_edge_is_mapped' and '_face_is_mapped'.
991
+
992
+ Returns
993
+ -------
994
+ mapping_change : bool
995
+ True if either flag is True, or if a flag has changed.
996
+ """
997
+ # The flags are initialized to None to ensure this returns True
998
+ # the first time it is called.
999
+ edge0 = self._edge_is_mapped
1000
+ face0 = self._face_is_mapped
1001
+ # After returning, the flags must be Booleans, not None.
1002
+ self._edge_is_mapped = False
1003
+ self._face_is_mapped = False
1004
+ if self._A is not None:
1005
+ if not cbook._str_equal(self._original_facecolor, 'none'):
1006
+ self._face_is_mapped = True
1007
+ if cbook._str_equal(self._original_edgecolor, 'face'):
1008
+ self._edge_is_mapped = True
1009
+ else:
1010
+ if self._original_edgecolor is None:
1011
+ self._edge_is_mapped = True
1012
+
1013
+ mapped = self._face_is_mapped or self._edge_is_mapped
1014
+ changed = (edge0 is None or face0 is None
1015
+ or self._edge_is_mapped != edge0
1016
+ or self._face_is_mapped != face0)
1017
+ return mapped or changed
1018
+
1019
+ def update_scalarmappable(self):
1020
+ """
1021
+ Update colors from the scalar mappable array, if any.
1022
+
1023
+ Assign colors to edges and faces based on the array and/or
1024
+ colors that were directly set, as appropriate.
1025
+ """
1026
+ if not self._set_mappable_flags():
1027
+ return
1028
+ # Allow possibility to call 'self.set_array(None)'.
1029
+ if self._A is not None:
1030
+ # QuadMesh can map 2d arrays (but pcolormesh supplies 1d array)
1031
+ if self._A.ndim > 1 and not isinstance(self, _MeshData):
1032
+ raise ValueError('Collections can only map rank 1 arrays')
1033
+ if np.iterable(self._alpha):
1034
+ if self._alpha.size != self._A.size:
1035
+ raise ValueError(
1036
+ f'Data array shape, {self._A.shape} '
1037
+ 'is incompatible with alpha array shape, '
1038
+ f'{self._alpha.shape}. '
1039
+ 'This can occur with the deprecated '
1040
+ 'behavior of the "flat" shading option, '
1041
+ 'in which a row and/or column of the data '
1042
+ 'array is dropped.')
1043
+ # pcolormesh, scatter, maybe others flatten their _A
1044
+ self._alpha = self._alpha.reshape(self._A.shape)
1045
+ self._mapped_colors = self.to_rgba(self._A, self._alpha)
1046
+
1047
+ if self._face_is_mapped:
1048
+ self._facecolors = self._mapped_colors
1049
+ else:
1050
+ self._set_facecolor(self._original_facecolor)
1051
+ if self._edge_is_mapped:
1052
+ self._edgecolors = self._mapped_colors
1053
+ else:
1054
+ self._set_edgecolor(self._original_edgecolor)
1055
+ self.stale = True
1056
+
1057
+ def get_fill(self):
1058
+ """Return whether face is colored."""
1059
+ return not cbook._str_lower_equal(self._original_facecolor, "none")
1060
+
1061
+ def update_from(self, other):
1062
+ """Copy properties from other to self."""
1063
+
1064
+ artist.Artist.update_from(self, other)
1065
+ self._antialiaseds = other._antialiaseds
1066
+ self._mapped_colors = other._mapped_colors
1067
+ self._edge_is_mapped = other._edge_is_mapped
1068
+ self._original_edgecolor = other._original_edgecolor
1069
+ self._edgecolors = other._edgecolors
1070
+ self._face_is_mapped = other._face_is_mapped
1071
+ self._original_facecolor = other._original_facecolor
1072
+ self._facecolors = other._facecolors
1073
+ self._linewidths = other._linewidths
1074
+ self._linestyles = other._linestyles
1075
+ self._us_linestyles = other._us_linestyles
1076
+ self._pickradius = other._pickradius
1077
+ self._hatch = other._hatch
1078
+ self._hatchcolors = other._hatchcolors
1079
+
1080
+ # update_from for scalarmappable
1081
+ self._A = other._A
1082
+ self.norm = other.norm
1083
+ self.cmap = other.cmap
1084
+ self.stale = True
1085
+
1086
+
1087
+ class _CollectionWithSizes(Collection):
1088
+ """
1089
+ Base class for collections that have an array of sizes.
1090
+ """
1091
+ _factor = 1.0
1092
+
1093
+ def get_sizes(self):
1094
+ """
1095
+ Return the sizes ('areas') of the elements in the collection.
1096
+
1097
+ Returns
1098
+ -------
1099
+ array
1100
+ The 'area' of each element.
1101
+ """
1102
+ return self._sizes
1103
+
1104
+ def set_sizes(self, sizes, dpi=72.0):
1105
+ """
1106
+ Set the sizes of each member of the collection.
1107
+
1108
+ Parameters
1109
+ ----------
1110
+ sizes : `numpy.ndarray` or None
1111
+ The size to set for each element of the collection. The
1112
+ value is the 'area' of the element.
1113
+ dpi : float, default: 72
1114
+ The dpi of the canvas.
1115
+ """
1116
+ if sizes is None:
1117
+ self._sizes = np.array([])
1118
+ self._transforms = np.empty((0, 3, 3))
1119
+ else:
1120
+ self._sizes = np.asarray(sizes)
1121
+ self._transforms = np.zeros((len(self._sizes), 3, 3))
1122
+ scale = np.sqrt(self._sizes) * dpi / 72.0 * self._factor
1123
+ self._transforms[:, 0, 0] = scale
1124
+ self._transforms[:, 1, 1] = scale
1125
+ self._transforms[:, 2, 2] = 1.0
1126
+ self.stale = True
1127
+
1128
+ @artist.allow_rasterization
1129
+ def draw(self, renderer):
1130
+ self.set_sizes(self._sizes, self.get_figure(root=True).dpi)
1131
+ super().draw(renderer)
1132
+
1133
+
1134
+ class PathCollection(_CollectionWithSizes):
1135
+ r"""
1136
+ A collection of `~.path.Path`\s, as created by e.g. `~.Axes.scatter`.
1137
+ """
1138
+
1139
+ def __init__(self, paths, sizes=None, **kwargs):
1140
+ """
1141
+ Parameters
1142
+ ----------
1143
+ paths : list of `.path.Path`
1144
+ The paths that will make up the `.Collection`.
1145
+ sizes : array-like
1146
+ The factor by which to scale each drawn `~.path.Path`. One unit
1147
+ squared in the Path's data space is scaled to be ``sizes**2``
1148
+ points when rendered.
1149
+ **kwargs
1150
+ Forwarded to `.Collection`.
1151
+ """
1152
+
1153
+ super().__init__(**kwargs)
1154
+ self.set_paths(paths)
1155
+ self.set_sizes(sizes)
1156
+ self.stale = True
1157
+
1158
+ def get_paths(self):
1159
+ return self._paths
1160
+
1161
+ def legend_elements(self, prop="colors", num="auto",
1162
+ fmt=None, func=lambda x: x, **kwargs):
1163
+ """
1164
+ Create legend handles and labels for a PathCollection.
1165
+
1166
+ Each legend handle is a `.Line2D` representing the Path that was drawn,
1167
+ and each label is a string that represents the Path.
1168
+
1169
+ This is useful for obtaining a legend for a `~.Axes.scatter` plot;
1170
+ e.g.::
1171
+
1172
+ scatter = plt.scatter([1, 2, 3], [4, 5, 6], c=[7, 2, 3], num=None)
1173
+ plt.legend(*scatter.legend_elements())
1174
+
1175
+ creates three legend elements, one for each color with the numerical
1176
+ values passed to *c* as the labels.
1177
+
1178
+ Also see the :ref:`automatedlegendcreation` example.
1179
+
1180
+ Parameters
1181
+ ----------
1182
+ prop : {"colors", "sizes"}, default: "colors"
1183
+ If "colors", the legend handles will show the different colors of
1184
+ the collection. If "sizes", the legend will show the different
1185
+ sizes. To set both, use *kwargs* to directly edit the `.Line2D`
1186
+ properties.
1187
+ num : int, None, "auto" (default), array-like, or `~.ticker.Locator`
1188
+ Target number of elements to create.
1189
+ If None, use all unique elements of the mappable array. If an
1190
+ integer, target to use *num* elements in the normed range.
1191
+ If *"auto"*, try to determine which option better suits the nature
1192
+ of the data.
1193
+ The number of created elements may slightly deviate from *num* due
1194
+ to a `~.ticker.Locator` being used to find useful locations.
1195
+ If a list or array, use exactly those elements for the legend.
1196
+ Finally, a `~.ticker.Locator` can be provided.
1197
+ fmt : str, `~matplotlib.ticker.Formatter`, or None (default)
1198
+ The format or formatter to use for the labels. If a string must be
1199
+ a valid input for a `.StrMethodFormatter`. If None (the default),
1200
+ use a `.ScalarFormatter`.
1201
+ func : function, default: ``lambda x: x``
1202
+ Function to calculate the labels. Often the size (or color)
1203
+ argument to `~.Axes.scatter` will have been pre-processed by the
1204
+ user using a function ``s = f(x)`` to make the markers visible;
1205
+ e.g. ``size = np.log10(x)``. Providing the inverse of this
1206
+ function here allows that pre-processing to be inverted, so that
1207
+ the legend labels have the correct values; e.g. ``func = lambda
1208
+ x: 10**x``.
1209
+ **kwargs
1210
+ Allowed keyword arguments are *color* and *size*. E.g. it may be
1211
+ useful to set the color of the markers if *prop="sizes"* is used;
1212
+ similarly to set the size of the markers if *prop="colors"* is
1213
+ used. Any further parameters are passed onto the `.Line2D`
1214
+ instance. This may be useful to e.g. specify a different
1215
+ *markeredgecolor* or *alpha* for the legend handles.
1216
+
1217
+ Returns
1218
+ -------
1219
+ handles : list of `.Line2D`
1220
+ Visual representation of each element of the legend.
1221
+ labels : list of str
1222
+ The string labels for elements of the legend.
1223
+ """
1224
+ handles = []
1225
+ labels = []
1226
+ hasarray = self.get_array() is not None
1227
+ if fmt is None:
1228
+ fmt = mpl.ticker.ScalarFormatter(useOffset=False, useMathText=True)
1229
+ elif isinstance(fmt, str):
1230
+ fmt = mpl.ticker.StrMethodFormatter(fmt)
1231
+ fmt.create_dummy_axis()
1232
+
1233
+ if prop == "colors":
1234
+ if not hasarray:
1235
+ warnings.warn("Collection without array used. Make sure to "
1236
+ "specify the values to be colormapped via the "
1237
+ "`c` argument.")
1238
+ return handles, labels
1239
+ u = np.unique(self.get_array())
1240
+ size = kwargs.pop("size", mpl.rcParams["lines.markersize"])
1241
+ elif prop == "sizes":
1242
+ u = np.unique(self.get_sizes())
1243
+ color = kwargs.pop("color", "k")
1244
+ else:
1245
+ raise ValueError("Valid values for `prop` are 'colors' or "
1246
+ f"'sizes'. You supplied '{prop}' instead.")
1247
+
1248
+ fu = func(u)
1249
+ fmt.axis.set_view_interval(fu.min(), fu.max())
1250
+ fmt.axis.set_data_interval(fu.min(), fu.max())
1251
+ if num == "auto":
1252
+ num = 9
1253
+ if len(u) <= num:
1254
+ num = None
1255
+ if num is None:
1256
+ values = u
1257
+ label_values = func(values)
1258
+ else:
1259
+ if prop == "colors":
1260
+ arr = self.get_array()
1261
+ elif prop == "sizes":
1262
+ arr = self.get_sizes()
1263
+ if isinstance(num, mpl.ticker.Locator):
1264
+ loc = num
1265
+ elif np.iterable(num):
1266
+ loc = mpl.ticker.FixedLocator(num)
1267
+ else:
1268
+ num = int(num)
1269
+ loc = mpl.ticker.MaxNLocator(nbins=num, min_n_ticks=num-1,
1270
+ steps=[1, 2, 2.5, 3, 5, 6, 8, 10])
1271
+ label_values = loc.tick_values(func(arr).min(), func(arr).max())
1272
+ cond = ((label_values >= func(arr).min()) &
1273
+ (label_values <= func(arr).max()))
1274
+ label_values = label_values[cond]
1275
+ yarr = np.linspace(arr.min(), arr.max(), 256)
1276
+ xarr = func(yarr)
1277
+ ix = np.argsort(xarr)
1278
+ values = np.interp(label_values, xarr[ix], yarr[ix])
1279
+
1280
+ kw = {"markeredgewidth": self.get_linewidths()[0],
1281
+ "alpha": self.get_alpha(),
1282
+ **kwargs}
1283
+
1284
+ # Pre-format all labels
1285
+ # TODO: check whether we can switch to
1286
+ # formatted_labels = fmt.format_ticks(label_values)
1287
+ # There are subtle differences for some formatters as that passes the
1288
+ # indices to __call__ as well.
1289
+ fmt.set_locs(label_values)
1290
+ formatted_labels = [fmt(lab) for lab in label_values]
1291
+
1292
+ for val, formatted in zip(values, formatted_labels):
1293
+ if prop == "colors":
1294
+ color = self.cmap(self.norm(val))
1295
+ elif prop == "sizes":
1296
+ size = np.sqrt(val)
1297
+ if np.isclose(size, 0.0):
1298
+ continue
1299
+ h = mlines.Line2D([0], [0], ls="", color=color, ms=size,
1300
+ marker=self.get_paths()[0], **kw)
1301
+ handles.append(h)
1302
+ labels.append(formatted)
1303
+
1304
+ return handles, labels
1305
+
1306
+
1307
+ class PolyCollection(_CollectionWithSizes):
1308
+
1309
+ def __init__(self, verts, sizes=None, *, closed=True, **kwargs):
1310
+ """
1311
+ Parameters
1312
+ ----------
1313
+ verts : list of array-like
1314
+ The sequence of polygons [*verts0*, *verts1*, ...] where each
1315
+ element *verts_i* defines the vertices of polygon *i* as a 2D
1316
+ array-like of shape (M, 2).
1317
+ sizes : array-like, default: None
1318
+ Squared scaling factors for the polygons. The coordinates of each
1319
+ polygon *verts_i* are multiplied by the square-root of the
1320
+ corresponding entry in *sizes* (i.e., *sizes* specify the scaling
1321
+ of areas). The scaling is applied before the Artist master
1322
+ transform.
1323
+ closed : bool, default: True
1324
+ Whether the polygon should be closed by adding a CLOSEPOLY
1325
+ connection at the end.
1326
+ **kwargs
1327
+ Forwarded to `.Collection`.
1328
+ """
1329
+ super().__init__(**kwargs)
1330
+ self.set_sizes(sizes)
1331
+ self.set_verts(verts, closed)
1332
+ self.stale = True
1333
+
1334
+ def set_verts(self, verts, closed=True):
1335
+ """
1336
+ Set the vertices of the polygons.
1337
+
1338
+ Parameters
1339
+ ----------
1340
+ verts : list of array-like
1341
+ The sequence of polygons [*verts0*, *verts1*, ...] where each
1342
+ element *verts_i* defines the vertices of polygon *i* as a 2D
1343
+ array-like of shape (M, 2).
1344
+ closed : bool, default: True
1345
+ Whether the polygon should be closed by adding a CLOSEPOLY
1346
+ connection at the end.
1347
+ """
1348
+ self.stale = True
1349
+ if isinstance(verts, np.ma.MaskedArray):
1350
+ verts = verts.astype(float).filled(np.nan)
1351
+
1352
+ # No need to do anything fancy if the path isn't closed.
1353
+ if not closed:
1354
+ self._paths = [mpath.Path(xy) for xy in verts]
1355
+ return
1356
+
1357
+ # Fast path for arrays
1358
+ if isinstance(verts, np.ndarray) and len(verts.shape) == 3 and verts.size:
1359
+ verts_pad = np.concatenate((verts, verts[:, :1]), axis=1)
1360
+ # It's faster to create the codes and internal flags once in a
1361
+ # template path and reuse them.
1362
+ template_path = mpath.Path(verts_pad[0], closed=True)
1363
+ codes = template_path.codes
1364
+ _make_path = mpath.Path._fast_from_codes_and_verts
1365
+ self._paths = [_make_path(xy, codes, internals_from=template_path)
1366
+ for xy in verts_pad]
1367
+ return
1368
+
1369
+ self._paths = []
1370
+ for xy in verts:
1371
+ if len(xy):
1372
+ self._paths.append(mpath.Path._create_closed(xy))
1373
+ else:
1374
+ self._paths.append(mpath.Path(xy))
1375
+
1376
+ set_paths = set_verts
1377
+
1378
+ def set_verts_and_codes(self, verts, codes):
1379
+ """Initialize vertices with path codes."""
1380
+ if len(verts) != len(codes):
1381
+ raise ValueError("'codes' must be a 1D list or array "
1382
+ "with the same length of 'verts'")
1383
+ self._paths = [mpath.Path(xy, cds) if len(xy) else mpath.Path(xy)
1384
+ for xy, cds in zip(verts, codes)]
1385
+ self.stale = True
1386
+
1387
+
1388
+ class FillBetweenPolyCollection(PolyCollection):
1389
+ """
1390
+ `.PolyCollection` that fills the area between two x- or y-curves.
1391
+ """
1392
+ def __init__(
1393
+ self, t_direction, t, f1, f2, *,
1394
+ where=None, interpolate=False, step=None, **kwargs):
1395
+ """
1396
+ Parameters
1397
+ ----------
1398
+ t_direction : {{'x', 'y'}}
1399
+ The axes on which the variable lies.
1400
+
1401
+ - 'x': the curves are ``(t, f1)`` and ``(t, f2)``.
1402
+ - 'y': the curves are ``(f1, t)`` and ``(f2, t)``.
1403
+
1404
+ t : array-like
1405
+ The ``t_direction`` coordinates of the nodes defining the curves.
1406
+
1407
+ f1 : array-like or float
1408
+ The other coordinates of the nodes defining the first curve.
1409
+
1410
+ f2 : array-like or float
1411
+ The other coordinates of the nodes defining the second curve.
1412
+
1413
+ where : array-like of bool, optional
1414
+ Define *where* to exclude some {dir} regions from being filled.
1415
+ The filled regions are defined by the coordinates ``t[where]``.
1416
+ More precisely, fill between ``t[i]`` and ``t[i+1]`` if
1417
+ ``where[i] and where[i+1]``. Note that this definition implies
1418
+ that an isolated *True* value between two *False* values in *where*
1419
+ will not result in filling. Both sides of the *True* position
1420
+ remain unfilled due to the adjacent *False* values.
1421
+
1422
+ interpolate : bool, default: False
1423
+ This option is only relevant if *where* is used and the two curves
1424
+ are crossing each other.
1425
+
1426
+ Semantically, *where* is often used for *f1* > *f2* or
1427
+ similar. By default, the nodes of the polygon defining the filled
1428
+ region will only be placed at the positions in the *t* array.
1429
+ Such a polygon cannot describe the above semantics close to the
1430
+ intersection. The t-sections containing the intersection are
1431
+ simply clipped.
1432
+
1433
+ Setting *interpolate* to *True* will calculate the actual
1434
+ intersection point and extend the filled region up to this point.
1435
+
1436
+ step : {{'pre', 'post', 'mid'}}, optional
1437
+ Define *step* if the filling should be a step function,
1438
+ i.e. constant in between *t*. The value determines where the
1439
+ step will occur:
1440
+
1441
+ - 'pre': The f value is continued constantly to the left from
1442
+ every *t* position, i.e. the interval ``(t[i-1], t[i]]`` has the
1443
+ value ``f[i]``.
1444
+ - 'post': The y value is continued constantly to the right from
1445
+ every *x* position, i.e. the interval ``[t[i], t[i+1])`` has the
1446
+ value ``f[i]``.
1447
+ - 'mid': Steps occur half-way between the *t* positions.
1448
+
1449
+ **kwargs
1450
+ Forwarded to `.PolyCollection`.
1451
+
1452
+ See Also
1453
+ --------
1454
+ .Axes.fill_between, .Axes.fill_betweenx
1455
+ """
1456
+ self.t_direction = t_direction
1457
+ self._interpolate = interpolate
1458
+ self._step = step
1459
+ verts = self._make_verts(t, f1, f2, where)
1460
+ super().__init__(verts, **kwargs)
1461
+
1462
+ @staticmethod
1463
+ def _f_dir_from_t(t_direction):
1464
+ """The direction that is other than `t_direction`."""
1465
+ if t_direction == "x":
1466
+ return "y"
1467
+ elif t_direction == "y":
1468
+ return "x"
1469
+ else:
1470
+ msg = f"t_direction must be 'x' or 'y', got {t_direction!r}"
1471
+ raise ValueError(msg)
1472
+
1473
+ @property
1474
+ def _f_direction(self):
1475
+ """The direction that is other than `self.t_direction`."""
1476
+ return self._f_dir_from_t(self.t_direction)
1477
+
1478
+ def set_data(self, t, f1, f2, *, where=None):
1479
+ """
1480
+ Set new values for the two bounding curves.
1481
+
1482
+ Parameters
1483
+ ----------
1484
+ t : array-like
1485
+ The ``self.t_direction`` coordinates of the nodes defining the curves.
1486
+
1487
+ f1 : array-like or float
1488
+ The other coordinates of the nodes defining the first curve.
1489
+
1490
+ f2 : array-like or float
1491
+ The other coordinates of the nodes defining the second curve.
1492
+
1493
+ where : array-like of bool, optional
1494
+ Define *where* to exclude some {dir} regions from being filled.
1495
+ The filled regions are defined by the coordinates ``t[where]``.
1496
+ More precisely, fill between ``t[i]`` and ``t[i+1]`` if
1497
+ ``where[i] and where[i+1]``. Note that this definition implies
1498
+ that an isolated *True* value between two *False* values in *where*
1499
+ will not result in filling. Both sides of the *True* position
1500
+ remain unfilled due to the adjacent *False* values.
1501
+
1502
+ See Also
1503
+ --------
1504
+ .PolyCollection.set_verts, .Line2D.set_data
1505
+ """
1506
+ t, f1, f2 = self.axes._fill_between_process_units(
1507
+ self.t_direction, self._f_direction, t, f1, f2)
1508
+
1509
+ verts = self._make_verts(t, f1, f2, where)
1510
+ self.set_verts(verts)
1511
+
1512
+ def get_datalim(self, transData):
1513
+ """Calculate the data limits and return them as a `.Bbox`."""
1514
+ datalim = transforms.Bbox.null()
1515
+ datalim.update_from_data_xy((self.get_transform() - transData).transform(
1516
+ np.concatenate([self._bbox, [self._bbox.minpos]])))
1517
+ return datalim
1518
+
1519
+ def _make_verts(self, t, f1, f2, where):
1520
+ """
1521
+ Make verts that can be forwarded to `.PolyCollection`.
1522
+ """
1523
+ self._validate_shapes(self.t_direction, self._f_direction, t, f1, f2)
1524
+
1525
+ where = self._get_data_mask(t, f1, f2, where)
1526
+ t, f1, f2 = np.broadcast_arrays(np.atleast_1d(t), f1, f2, subok=True)
1527
+
1528
+ self._bbox = transforms.Bbox.null()
1529
+ t_where = t.data[where] if np.ma.isMA(t) else t[where]
1530
+ f1_where = f1.data[where] if np.ma.isMA(f1) else f1[where]
1531
+ f2_where = f2.data[where] if np.ma.isMA(f2) else f2[where]
1532
+ n = len(t_where)
1533
+ if n > 0:
1534
+ pts = np.empty((2 * n, 2)) # Preallocate and fill for speed
1535
+ pts[:n, 0], pts[:n, 1] = t_where, f1_where
1536
+ pts[n:, 0], pts[n:, 1] = t_where, f2_where
1537
+ self._bbox.update_from_data_xy(self._fix_pts_xy_order(pts))
1538
+
1539
+ return [
1540
+ self._make_verts_for_region(t, f1, f2, idx0, idx1)
1541
+ for idx0, idx1 in cbook.contiguous_regions(where)
1542
+ ]
1543
+
1544
+ def _get_data_mask(self, t, f1, f2, where):
1545
+ """
1546
+ Return a bool array, with True at all points that should eventually be rendered.
1547
+
1548
+ The array is True at a point if none of the data inputs
1549
+ *t*, *f1*, *f2* is masked and if the input *where* is true at that point.
1550
+ """
1551
+ if where is None:
1552
+ where = True
1553
+ else:
1554
+ where = np.asarray(where, dtype=bool)
1555
+ if where.size != t.size:
1556
+ msg = "where size ({}) does not match {!r} size ({})".format(
1557
+ where.size, self.t_direction, t.size)
1558
+ raise ValueError(msg)
1559
+ return where & ~functools.reduce(
1560
+ np.logical_or, map(np.ma.getmaskarray, [t, f1, f2]))
1561
+
1562
+ @staticmethod
1563
+ def _validate_shapes(t_dir, f_dir, t, f1, f2):
1564
+ """Validate that t, f1 and f2 are 1-dimensional and have the same length."""
1565
+ names = (d + s for d, s in zip((t_dir, f_dir, f_dir), ("", "1", "2")))
1566
+ for name, array in zip(names, [t, f1, f2]):
1567
+ if array.ndim > 1:
1568
+ raise ValueError(f"{name!r} is not 1-dimensional")
1569
+ if t.size > 1 and array.size > 1 and t.size != array.size:
1570
+ msg = "{!r} has size {}, but {!r} has an unequal size of {}".format(
1571
+ t_dir, t.size, name, array.size)
1572
+ raise ValueError(msg)
1573
+
1574
+ def _make_verts_for_region(self, t, f1, f2, idx0, idx1):
1575
+ """
1576
+ Make ``verts`` for a contiguous region between ``idx0`` and ``idx1``, taking
1577
+ into account ``step`` and ``interpolate``.
1578
+ """
1579
+ t_slice = t[idx0:idx1]
1580
+ f1_slice = f1[idx0:idx1]
1581
+ f2_slice = f2[idx0:idx1]
1582
+ if self._step is not None:
1583
+ step_func = cbook.STEP_LOOKUP_MAP["steps-" + self._step]
1584
+ t_slice, f1_slice, f2_slice = step_func(t_slice, f1_slice, f2_slice)
1585
+
1586
+ if self._interpolate:
1587
+ start = self._get_interpolating_points(t, f1, f2, idx0)
1588
+ end = self._get_interpolating_points(t, f1, f2, idx1)
1589
+ else:
1590
+ # Handle scalar f2 (e.g. 0): the fill should go all
1591
+ # the way down to 0 even if none of the dep1 sample points do.
1592
+ start = t_slice[0], f2_slice[0]
1593
+ end = t_slice[-1], f2_slice[-1]
1594
+
1595
+ # Build polygon: start -> along f1 -> end -> back along f2 (reversed)
1596
+ # Preallocate and fill for speed
1597
+ n = len(t_slice)
1598
+ pts = np.empty((2 * n + 2, 2))
1599
+ pts[0, :] = start
1600
+ pts[1:n+1, 0], pts[1:n+1, 1] = t_slice, f1_slice
1601
+ pts[n+1, :] = end
1602
+ pts[n+2:, 0], pts[n+2:, 1] = t_slice[::-1], f2_slice[::-1]
1603
+
1604
+ return self._fix_pts_xy_order(pts)
1605
+
1606
+ @classmethod
1607
+ def _get_interpolating_points(cls, t, f1, f2, idx):
1608
+ """Calculate interpolating points."""
1609
+ im1 = max(idx - 1, 0)
1610
+ t_values = t[im1:idx+1]
1611
+ diff_values = f1[im1:idx+1] - f2[im1:idx+1]
1612
+ f1_values = f1[im1:idx+1]
1613
+
1614
+ if len(diff_values) == 2:
1615
+ if np.ma.is_masked(diff_values[1]):
1616
+ return t[im1], f1[im1]
1617
+ elif np.ma.is_masked(diff_values[0]):
1618
+ return t[idx], f1[idx]
1619
+
1620
+ diff_root_t = cls._get_diff_root(0, diff_values, t_values)
1621
+ diff_root_f = cls._get_diff_root(diff_root_t, t_values, f1_values)
1622
+ return diff_root_t, diff_root_f
1623
+
1624
+ @staticmethod
1625
+ def _get_diff_root(x, xp, fp):
1626
+ """Calculate diff root."""
1627
+ order = xp.argsort()
1628
+ return np.interp(x, xp[order], fp[order])
1629
+
1630
+ def _fix_pts_xy_order(self, pts):
1631
+ """
1632
+ Fix pts calculation results with `self.t_direction`.
1633
+
1634
+ In the workflow, it is assumed that `self.t_direction` is 'x'. If this
1635
+ is not true, we need to exchange the coordinates.
1636
+ """
1637
+ return pts[:, ::-1] if self.t_direction == "y" else pts
1638
+
1639
+
1640
+ class RegularPolyCollection(_CollectionWithSizes):
1641
+ """A collection of n-sided regular polygons."""
1642
+
1643
+ _path_generator = mpath.Path.unit_regular_polygon
1644
+ _factor = np.pi ** (-1/2)
1645
+
1646
+ def __init__(self,
1647
+ numsides,
1648
+ *,
1649
+ rotation=0,
1650
+ sizes=(1,),
1651
+ **kwargs):
1652
+ """
1653
+ Parameters
1654
+ ----------
1655
+ numsides : int
1656
+ The number of sides of the polygon.
1657
+ rotation : float
1658
+ The rotation of the polygon in radians.
1659
+ sizes : tuple of float
1660
+ The area of the circle circumscribing the polygon in points^2.
1661
+ **kwargs
1662
+ Forwarded to `.Collection`.
1663
+
1664
+ Examples
1665
+ --------
1666
+ See :doc:`/gallery/event_handling/lasso_demo` for a complete example::
1667
+
1668
+ offsets = np.random.rand(20, 2)
1669
+ facecolors = [cm.jet(x) for x in np.random.rand(20)]
1670
+
1671
+ collection = RegularPolyCollection(
1672
+ numsides=5, # a pentagon
1673
+ rotation=0, sizes=(50,),
1674
+ facecolors=facecolors,
1675
+ edgecolors=("black",),
1676
+ linewidths=(1,),
1677
+ offsets=offsets,
1678
+ offset_transform=ax.transData,
1679
+ )
1680
+ """
1681
+ super().__init__(**kwargs)
1682
+ self.set_sizes(sizes)
1683
+ self._numsides = numsides
1684
+ self._paths = [self._path_generator(numsides)]
1685
+ self._rotation = rotation
1686
+ self.set_transform(transforms.IdentityTransform())
1687
+
1688
+ def get_numsides(self):
1689
+ return self._numsides
1690
+
1691
+ def get_rotation(self):
1692
+ return self._rotation
1693
+
1694
+ @artist.allow_rasterization
1695
+ def draw(self, renderer):
1696
+ self.set_sizes(self._sizes, self.get_figure(root=True).dpi)
1697
+ self._transforms = [
1698
+ transforms.Affine2D(x).rotate(-self._rotation).get_matrix()
1699
+ for x in self._transforms
1700
+ ]
1701
+ # Explicitly not super().draw, because set_sizes must be called before
1702
+ # updating self._transforms.
1703
+ Collection.draw(self, renderer)
1704
+
1705
+
1706
+ class StarPolygonCollection(RegularPolyCollection):
1707
+ """Draw a collection of regular stars with *numsides* points."""
1708
+ _path_generator = mpath.Path.unit_regular_star
1709
+
1710
+
1711
+ class AsteriskPolygonCollection(RegularPolyCollection):
1712
+ """Draw a collection of regular asterisks with *numsides* points."""
1713
+ _path_generator = mpath.Path.unit_regular_asterisk
1714
+
1715
+
1716
+ class LineCollection(Collection):
1717
+ r"""
1718
+ Represents a sequence of `.Line2D`\s that should be drawn together.
1719
+
1720
+ This class extends `.Collection` to represent a sequence of
1721
+ `.Line2D`\s instead of just a sequence of `.Patch`\s.
1722
+ Just as in `.Collection`, each property of a *LineCollection* may be either
1723
+ a single value or a list of values. This list is then used cyclically for
1724
+ each element of the LineCollection, so the property of the ``i``\th element
1725
+ of the collection is::
1726
+
1727
+ prop[i % len(prop)]
1728
+
1729
+ The properties of each member of a *LineCollection* default to their values
1730
+ in :rc:`lines.*` instead of :rc:`patch.*`, and the property *colors* is
1731
+ added in place of *edgecolors*.
1732
+ """
1733
+
1734
+ _edge_default = True
1735
+
1736
+ def __init__(self, segments, # Can be None.
1737
+ *,
1738
+ zorder=2, # Collection.zorder is 1
1739
+ **kwargs
1740
+ ):
1741
+ """
1742
+ Parameters
1743
+ ----------
1744
+ segments : list of (N, 2) array-like
1745
+ A sequence ``[line0, line1, ...]`` where each line is a (N, 2)-shape
1746
+ array-like containing points::
1747
+
1748
+ line0 = [(x0, y0), (x1, y1), ...]
1749
+
1750
+ Each line can contain a different number of points.
1751
+ linewidths : float or list of float, default: :rc:`lines.linewidth`
1752
+ The width of each line in points.
1753
+ colors : :mpltype:`color` or list of color, default: :rc:`lines.color`
1754
+ A sequence of RGBA tuples (e.g., arbitrary color strings, etc, not
1755
+ allowed).
1756
+ antialiaseds : bool or list of bool, default: :rc:`lines.antialiased`
1757
+ Whether to use antialiasing for each line.
1758
+ zorder : float, default: 2
1759
+ zorder of the lines once drawn.
1760
+
1761
+ facecolors : :mpltype:`color` or list of :mpltype:`color`, default: 'none'
1762
+ When setting *facecolors*, each line is interpreted as a boundary
1763
+ for an area, implicitly closing the path from the last point to the
1764
+ first point. The enclosed area is filled with *facecolor*.
1765
+ In order to manually specify what should count as the "interior" of
1766
+ each line, please use `.PathCollection` instead, where the
1767
+ "interior" can be specified by appropriate usage of
1768
+ `~.path.Path.CLOSEPOLY`.
1769
+
1770
+ **kwargs
1771
+ Forwarded to `.Collection`.
1772
+ """
1773
+ # Unfortunately, mplot3d needs this explicit setting of 'facecolors'.
1774
+ kwargs.setdefault('facecolors', 'none')
1775
+ super().__init__(
1776
+ zorder=zorder,
1777
+ **kwargs)
1778
+ self.set_segments(segments)
1779
+
1780
+ def set_segments(self, segments):
1781
+ if segments is None:
1782
+ return
1783
+
1784
+ self._paths = [mpath.Path(seg) if isinstance(seg, np.ma.MaskedArray)
1785
+ else mpath.Path(np.asarray(seg, float))
1786
+ for seg in segments]
1787
+ self.stale = True
1788
+
1789
+ set_verts = set_segments # for compatibility with PolyCollection
1790
+ set_paths = set_segments
1791
+
1792
+ def get_segments(self):
1793
+ """
1794
+ Returns
1795
+ -------
1796
+ list
1797
+ List of segments in the LineCollection. Each list item contains an
1798
+ array of vertices.
1799
+ """
1800
+ segments = []
1801
+
1802
+ for path in self._paths:
1803
+ vertices = [
1804
+ vertex
1805
+ for vertex, _
1806
+ # Never simplify here, we want to get the data-space values
1807
+ # back and there in no way to know the "right" simplification
1808
+ # threshold so never try.
1809
+ in path.iter_segments(simplify=False)
1810
+ ]
1811
+ vertices = np.asarray(vertices)
1812
+ segments.append(vertices)
1813
+
1814
+ return segments
1815
+
1816
+ def _get_default_linewidth(self):
1817
+ return mpl.rcParams['lines.linewidth']
1818
+
1819
+ def _get_default_antialiased(self):
1820
+ return mpl.rcParams['lines.antialiased']
1821
+
1822
+ def _get_default_edgecolor(self):
1823
+ return mpl.rcParams['lines.color']
1824
+
1825
+ def _get_default_facecolor(self):
1826
+ return 'none'
1827
+
1828
+ def set_alpha(self, alpha):
1829
+ # docstring inherited
1830
+ super().set_alpha(alpha)
1831
+ if self._gapcolor is not None:
1832
+ self.set_gapcolor(self._original_gapcolor)
1833
+
1834
+ def set_color(self, c):
1835
+ """
1836
+ Set the edgecolor(s) of the LineCollection.
1837
+
1838
+ Parameters
1839
+ ----------
1840
+ c : :mpltype:`color` or list of :mpltype:`color`
1841
+ Single color (all lines have same color), or a
1842
+ sequence of RGBA tuples; if it is a sequence the lines will
1843
+ cycle through the sequence.
1844
+ """
1845
+ self.set_edgecolor(c)
1846
+
1847
+ set_colors = set_color
1848
+
1849
+ def get_color(self):
1850
+ return self._edgecolors
1851
+
1852
+ get_colors = get_color # for compatibility with old versions
1853
+
1854
+ def set_gapcolor(self, gapcolor):
1855
+ """
1856
+ Set a color to fill the gaps in the dashed line style.
1857
+
1858
+ .. note::
1859
+
1860
+ Striped lines are created by drawing two interleaved dashed lines.
1861
+ There can be overlaps between those two, which may result in
1862
+ artifacts when using transparency.
1863
+
1864
+ This functionality is experimental and may change.
1865
+
1866
+ Parameters
1867
+ ----------
1868
+ gapcolor : :mpltype:`color` or list of :mpltype:`color` or None
1869
+ The color with which to fill the gaps. If None, the gaps are
1870
+ unfilled.
1871
+ """
1872
+ self._original_gapcolor = gapcolor
1873
+ self._set_gapcolor(gapcolor)
1874
+
1875
+ def _set_gapcolor(self, gapcolor):
1876
+ if gapcolor is not None:
1877
+ gapcolor = mcolors.to_rgba_array(gapcolor, self._alpha)
1878
+ self._gapcolor = gapcolor
1879
+ self.stale = True
1880
+
1881
+ def get_gapcolor(self):
1882
+ return self._gapcolor
1883
+
1884
+ def _get_inverse_paths_linestyles(self):
1885
+ """
1886
+ Returns the path and pattern for the gaps in the non-solid lines.
1887
+
1888
+ This path and pattern is the inverse of the path and pattern used to
1889
+ construct the non-solid lines. For solid lines, we set the inverse path
1890
+ to nans to prevent drawing an inverse line.
1891
+ """
1892
+ path_patterns = [
1893
+ (mpath.Path(np.full((1, 2), np.nan)), ls)
1894
+ if ls == (0, None) else
1895
+ (path, mlines._get_inverse_dash_pattern(*ls))
1896
+ for (path, ls) in
1897
+ zip(self._paths, itertools.cycle(self._linestyles))]
1898
+
1899
+ return zip(*path_patterns)
1900
+
1901
+
1902
+ class EventCollection(LineCollection):
1903
+ """
1904
+ A collection of locations along a single axis at which an "event" occurred.
1905
+
1906
+ The events are given by a 1-dimensional array. They do not have an
1907
+ amplitude and are displayed as parallel lines.
1908
+ """
1909
+
1910
+ _edge_default = True
1911
+
1912
+ def __init__(self,
1913
+ positions, # Cannot be None.
1914
+ orientation='horizontal',
1915
+ *,
1916
+ lineoffset=0,
1917
+ linelength=1,
1918
+ linewidth=None,
1919
+ color=None,
1920
+ linestyle='solid',
1921
+ antialiased=None,
1922
+ **kwargs
1923
+ ):
1924
+ """
1925
+ Parameters
1926
+ ----------
1927
+ positions : 1D array-like
1928
+ Each value is an event.
1929
+ orientation : {'horizontal', 'vertical'}, default: 'horizontal'
1930
+ The sequence of events is plotted along this direction.
1931
+ The marker lines of the single events are along the orthogonal
1932
+ direction.
1933
+ lineoffset : float, default: 0
1934
+ The offset of the center of the markers from the origin, in the
1935
+ direction orthogonal to *orientation*.
1936
+ linelength : float, default: 1
1937
+ The total height of the marker (i.e. the marker stretches from
1938
+ ``lineoffset - linelength/2`` to ``lineoffset + linelength/2``).
1939
+ linewidth : float or list thereof, default: :rc:`lines.linewidth`
1940
+ The line width of the event lines, in points.
1941
+ color : :mpltype:`color` or list of :mpltype:`color`, default: :rc:`lines.color`
1942
+ The color of the event lines.
1943
+ linestyle : str or tuple or list thereof, default: 'solid'
1944
+ Valid strings are ['solid', 'dashed', 'dashdot', 'dotted',
1945
+ '-', '--', '-.', ':']. Dash tuples should be of the form::
1946
+
1947
+ (offset, onoffseq),
1948
+
1949
+ where *onoffseq* is an even length tuple of on and off ink
1950
+ in points.
1951
+ antialiased : bool or list thereof, default: :rc:`lines.antialiased`
1952
+ Whether to use antialiasing for drawing the lines.
1953
+ **kwargs
1954
+ Forwarded to `.LineCollection`.
1955
+
1956
+ Examples
1957
+ --------
1958
+ .. plot:: gallery/lines_bars_and_markers/eventcollection_demo.py
1959
+ """
1960
+ super().__init__([],
1961
+ linewidths=linewidth, linestyles=linestyle,
1962
+ colors=color, antialiaseds=antialiased,
1963
+ **kwargs)
1964
+ self._is_horizontal = True # Initial value, may be switched below.
1965
+ self._linelength = linelength
1966
+ self._lineoffset = lineoffset
1967
+ self.set_orientation(orientation)
1968
+ self.set_positions(positions)
1969
+
1970
+ def get_positions(self):
1971
+ """
1972
+ Return an array containing the floating-point values of the positions.
1973
+ """
1974
+ pos = 0 if self.is_horizontal() else 1
1975
+ return [segment[0, pos] for segment in self.get_segments()]
1976
+
1977
+ def set_positions(self, positions):
1978
+ """Set the positions of the events."""
1979
+ if positions is None:
1980
+ positions = []
1981
+ if np.ndim(positions) != 1:
1982
+ raise ValueError('positions must be one-dimensional')
1983
+ lineoffset = self.get_lineoffset()
1984
+ linelength = self.get_linelength()
1985
+ pos_idx = 0 if self.is_horizontal() else 1
1986
+ segments = np.empty((len(positions), 2, 2))
1987
+ segments[:, :, pos_idx] = np.sort(positions)[:, None]
1988
+ segments[:, 0, 1 - pos_idx] = lineoffset + linelength / 2
1989
+ segments[:, 1, 1 - pos_idx] = lineoffset - linelength / 2
1990
+ self.set_segments(segments)
1991
+
1992
+ def add_positions(self, position):
1993
+ """Add one or more events at the specified positions."""
1994
+ if position is None or (hasattr(position, 'len') and
1995
+ len(position) == 0):
1996
+ return
1997
+ positions = self.get_positions()
1998
+ positions = np.hstack([positions, np.asanyarray(position)])
1999
+ self.set_positions(positions)
2000
+ extend_positions = append_positions = add_positions
2001
+
2002
+ def is_horizontal(self):
2003
+ """True if the eventcollection is horizontal, False if vertical."""
2004
+ return self._is_horizontal
2005
+
2006
+ def get_orientation(self):
2007
+ """
2008
+ Return the orientation of the event line ('horizontal' or 'vertical').
2009
+ """
2010
+ return 'horizontal' if self.is_horizontal() else 'vertical'
2011
+
2012
+ def switch_orientation(self):
2013
+ """
2014
+ Switch the orientation of the event line, either from vertical to
2015
+ horizontal or vice versus.
2016
+ """
2017
+ segments = self.get_segments()
2018
+ for i, segment in enumerate(segments):
2019
+ segments[i] = np.fliplr(segment)
2020
+ self.set_segments(segments)
2021
+ self._is_horizontal = not self.is_horizontal()
2022
+ self.stale = True
2023
+
2024
+ def set_orientation(self, orientation):
2025
+ """
2026
+ Set the orientation of the event line.
2027
+
2028
+ Parameters
2029
+ ----------
2030
+ orientation : {'horizontal', 'vertical'}
2031
+ """
2032
+ is_horizontal = _api.getitem_checked(
2033
+ {"horizontal": True, "vertical": False},
2034
+ orientation=orientation)
2035
+ if is_horizontal == self.is_horizontal():
2036
+ return
2037
+ self.switch_orientation()
2038
+
2039
+ def get_linelength(self):
2040
+ """Return the length of the lines used to mark each event."""
2041
+ return self._linelength
2042
+
2043
+ def set_linelength(self, linelength):
2044
+ """Set the length of the lines used to mark each event."""
2045
+ if linelength == self.get_linelength():
2046
+ return
2047
+ lineoffset = self.get_lineoffset()
2048
+ segments = self.get_segments()
2049
+ pos = 1 if self.is_horizontal() else 0
2050
+ for segment in segments:
2051
+ segment[0, pos] = lineoffset + linelength / 2.
2052
+ segment[1, pos] = lineoffset - linelength / 2.
2053
+ self.set_segments(segments)
2054
+ self._linelength = linelength
2055
+
2056
+ def get_lineoffset(self):
2057
+ """Return the offset of the lines used to mark each event."""
2058
+ return self._lineoffset
2059
+
2060
+ def set_lineoffset(self, lineoffset):
2061
+ """Set the offset of the lines used to mark each event."""
2062
+ if lineoffset == self.get_lineoffset():
2063
+ return
2064
+ linelength = self.get_linelength()
2065
+ segments = self.get_segments()
2066
+ pos = 1 if self.is_horizontal() else 0
2067
+ for segment in segments:
2068
+ segment[0, pos] = lineoffset + linelength / 2.
2069
+ segment[1, pos] = lineoffset - linelength / 2.
2070
+ self.set_segments(segments)
2071
+ self._lineoffset = lineoffset
2072
+
2073
+ def get_linewidth(self):
2074
+ """Get the width of the lines used to mark each event."""
2075
+ return super().get_linewidth()[0]
2076
+
2077
+ def get_linewidths(self):
2078
+ return super().get_linewidth()
2079
+
2080
+ def get_color(self):
2081
+ """Return the color of the lines used to mark each event."""
2082
+ return self.get_colors()[0]
2083
+
2084
+
2085
+ class CircleCollection(_CollectionWithSizes):
2086
+ """A collection of circles, drawn using splines."""
2087
+
2088
+ _factor = np.pi ** (-1/2)
2089
+
2090
+ def __init__(self, sizes, **kwargs):
2091
+ """
2092
+ Parameters
2093
+ ----------
2094
+ sizes : float or array-like
2095
+ The area of each circle in points^2.
2096
+ **kwargs
2097
+ Forwarded to `.Collection`.
2098
+ """
2099
+ super().__init__(**kwargs)
2100
+ self.set_sizes(sizes)
2101
+ self.set_transform(transforms.IdentityTransform())
2102
+ self._paths = [mpath.Path.unit_circle()]
2103
+
2104
+
2105
+ class EllipseCollection(Collection):
2106
+ """A collection of ellipses, drawn using splines."""
2107
+
2108
+ def __init__(self, widths, heights, angles, *, units='points', **kwargs):
2109
+ """
2110
+ Parameters
2111
+ ----------
2112
+ widths : array-like
2113
+ The lengths of the first axes (e.g., major axis lengths).
2114
+ heights : array-like
2115
+ The lengths of second axes.
2116
+ angles : array-like
2117
+ The angles of the first axes, degrees CCW from the x-axis.
2118
+ units : {'points', 'inches', 'dots', 'width', 'height', 'x', 'y', 'xy'}
2119
+ The units in which majors and minors are given; 'width' and
2120
+ 'height' refer to the dimensions of the axes, while 'x' and 'y'
2121
+ refer to the *offsets* data units. 'xy' differs from all others in
2122
+ that the angle as plotted varies with the aspect ratio, and equals
2123
+ the specified angle only when the aspect ratio is unity. Hence
2124
+ it behaves the same as the `~.patches.Ellipse` with
2125
+ ``axes.transData`` as its transform.
2126
+ **kwargs
2127
+ Forwarded to `Collection`.
2128
+ """
2129
+ super().__init__(**kwargs)
2130
+ self.set_widths(widths)
2131
+ self.set_heights(heights)
2132
+ self.set_angles(angles)
2133
+ self._units = units
2134
+ self.set_transform(transforms.IdentityTransform())
2135
+ self._transforms = np.empty((0, 3, 3))
2136
+ self._paths = [mpath.Path.unit_circle()]
2137
+
2138
+ def _set_transforms(self):
2139
+ """Calculate transforms immediately before drawing."""
2140
+
2141
+ ax = self.axes
2142
+ fig = self.get_figure(root=False)
2143
+
2144
+ if self._units == 'xy':
2145
+ sc = 1
2146
+ elif self._units == 'x':
2147
+ sc = ax.bbox.width / ax.viewLim.width
2148
+ elif self._units == 'y':
2149
+ sc = ax.bbox.height / ax.viewLim.height
2150
+ elif self._units == 'inches':
2151
+ sc = fig.dpi
2152
+ elif self._units == 'points':
2153
+ sc = fig.dpi / 72.0
2154
+ elif self._units == 'width':
2155
+ sc = ax.bbox.width
2156
+ elif self._units == 'height':
2157
+ sc = ax.bbox.height
2158
+ elif self._units == 'dots':
2159
+ sc = 1.0
2160
+ else:
2161
+ raise ValueError(f'Unrecognized units: {self._units!r}')
2162
+
2163
+ self._transforms = np.zeros((len(self._widths), 3, 3))
2164
+ widths = self._widths * sc
2165
+ heights = self._heights * sc
2166
+ sin_angle = np.sin(self._angles)
2167
+ cos_angle = np.cos(self._angles)
2168
+ self._transforms[:, 0, 0] = widths * cos_angle
2169
+ self._transforms[:, 0, 1] = heights * -sin_angle
2170
+ self._transforms[:, 1, 0] = widths * sin_angle
2171
+ self._transforms[:, 1, 1] = heights * cos_angle
2172
+ self._transforms[:, 2, 2] = 1.0
2173
+
2174
+ _affine = transforms.Affine2D
2175
+ if self._units == 'xy':
2176
+ m = ax.transData.get_affine().get_matrix().copy()
2177
+ m[:2, 2:] = 0
2178
+ self.set_transform(_affine(m))
2179
+
2180
+ def set_widths(self, widths):
2181
+ """Set the lengths of the first axes (e.g., major axis)."""
2182
+ self._widths = 0.5 * np.asarray(widths).ravel()
2183
+ self.stale = True
2184
+
2185
+ def set_heights(self, heights):
2186
+ """Set the lengths of second axes (e.g., minor axes)."""
2187
+ self._heights = 0.5 * np.asarray(heights).ravel()
2188
+ self.stale = True
2189
+
2190
+ def set_angles(self, angles):
2191
+ """Set the angles of the first axes, degrees CCW from the x-axis."""
2192
+ self._angles = np.deg2rad(angles).ravel()
2193
+ self.stale = True
2194
+
2195
+ def get_widths(self):
2196
+ """Get the lengths of the first axes (e.g., major axis)."""
2197
+ return self._widths * 2
2198
+
2199
+ def get_heights(self):
2200
+ """Set the lengths of second axes (e.g., minor axes)."""
2201
+ return self._heights * 2
2202
+
2203
+ def get_angles(self):
2204
+ """Get the angles of the first axes, degrees CCW from the x-axis."""
2205
+ return np.rad2deg(self._angles)
2206
+
2207
+ @artist.allow_rasterization
2208
+ def draw(self, renderer):
2209
+ self._set_transforms()
2210
+ super().draw(renderer)
2211
+
2212
+
2213
+ class PatchCollection(Collection):
2214
+ """
2215
+ A generic collection of patches.
2216
+
2217
+ PatchCollection draws faster than a large number of equivalent individual
2218
+ Patches. It also makes it easier to assign a colormap to a heterogeneous
2219
+ collection of patches.
2220
+ """
2221
+
2222
+ def __init__(self, patches, *, match_original=False, **kwargs):
2223
+ """
2224
+ Parameters
2225
+ ----------
2226
+ patches : list of `.Patch`
2227
+ A sequence of Patch objects. This list may include
2228
+ a heterogeneous assortment of different patch types.
2229
+
2230
+ match_original : bool, default: False
2231
+ If True, use the colors and linewidths of the original
2232
+ patches. If False, new colors may be assigned by
2233
+ providing the standard collection arguments, facecolor,
2234
+ edgecolor, linewidths, norm or cmap.
2235
+
2236
+ **kwargs
2237
+ All other parameters are forwarded to `.Collection`.
2238
+
2239
+ If any of *edgecolors*, *facecolors*, *linewidths*, *antialiaseds*
2240
+ are None, they default to their `.rcParams` patch setting, in
2241
+ sequence form.
2242
+
2243
+ Notes
2244
+ -----
2245
+ The use of `~matplotlib.cm.ScalarMappable` functionality is optional.
2246
+ If the `~matplotlib.cm.ScalarMappable` matrix ``_A`` has been set (via
2247
+ a call to `~.ScalarMappable.set_array`), at draw time a call to scalar
2248
+ mappable will be made to set the face colors.
2249
+ """
2250
+
2251
+ if match_original:
2252
+ def determine_facecolor(patch):
2253
+ if patch.get_fill():
2254
+ return patch.get_facecolor()
2255
+ return [0, 0, 0, 0]
2256
+
2257
+ kwargs['facecolors'] = [determine_facecolor(p) for p in patches]
2258
+ kwargs['edgecolors'] = [p.get_edgecolor() for p in patches]
2259
+ kwargs['linewidths'] = [p.get_linewidth() for p in patches]
2260
+ kwargs['linestyles'] = [p.get_linestyle() for p in patches]
2261
+ kwargs['antialiaseds'] = [p.get_antialiased() for p in patches]
2262
+
2263
+ super().__init__(**kwargs)
2264
+
2265
+ self.set_paths(patches)
2266
+
2267
+ def set_paths(self, patches):
2268
+ paths = [p.get_transform().transform_path(p.get_path())
2269
+ for p in patches]
2270
+ self._paths = paths
2271
+
2272
+
2273
+ class TriMesh(Collection):
2274
+ """
2275
+ Class for the efficient drawing of a triangular mesh using Gouraud shading.
2276
+
2277
+ A triangular mesh is a `~matplotlib.tri.Triangulation` object.
2278
+ """
2279
+ def __init__(self, triangulation, **kwargs):
2280
+ super().__init__(**kwargs)
2281
+ self._triangulation = triangulation
2282
+ self._shading = 'gouraud'
2283
+
2284
+ self._bbox = transforms.Bbox.unit()
2285
+
2286
+ # Unfortunately this requires a copy, unless Triangulation
2287
+ # was rewritten.
2288
+ xy = np.hstack((triangulation.x.reshape(-1, 1),
2289
+ triangulation.y.reshape(-1, 1)))
2290
+ self._bbox.update_from_data_xy(xy)
2291
+
2292
+ def get_paths(self):
2293
+ if self._paths is None:
2294
+ self.set_paths()
2295
+ return self._paths
2296
+
2297
+ def set_paths(self):
2298
+ self._paths = self.convert_mesh_to_paths(self._triangulation)
2299
+
2300
+ @staticmethod
2301
+ def convert_mesh_to_paths(tri):
2302
+ """
2303
+ Convert a given mesh into a sequence of `.Path` objects.
2304
+
2305
+ This function is primarily of use to implementers of backends that do
2306
+ not directly support meshes.
2307
+ """
2308
+ triangles = tri.get_masked_triangles()
2309
+ verts = np.stack((tri.x[triangles], tri.y[triangles]), axis=-1)
2310
+ return [mpath.Path(x) for x in verts]
2311
+
2312
+ @artist.allow_rasterization
2313
+ def draw(self, renderer):
2314
+ if not self.get_visible():
2315
+ return
2316
+ renderer.open_group(self.__class__.__name__, gid=self.get_gid())
2317
+ transform = self.get_transform()
2318
+
2319
+ # Get a list of triangles and the color at each vertex.
2320
+ tri = self._triangulation
2321
+ triangles = tri.get_masked_triangles()
2322
+
2323
+ verts = np.stack((tri.x[triangles], tri.y[triangles]), axis=-1)
2324
+
2325
+ self.update_scalarmappable()
2326
+ colors = self._facecolors[triangles]
2327
+
2328
+ gc = renderer.new_gc()
2329
+ self._set_gc_clip(gc)
2330
+ gc.set_linewidth(self.get_linewidth()[0])
2331
+ renderer.draw_gouraud_triangles(gc, verts, colors, transform.frozen())
2332
+ gc.restore()
2333
+ renderer.close_group(self.__class__.__name__)
2334
+
2335
+
2336
+ class _MeshData:
2337
+ r"""
2338
+ Class for managing the two dimensional coordinates of Quadrilateral meshes
2339
+ and the associated data with them. This class is a mixin and is intended to
2340
+ be used with another collection that will implement the draw separately.
2341
+
2342
+ A quadrilateral mesh is a grid of M by N adjacent quadrilaterals that are
2343
+ defined via a (M+1, N+1) grid of vertices. The quadrilateral (m, n) is
2344
+ defined by the vertices ::
2345
+
2346
+ (m+1, n) ----------- (m+1, n+1)
2347
+ / /
2348
+ / /
2349
+ / /
2350
+ (m, n) -------- (m, n+1)
2351
+
2352
+ The mesh need not be regular and the polygons need not be convex.
2353
+
2354
+ Parameters
2355
+ ----------
2356
+ coordinates : (M+1, N+1, 2) array-like
2357
+ The vertices. ``coordinates[m, n]`` specifies the (x, y) coordinates
2358
+ of vertex (m, n).
2359
+
2360
+ shading : {'flat', 'gouraud'}, default: 'flat'
2361
+ """
2362
+ def __init__(self, coordinates, *, shading='flat'):
2363
+ _api.check_shape((None, None, 2), coordinates=coordinates)
2364
+ self._coordinates = coordinates
2365
+ self._shading = shading
2366
+
2367
+ def set_array(self, A):
2368
+ """
2369
+ Set the data values.
2370
+
2371
+ Parameters
2372
+ ----------
2373
+ A : array-like
2374
+ The mesh data. Supported array shapes are:
2375
+
2376
+ - (M, N) or (M*N,): a mesh with scalar data. The values are mapped
2377
+ to colors using normalization and a colormap. See parameters
2378
+ *norm*, *cmap*, *vmin*, *vmax*.
2379
+ - (M, N, 3): an image with RGB values (0-1 float or 0-255 int).
2380
+ - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int),
2381
+ i.e. including transparency.
2382
+
2383
+ If the values are provided as a 2D grid, the shape must match the
2384
+ coordinates grid. If the values are 1D, they are reshaped to 2D.
2385
+ M, N follow from the coordinates grid, where the coordinates grid
2386
+ shape is (M, N) for 'gouraud' *shading* and (M+1, N+1) for 'flat'
2387
+ shading.
2388
+ """
2389
+ height, width = self._coordinates.shape[0:-1]
2390
+ if self._shading == 'flat':
2391
+ h, w = height - 1, width - 1
2392
+ else:
2393
+ h, w = height, width
2394
+ ok_shapes = [(h, w, 3), (h, w, 4), (h, w), (h * w,)]
2395
+ if A is not None:
2396
+ shape = np.shape(A)
2397
+ if shape not in ok_shapes:
2398
+ raise ValueError(
2399
+ f"For X ({width}) and Y ({height}) with {self._shading} "
2400
+ f"shading, A should have shape "
2401
+ f"{' or '.join(map(str, ok_shapes))}, not {A.shape}")
2402
+ return super().set_array(A)
2403
+
2404
+ def get_coordinates(self):
2405
+ """
2406
+ Return the vertices of the mesh as an (M+1, N+1, 2) array.
2407
+
2408
+ M, N are the number of quadrilaterals in the rows / columns of the
2409
+ mesh, corresponding to (M+1, N+1) vertices.
2410
+ The last dimension specifies the components (x, y).
2411
+ """
2412
+ return self._coordinates
2413
+
2414
+ def get_edgecolor(self):
2415
+ # docstring inherited
2416
+ # Note that we want to return an array of shape (N*M, 4)
2417
+ # a flattened RGBA collection
2418
+ return super().get_edgecolor().reshape(-1, 4)
2419
+
2420
+ def get_facecolor(self):
2421
+ # docstring inherited
2422
+ # Note that we want to return an array of shape (N*M, 4)
2423
+ # a flattened RGBA collection
2424
+ return super().get_facecolor().reshape(-1, 4)
2425
+
2426
+ @staticmethod
2427
+ def _convert_mesh_to_paths(coordinates):
2428
+ """
2429
+ Convert a given mesh into a sequence of `.Path` objects.
2430
+
2431
+ This function is primarily of use to implementers of backends that do
2432
+ not directly support quadmeshes.
2433
+ """
2434
+ if isinstance(coordinates, np.ma.MaskedArray):
2435
+ c = coordinates.data
2436
+ else:
2437
+ c = coordinates
2438
+ points = np.concatenate([
2439
+ c[:-1, :-1],
2440
+ c[:-1, 1:],
2441
+ c[1:, 1:],
2442
+ c[1:, :-1],
2443
+ c[:-1, :-1]
2444
+ ], axis=2).reshape((-1, 5, 2))
2445
+ return [mpath.Path(x) for x in points]
2446
+
2447
+ def _convert_mesh_to_triangles(self, coordinates):
2448
+ """
2449
+ Convert a given mesh into a sequence of triangles, each point
2450
+ with its own color. The result can be used to construct a call to
2451
+ `~.RendererBase.draw_gouraud_triangles`.
2452
+ """
2453
+ if isinstance(coordinates, np.ma.MaskedArray):
2454
+ p = coordinates.data
2455
+ else:
2456
+ p = coordinates
2457
+
2458
+ p_a = p[:-1, :-1]
2459
+ p_b = p[:-1, 1:]
2460
+ p_c = p[1:, 1:]
2461
+ p_d = p[1:, :-1]
2462
+ p_center = (p_a + p_b + p_c + p_d) / 4.0
2463
+ triangles = np.concatenate([
2464
+ p_a, p_b, p_center,
2465
+ p_b, p_c, p_center,
2466
+ p_c, p_d, p_center,
2467
+ p_d, p_a, p_center,
2468
+ ], axis=2).reshape((-1, 3, 2))
2469
+
2470
+ c = self.get_facecolor().reshape((*coordinates.shape[:2], 4))
2471
+ z = self.get_array()
2472
+ mask = z.mask if np.ma.is_masked(z) else None
2473
+ if mask is not None:
2474
+ c[mask, 3] = np.nan
2475
+ c_a = c[:-1, :-1]
2476
+ c_b = c[:-1, 1:]
2477
+ c_c = c[1:, 1:]
2478
+ c_d = c[1:, :-1]
2479
+ c_center = (c_a + c_b + c_c + c_d) / 4.0
2480
+ colors = np.concatenate([
2481
+ c_a, c_b, c_center,
2482
+ c_b, c_c, c_center,
2483
+ c_c, c_d, c_center,
2484
+ c_d, c_a, c_center,
2485
+ ], axis=2).reshape((-1, 3, 4))
2486
+ tmask = np.isnan(colors[..., 2, 3])
2487
+ return triangles[~tmask], colors[~tmask]
2488
+
2489
+
2490
+ class QuadMesh(_MeshData, Collection):
2491
+ r"""
2492
+ Class for the efficient drawing of a quadrilateral mesh.
2493
+
2494
+ A quadrilateral mesh is a grid of M by N adjacent quadrilaterals that are
2495
+ defined via a (M+1, N+1) grid of vertices. The quadrilateral (m, n) is
2496
+ defined by the vertices ::
2497
+
2498
+ (m+1, n) ----------- (m+1, n+1)
2499
+ / /
2500
+ / /
2501
+ / /
2502
+ (m, n) -------- (m, n+1)
2503
+
2504
+ The mesh need not be regular and the polygons need not be convex.
2505
+
2506
+ Parameters
2507
+ ----------
2508
+ coordinates : (M+1, N+1, 2) array-like
2509
+ The vertices. ``coordinates[m, n]`` specifies the (x, y) coordinates
2510
+ of vertex (m, n).
2511
+
2512
+ antialiased : bool, default: True
2513
+
2514
+ shading : {'flat', 'gouraud'}, default: 'flat'
2515
+
2516
+ Notes
2517
+ -----
2518
+ Unlike other `.Collection`\s, the default *pickradius* of `.QuadMesh` is 0,
2519
+ i.e. `~.Artist.contains` checks whether the test point is within any of the
2520
+ mesh quadrilaterals.
2521
+
2522
+ """
2523
+
2524
+ def __init__(self, coordinates, *, antialiased=True, shading='flat',
2525
+ **kwargs):
2526
+ kwargs.setdefault("pickradius", 0)
2527
+ super().__init__(coordinates=coordinates, shading=shading)
2528
+ Collection.__init__(self, **kwargs)
2529
+
2530
+ self._antialiased = antialiased
2531
+ self._bbox = transforms.Bbox.unit()
2532
+ self._bbox.update_from_data_xy(self._coordinates.reshape(-1, 2))
2533
+ self.set_mouseover(False)
2534
+
2535
+ def get_paths(self):
2536
+ if self._paths is None:
2537
+ self.set_paths()
2538
+ return self._paths
2539
+
2540
+ def set_paths(self):
2541
+ self._paths = self._convert_mesh_to_paths(self._coordinates)
2542
+ self.stale = True
2543
+
2544
+ def get_datalim(self, transData):
2545
+ return (self.get_transform() - transData).transform_bbox(self._bbox)
2546
+
2547
+ @artist.allow_rasterization
2548
+ def draw(self, renderer):
2549
+ if not self.get_visible():
2550
+ return
2551
+ renderer.open_group(self.__class__.__name__, self.get_gid())
2552
+ transform = self.get_transform()
2553
+ offset_trf = self.get_offset_transform()
2554
+ offsets = self.get_offsets()
2555
+
2556
+ if self.have_units():
2557
+ xs = self.convert_xunits(offsets[:, 0])
2558
+ ys = self.convert_yunits(offsets[:, 1])
2559
+ offsets = np.column_stack([xs, ys])
2560
+
2561
+ self.update_scalarmappable()
2562
+
2563
+ if not transform.is_affine:
2564
+ coordinates = self._coordinates.reshape((-1, 2))
2565
+ coordinates = transform.transform(coordinates)
2566
+ coordinates = coordinates.reshape(self._coordinates.shape)
2567
+ transform = transforms.IdentityTransform()
2568
+ else:
2569
+ coordinates = self._coordinates
2570
+
2571
+ if not offset_trf.is_affine:
2572
+ offsets = offset_trf.transform_non_affine(offsets)
2573
+ offset_trf = offset_trf.get_affine()
2574
+
2575
+ gc = renderer.new_gc()
2576
+ gc.set_snap(self.get_snap())
2577
+ self._set_gc_clip(gc)
2578
+ gc.set_linewidth(self.get_linewidth()[0])
2579
+
2580
+ if self._shading == 'gouraud':
2581
+ triangles, colors = self._convert_mesh_to_triangles(coordinates)
2582
+ renderer.draw_gouraud_triangles(
2583
+ gc, triangles, colors, transform.frozen())
2584
+ else:
2585
+ renderer.draw_quad_mesh(
2586
+ gc, transform.frozen(),
2587
+ coordinates.shape[1] - 1, coordinates.shape[0] - 1,
2588
+ coordinates, offsets, offset_trf,
2589
+ # Backends expect flattened rgba arrays (n*m, 4) for fc and ec
2590
+ self.get_facecolor().reshape((-1, 4)),
2591
+ self._antialiased, self.get_edgecolors().reshape((-1, 4)))
2592
+ gc.restore()
2593
+ renderer.close_group(self.__class__.__name__)
2594
+ self.stale = False
2595
+
2596
+ def get_cursor_data(self, event):
2597
+ contained, info = self.contains(event)
2598
+ if contained and self.get_array() is not None:
2599
+ return self.get_array().ravel()[info["ind"]]
2600
+ return None
2601
+
2602
+
2603
+ class PolyQuadMesh(_MeshData, PolyCollection):
2604
+ """
2605
+ Class for drawing a quadrilateral mesh as individual Polygons.
2606
+
2607
+ A quadrilateral mesh is a grid of M by N adjacent quadrilaterals that are
2608
+ defined via a (M+1, N+1) grid of vertices. The quadrilateral (m, n) is
2609
+ defined by the vertices ::
2610
+
2611
+ (m+1, n) ----------- (m+1, n+1)
2612
+ / /
2613
+ / /
2614
+ / /
2615
+ (m, n) -------- (m, n+1)
2616
+
2617
+ The mesh need not be regular and the polygons need not be convex.
2618
+
2619
+ Parameters
2620
+ ----------
2621
+ coordinates : (M+1, N+1, 2) array-like
2622
+ The vertices. ``coordinates[m, n]`` specifies the (x, y) coordinates
2623
+ of vertex (m, n).
2624
+
2625
+ Notes
2626
+ -----
2627
+ Unlike `.QuadMesh`, this class will draw each cell as an individual Polygon.
2628
+ This is significantly slower, but allows for more flexibility when wanting
2629
+ to add additional properties to the cells, such as hatching.
2630
+
2631
+ Another difference from `.QuadMesh` is that if any of the vertices or data
2632
+ of a cell are masked, that Polygon will **not** be drawn and it won't be in
2633
+ the list of paths returned.
2634
+ """
2635
+
2636
+ def __init__(self, coordinates, **kwargs):
2637
+ super().__init__(coordinates=coordinates)
2638
+ PolyCollection.__init__(self, verts=[], **kwargs)
2639
+ # Setting the verts updates the paths of the PolyCollection
2640
+ # This is called after the initializers to make sure the kwargs
2641
+ # have all been processed and available for the masking calculations
2642
+ self._set_unmasked_verts()
2643
+
2644
+ def _get_unmasked_polys(self):
2645
+ """Get the unmasked regions using the coordinates and array"""
2646
+ # mask(X) | mask(Y)
2647
+ mask = np.any(np.ma.getmaskarray(self._coordinates), axis=-1)
2648
+
2649
+ # We want the shape of the polygon, which is the corner of each X/Y array
2650
+ mask = (mask[0:-1, 0:-1] | mask[1:, 1:] | mask[0:-1, 1:] | mask[1:, 0:-1])
2651
+ arr = self.get_array()
2652
+ if arr is not None:
2653
+ arr = np.ma.getmaskarray(arr)
2654
+ if arr.ndim == 3:
2655
+ # RGB(A) case
2656
+ mask |= np.any(arr, axis=-1)
2657
+ elif arr.ndim == 2:
2658
+ mask |= arr
2659
+ else:
2660
+ mask |= arr.reshape(self._coordinates[:-1, :-1, :].shape[:2])
2661
+ return ~mask
2662
+
2663
+ def _set_unmasked_verts(self):
2664
+ X = self._coordinates[..., 0]
2665
+ Y = self._coordinates[..., 1]
2666
+
2667
+ unmask = self._get_unmasked_polys()
2668
+ X1 = np.ma.filled(X[:-1, :-1])[unmask]
2669
+ Y1 = np.ma.filled(Y[:-1, :-1])[unmask]
2670
+ X2 = np.ma.filled(X[1:, :-1])[unmask]
2671
+ Y2 = np.ma.filled(Y[1:, :-1])[unmask]
2672
+ X3 = np.ma.filled(X[1:, 1:])[unmask]
2673
+ Y3 = np.ma.filled(Y[1:, 1:])[unmask]
2674
+ X4 = np.ma.filled(X[:-1, 1:])[unmask]
2675
+ Y4 = np.ma.filled(Y[:-1, 1:])[unmask]
2676
+ npoly = len(X1)
2677
+
2678
+ xy = np.ma.stack([X1, Y1, X2, Y2, X3, Y3, X4, Y4, X1, Y1], axis=-1)
2679
+ verts = xy.reshape((npoly, 5, 2))
2680
+ self.set_verts(verts)
2681
+
2682
+ def get_edgecolor(self):
2683
+ # docstring inherited
2684
+ # We only want to return the facecolors of the polygons
2685
+ # that were drawn.
2686
+ ec = super().get_edgecolor()
2687
+ unmasked_polys = self._get_unmasked_polys().ravel()
2688
+ if len(ec) != len(unmasked_polys):
2689
+ # Mapping is off
2690
+ return ec
2691
+ return ec[unmasked_polys, :]
2692
+
2693
+ def get_facecolor(self):
2694
+ # docstring inherited
2695
+ # We only want to return the facecolors of the polygons
2696
+ # that were drawn.
2697
+ fc = super().get_facecolor()
2698
+ unmasked_polys = self._get_unmasked_polys().ravel()
2699
+ if len(fc) != len(unmasked_polys):
2700
+ # Mapping is off
2701
+ return fc
2702
+ return fc[unmasked_polys, :]
2703
+
2704
+ def set_array(self, A):
2705
+ # docstring inherited
2706
+ prev_unmask = self._get_unmasked_polys()
2707
+ super().set_array(A)
2708
+ # If the mask has changed at all we need to update
2709
+ # the set of Polys that we are drawing
2710
+ if not np.array_equal(prev_unmask, self._get_unmasked_polys()):
2711
+ self._set_unmasked_verts()