matplotlib-rs 0.0.8__cp315-cp315-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (352) hide show
  1. docs/releases/0.0.1.md +268 -0
  2. docs/releases/0.0.2.md +69 -0
  3. docs/releases/0.0.3.md +80 -0
  4. docs/releases/0.0.4.md +73 -0
  5. docs/releases/0.0.5.md +24 -0
  6. docs/releases/0.0.6.md +24 -0
  7. docs/releases/0.0.7.md +24 -0
  8. docs/releases/0.0.8.md +16 -0
  9. licenses/LICENSE_CONTOURPY +29 -0
  10. licenses/LICENSE_CYCLER +27 -0
  11. licenses/LICENSE_DATEUTIL +54 -0
  12. licenses/LICENSE_KIWISOLVER +71 -0
  13. licenses/LICENSE_LIBWEBP +56 -0
  14. licenses/LICENSE_MATPLOTLIB +1253 -0
  15. licenses/LICENSE_PYPARSING +20 -0
  16. licenses/LICENSE_QHULL +39 -0
  17. licenses/LICENSE_SIX +18 -0
  18. matplotlib_rs/__init__.py +1683 -0
  19. matplotlib_rs/__main__.py +27 -0
  20. matplotlib_rs/_afm.py +500 -0
  21. matplotlib_rs/_animation_data.py +263 -0
  22. matplotlib_rs/_api/__init__.py +495 -0
  23. matplotlib_rs/_api/deprecation.py +534 -0
  24. matplotlib_rs/_axis_py.py +2991 -0
  25. matplotlib_rs/_blocking_input.py +31 -0
  26. matplotlib_rs/_cm.py +1500 -0
  27. matplotlib_rs/_cm_bivar.py +1289 -0
  28. matplotlib_rs/_cm_listed.py +2848 -0
  29. matplotlib_rs/_cm_multivar.py +167 -0
  30. matplotlib_rs/_color_data.py +1142 -0
  31. matplotlib_rs/_colormap.py +132 -0
  32. matplotlib_rs/_constrained_layout.py +825 -0
  33. matplotlib_rs/_contour.py +108 -0
  34. matplotlib_rs/_doc_cache.py +12214 -0
  35. matplotlib_rs/_docstring.py +142 -0
  36. matplotlib_rs/_enums.py +178 -0
  37. matplotlib_rs/_figure_rs.py +294 -0
  38. matplotlib_rs/_fontconfig_pattern.py +129 -0
  39. matplotlib_rs/_foreign.py +220 -0
  40. matplotlib_rs/_hook.py +94 -0
  41. matplotlib_rs/_image.py +160 -0
  42. matplotlib_rs/_imageio.py +229 -0
  43. matplotlib_rs/_internal_utils.py +65 -0
  44. matplotlib_rs/_kiwi.py +484 -0
  45. matplotlib_rs/_layoutgrid.py +549 -0
  46. matplotlib_rs/_live.py +192 -0
  47. matplotlib_rs/_mathtext.py +3103 -0
  48. matplotlib_rs/_mathtext_data.py +1811 -0
  49. matplotlib_rs/_mplrs.cp315-win_amd64.pyd +0 -0
  50. matplotlib_rs/_path.py +25 -0
  51. matplotlib_rs/_png.py +162 -0
  52. matplotlib_rs/_pylab_helpers.py +137 -0
  53. matplotlib_rs/_qhull.py +66 -0
  54. matplotlib_rs/_rcpush.py +84 -0
  55. matplotlib_rs/_spines_rs.py +108 -0
  56. matplotlib_rs/_style_helpers.py +52 -0
  57. matplotlib_rs/_text_helpers.py +51 -0
  58. matplotlib_rs/_tight_bbox.py +85 -0
  59. matplotlib_rs/_tight_layout.py +302 -0
  60. matplotlib_rs/_tri.py +140 -0
  61. matplotlib_rs/_type1font.py +1228 -0
  62. matplotlib_rs/_vendor/__init__.py +8 -0
  63. matplotlib_rs/_vendor/cycler.py +574 -0
  64. matplotlib_rs/_vendor/dateutil/__init__.py +27 -0
  65. matplotlib_rs/_vendor/dateutil/_common.py +44 -0
  66. matplotlib_rs/_vendor/dateutil/_tzdata_impl.py +148 -0
  67. matplotlib_rs/_vendor/dateutil/_version.py +5 -0
  68. matplotlib_rs/_vendor/dateutil/easter.py +90 -0
  69. matplotlib_rs/_vendor/dateutil/parser/__init__.py +62 -0
  70. matplotlib_rs/_vendor/dateutil/parser/_parser.py +1614 -0
  71. matplotlib_rs/_vendor/dateutil/parser/isoparser.py +417 -0
  72. matplotlib_rs/_vendor/dateutil/relativedelta.py +597 -0
  73. matplotlib_rs/_vendor/dateutil/rrule.py +1765 -0
  74. matplotlib_rs/_vendor/dateutil/tz/__init__.py +61 -0
  75. matplotlib_rs/_vendor/dateutil/tz/_common.py +420 -0
  76. matplotlib_rs/_vendor/dateutil/tz/_factories.py +81 -0
  77. matplotlib_rs/_vendor/dateutil/tz/_tzfile.py +1429 -0
  78. matplotlib_rs/_vendor/dateutil/tz/_tzpath.py +105 -0
  79. matplotlib_rs/_vendor/dateutil/tz/tz.py +1473 -0
  80. matplotlib_rs/_vendor/dateutil/tz/win.py +371 -0
  81. matplotlib_rs/_vendor/dateutil/tzwin.py +3 -0
  82. matplotlib_rs/_vendor/dateutil/utils.py +72 -0
  83. matplotlib_rs/_vendor/dateutil/zoneinfo/__init__.py +234 -0
  84. matplotlib_rs/_vendor/pyparsing/__init__.py +414 -0
  85. matplotlib_rs/_vendor/pyparsing/actions.py +265 -0
  86. matplotlib_rs/_vendor/pyparsing/common.py +571 -0
  87. matplotlib_rs/_vendor/pyparsing/core.py +6973 -0
  88. matplotlib_rs/_vendor/pyparsing/exceptions.py +354 -0
  89. matplotlib_rs/_vendor/pyparsing/helpers.py +1770 -0
  90. matplotlib_rs/_vendor/pyparsing/results.py +929 -0
  91. matplotlib_rs/_vendor/pyparsing/testing.py +399 -0
  92. matplotlib_rs/_vendor/pyparsing/unicode.py +357 -0
  93. matplotlib_rs/_vendor/pyparsing/util.py +515 -0
  94. matplotlib_rs/_vendor/pyparsing/warnings.py +11 -0
  95. matplotlib_rs/_vendor/six.py +1004 -0
  96. matplotlib_rs/animation.py +1843 -0
  97. matplotlib_rs/artist.py +2302 -0
  98. matplotlib_rs/axes/__init__.py +19 -0
  99. matplotlib_rs/axes/_axes.py +9402 -0
  100. matplotlib_rs/axes/_bar.py +185 -0
  101. matplotlib_rs/axes/_base.py +5236 -0
  102. matplotlib_rs/axes/_base_rs.py +727 -0
  103. matplotlib_rs/axes/_boxplot.py +391 -0
  104. matplotlib_rs/axes/_hist.py +99 -0
  105. matplotlib_rs/axes/_secondary_axes.py +357 -0
  106. matplotlib_rs/axis.py +1963 -0
  107. matplotlib_rs/backend_bases.py +3760 -0
  108. matplotlib_rs/backend_managers.py +388 -0
  109. matplotlib_rs/backend_tools.py +1002 -0
  110. matplotlib_rs/backends/__init__.py +6 -0
  111. matplotlib_rs/backends/_backend_pdf_ps.py +451 -0
  112. matplotlib_rs/backends/backend_agg.py +552 -0
  113. matplotlib_rs/backends/backend_mixed.py +123 -0
  114. matplotlib_rs/backends/backend_pdf.py +2711 -0
  115. matplotlib_rs/backends/backend_pgf.py +1031 -0
  116. matplotlib_rs/backends/backend_ps.py +1491 -0
  117. matplotlib_rs/backends/backend_svg.py +1395 -0
  118. matplotlib_rs/backends/backend_template.py +214 -0
  119. matplotlib_rs/backends/registry.py +423 -0
  120. matplotlib_rs/bezier.py +691 -0
  121. matplotlib_rs/category.py +236 -0
  122. matplotlib_rs/cbook.py +2762 -0
  123. matplotlib_rs/cm.py +251 -0
  124. matplotlib_rs/collections.py +2711 -0
  125. matplotlib_rs/colorbar.py +1586 -0
  126. matplotlib_rs/colorizer.py +909 -0
  127. matplotlib_rs/colors.py +4278 -0
  128. matplotlib_rs/container.py +256 -0
  129. matplotlib_rs/contour.py +1756 -0
  130. matplotlib_rs/dates.py +1847 -0
  131. matplotlib_rs/dviread.py +1386 -0
  132. matplotlib_rs/figure.py +3815 -0
  133. matplotlib_rs/font_manager.py +1855 -0
  134. matplotlib_rs/ft2font.py +515 -0
  135. matplotlib_rs/gridspec.py +808 -0
  136. matplotlib_rs/hatch.py +244 -0
  137. matplotlib_rs/image.py +1863 -0
  138. matplotlib_rs/inset.py +291 -0
  139. matplotlib_rs/layout_engine.py +310 -0
  140. matplotlib_rs/legend.py +1480 -0
  141. matplotlib_rs/legend_handler.py +812 -0
  142. matplotlib_rs/lines.py +1886 -0
  143. matplotlib_rs/markers.py +908 -0
  144. matplotlib_rs/mathtext.py +141 -0
  145. matplotlib_rs/mlab.py +959 -0
  146. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-Bold.ttf +0 -0
  147. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-BoldOblique.ttf +0 -0
  148. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-Oblique.ttf +0 -0
  149. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans.ttf +0 -0
  150. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansDisplay.ttf +0 -0
  151. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-Bold.ttf +0 -0
  152. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-BoldOblique.ttf +0 -0
  153. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-Oblique.ttf +0 -0
  154. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono.ttf +0 -0
  155. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-Bold.ttf +0 -0
  156. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-BoldItalic.ttf +0 -0
  157. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-Italic.ttf +0 -0
  158. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif.ttf +0 -0
  159. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerifDisplay.ttf +0 -0
  160. matplotlib_rs/mpl-data/fonts/ttf/LICENSE_DEJAVU +99 -0
  161. matplotlib_rs/mpl-data/fonts/ttf/LICENSE_STIX +124 -0
  162. matplotlib_rs/mpl-data/fonts/ttf/LastResortHE-Regular.ttf +0 -0
  163. matplotlib_rs/mpl-data/fonts/ttf/STIXGeneral.ttf +0 -0
  164. matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralBol.ttf +0 -0
  165. matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralBolIta.ttf +0 -0
  166. matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralItalic.ttf +0 -0
  167. matplotlib_rs/mpl-data/fonts/ttf/STIXNonUni.ttf +0 -0
  168. matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniBol.ttf +0 -0
  169. matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniBolIta.ttf +0 -0
  170. matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniIta.ttf +0 -0
  171. matplotlib_rs/mpl-data/fonts/ttf/STIXSizFiveSymReg.ttf +0 -0
  172. matplotlib_rs/mpl-data/fonts/ttf/STIXSizFourSymBol.ttf +0 -0
  173. matplotlib_rs/mpl-data/fonts/ttf/STIXSizFourSymReg.ttf +0 -0
  174. matplotlib_rs/mpl-data/fonts/ttf/STIXSizOneSymBol.ttf +0 -0
  175. matplotlib_rs/mpl-data/fonts/ttf/STIXSizOneSymReg.ttf +0 -0
  176. matplotlib_rs/mpl-data/fonts/ttf/STIXSizThreeSymBol.ttf +0 -0
  177. matplotlib_rs/mpl-data/fonts/ttf/STIXSizThreeSymReg.ttf +0 -0
  178. matplotlib_rs/mpl-data/fonts/ttf/STIXSizTwoSymBol.ttf +0 -0
  179. matplotlib_rs/mpl-data/fonts/ttf/STIXSizTwoSymReg.ttf +0 -0
  180. matplotlib_rs/mpl-data/fonts/ttf/cmb10.ttf +0 -0
  181. matplotlib_rs/mpl-data/fonts/ttf/cmex10.ttf +0 -0
  182. matplotlib_rs/mpl-data/fonts/ttf/cmmi10.ttf +0 -0
  183. matplotlib_rs/mpl-data/fonts/ttf/cmr10.ttf +0 -0
  184. matplotlib_rs/mpl-data/fonts/ttf/cmss10.ttf +0 -0
  185. matplotlib_rs/mpl-data/fonts/ttf/cmsy10.ttf +0 -0
  186. matplotlib_rs/mpl-data/fonts/ttf/cmti10.ttf +0 -0
  187. matplotlib_rs/mpl-data/fonts/ttf/cmtt10.ttf +0 -0
  188. matplotlib_rs/mpl-data/images/back-symbolic.svg +46 -0
  189. matplotlib_rs/mpl-data/images/back.pdf +0 -0
  190. matplotlib_rs/mpl-data/images/back.png +0 -0
  191. matplotlib_rs/mpl-data/images/back.svg +46 -0
  192. matplotlib_rs/mpl-data/images/back_large.png +0 -0
  193. matplotlib_rs/mpl-data/images/filesave-symbolic.svg +68 -0
  194. matplotlib_rs/mpl-data/images/filesave.pdf +72 -0
  195. matplotlib_rs/mpl-data/images/filesave.png +0 -0
  196. matplotlib_rs/mpl-data/images/filesave.svg +68 -0
  197. matplotlib_rs/mpl-data/images/filesave_large.png +0 -0
  198. matplotlib_rs/mpl-data/images/forward-symbolic.svg +46 -0
  199. matplotlib_rs/mpl-data/images/forward.pdf +0 -0
  200. matplotlib_rs/mpl-data/images/forward.png +0 -0
  201. matplotlib_rs/mpl-data/images/forward.svg +46 -0
  202. matplotlib_rs/mpl-data/images/forward_large.png +0 -0
  203. matplotlib_rs/mpl-data/images/hand.pdf +0 -0
  204. matplotlib_rs/mpl-data/images/hand.png +0 -0
  205. matplotlib_rs/mpl-data/images/hand.svg +130 -0
  206. matplotlib_rs/mpl-data/images/help-symbolic.svg +52 -0
  207. matplotlib_rs/mpl-data/images/help.pdf +71 -0
  208. matplotlib_rs/mpl-data/images/help.png +0 -0
  209. matplotlib_rs/mpl-data/images/help.svg +52 -0
  210. matplotlib_rs/mpl-data/images/help_large.png +0 -0
  211. matplotlib_rs/mpl-data/images/home-symbolic.svg +59 -0
  212. matplotlib_rs/mpl-data/images/home.pdf +0 -0
  213. matplotlib_rs/mpl-data/images/home.png +0 -0
  214. matplotlib_rs/mpl-data/images/home.svg +59 -0
  215. matplotlib_rs/mpl-data/images/home_large.png +0 -0
  216. matplotlib_rs/mpl-data/images/matplotlib.pdf +0 -0
  217. matplotlib_rs/mpl-data/images/matplotlib.png +0 -0
  218. matplotlib_rs/mpl-data/images/matplotlib.svg +3171 -0
  219. matplotlib_rs/mpl-data/images/matplotlib_large.png +0 -0
  220. matplotlib_rs/mpl-data/images/move-symbolic.svg +73 -0
  221. matplotlib_rs/mpl-data/images/move.pdf +0 -0
  222. matplotlib_rs/mpl-data/images/move.png +0 -0
  223. matplotlib_rs/mpl-data/images/move.svg +73 -0
  224. matplotlib_rs/mpl-data/images/move_large.png +0 -0
  225. matplotlib_rs/mpl-data/images/qt4_editor_options.pdf +0 -0
  226. matplotlib_rs/mpl-data/images/qt4_editor_options.png +0 -0
  227. matplotlib_rs/mpl-data/images/qt4_editor_options.svg +48 -0
  228. matplotlib_rs/mpl-data/images/qt4_editor_options_large.png +0 -0
  229. matplotlib_rs/mpl-data/images/subplots-symbolic.svg +81 -0
  230. matplotlib_rs/mpl-data/images/subplots.pdf +0 -0
  231. matplotlib_rs/mpl-data/images/subplots.png +0 -0
  232. matplotlib_rs/mpl-data/images/subplots.svg +81 -0
  233. matplotlib_rs/mpl-data/images/subplots_large.png +0 -0
  234. matplotlib_rs/mpl-data/images/zoom_to_rect-symbolic.svg +40 -0
  235. matplotlib_rs/mpl-data/images/zoom_to_rect.pdf +69 -0
  236. matplotlib_rs/mpl-data/images/zoom_to_rect.png +0 -0
  237. matplotlib_rs/mpl-data/images/zoom_to_rect.svg +40 -0
  238. matplotlib_rs/mpl-data/images/zoom_to_rect_large.png +0 -0
  239. matplotlib_rs/mpl-data/kpsewhich.lua +4 -0
  240. matplotlib_rs/mpl-data/matplotlibrc +849 -0
  241. matplotlib_rs/mpl-data/plot_directive/plot_directive.css +16 -0
  242. matplotlib_rs/mpl-data/sample_data/Minduka_Present_Blue_Pack.png +0 -0
  243. matplotlib_rs/mpl-data/sample_data/README.txt +2 -0
  244. matplotlib_rs/mpl-data/sample_data/Stocks.csv +526 -0
  245. matplotlib_rs/mpl-data/sample_data/axes_grid/bivariate_normal.npy +0 -0
  246. matplotlib_rs/mpl-data/sample_data/data_x_x2_x3.csv +11 -0
  247. matplotlib_rs/mpl-data/sample_data/eeg.dat +0 -0
  248. matplotlib_rs/mpl-data/sample_data/embedding_in_wx3.xrc +65 -0
  249. matplotlib_rs/mpl-data/sample_data/goog.npz +0 -0
  250. matplotlib_rs/mpl-data/sample_data/grace_hopper.jpg +0 -0
  251. matplotlib_rs/mpl-data/sample_data/jacksboro_fault_dem.npz +0 -0
  252. matplotlib_rs/mpl-data/sample_data/logo2.png +0 -0
  253. matplotlib_rs/mpl-data/sample_data/membrane.dat +0 -0
  254. matplotlib_rs/mpl-data/sample_data/msft.csv +66 -0
  255. matplotlib_rs/mpl-data/sample_data/s1045.ima.gz +0 -0
  256. matplotlib_rs/mpl-data/sample_data/topobathy.npz +0 -0
  257. matplotlib_rs/mpl-data/stylelib/Solarize_Light2.mplstyle +53 -0
  258. matplotlib_rs/mpl-data/stylelib/_classic_test_patch.mplstyle +8 -0
  259. matplotlib_rs/mpl-data/stylelib/_mpl-gallery-nogrid.mplstyle +19 -0
  260. matplotlib_rs/mpl-data/stylelib/_mpl-gallery.mplstyle +19 -0
  261. matplotlib_rs/mpl-data/stylelib/bmh.mplstyle +27 -0
  262. matplotlib_rs/mpl-data/stylelib/classic.mplstyle +491 -0
  263. matplotlib_rs/mpl-data/stylelib/dark_background.mplstyle +26 -0
  264. matplotlib_rs/mpl-data/stylelib/fast.mplstyle +11 -0
  265. matplotlib_rs/mpl-data/stylelib/fivethirtyeight.mplstyle +37 -0
  266. matplotlib_rs/mpl-data/stylelib/ggplot.mplstyle +39 -0
  267. matplotlib_rs/mpl-data/stylelib/grayscale.mplstyle +29 -0
  268. matplotlib_rs/mpl-data/stylelib/petroff10.mplstyle +5 -0
  269. matplotlib_rs/mpl-data/stylelib/petroff6.mplstyle +5 -0
  270. matplotlib_rs/mpl-data/stylelib/petroff8.mplstyle +5 -0
  271. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-bright.mplstyle +3 -0
  272. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-colorblind.mplstyle +3 -0
  273. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-dark-palette.mplstyle +3 -0
  274. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-dark.mplstyle +30 -0
  275. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-darkgrid.mplstyle +30 -0
  276. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-deep.mplstyle +3 -0
  277. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-muted.mplstyle +3 -0
  278. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-notebook.mplstyle +21 -0
  279. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-paper.mplstyle +21 -0
  280. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-pastel.mplstyle +3 -0
  281. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-poster.mplstyle +21 -0
  282. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-talk.mplstyle +21 -0
  283. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-ticks.mplstyle +30 -0
  284. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-white.mplstyle +30 -0
  285. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-whitegrid.mplstyle +30 -0
  286. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8.mplstyle +57 -0
  287. matplotlib_rs/mpl-data/stylelib/tableau-colorblind10.mplstyle +3 -0
  288. matplotlib_rs/mpl_toolkits/__init__.py +3 -0
  289. matplotlib_rs/mpl_toolkits/axes_grid1/__init__.py +11 -0
  290. matplotlib_rs/mpl_toolkits/axes_grid1/anchored_artists.py +415 -0
  291. matplotlib_rs/mpl_toolkits/axes_grid1/axes_divider.py +619 -0
  292. matplotlib_rs/mpl_toolkits/axes_grid1/axes_grid.py +565 -0
  293. matplotlib_rs/mpl_toolkits/axes_grid1/axes_rgb.py +158 -0
  294. matplotlib_rs/mpl_toolkits/axes_grid1/axes_size.py +272 -0
  295. matplotlib_rs/mpl_toolkits/axes_grid1/inset_locator.py +525 -0
  296. matplotlib_rs/mpl_toolkits/axes_grid1/mpl_axes.py +129 -0
  297. matplotlib_rs/mpl_toolkits/axes_grid1/parasite_axes.py +261 -0
  298. matplotlib_rs/mpl_toolkits/axisartist/__init__.py +15 -0
  299. matplotlib_rs/mpl_toolkits/axisartist/angle_helper.py +396 -0
  300. matplotlib_rs/mpl_toolkits/axisartist/axes_divider.py +3 -0
  301. matplotlib_rs/mpl_toolkits/axisartist/axis_artist.py +1148 -0
  302. matplotlib_rs/mpl_toolkits/axisartist/axisline_style.py +193 -0
  303. matplotlib_rs/mpl_toolkits/axisartist/axislines.py +475 -0
  304. matplotlib_rs/mpl_toolkits/axisartist/floating_axes.py +265 -0
  305. matplotlib_rs/mpl_toolkits/axisartist/grid_finder.py +329 -0
  306. matplotlib_rs/mpl_toolkits/axisartist/grid_helper_curvelinear.py +353 -0
  307. matplotlib_rs/mpl_toolkits/axisartist/parasite_axes.py +8 -0
  308. matplotlib_rs/mpl_toolkits/mplot3d/__init__.py +4 -0
  309. matplotlib_rs/mpl_toolkits/mplot3d/art3d.py +1758 -0
  310. matplotlib_rs/mpl_toolkits/mplot3d/axes3d.py +4462 -0
  311. matplotlib_rs/mpl_toolkits/mplot3d/axis3d.py +807 -0
  312. matplotlib_rs/mpl_toolkits/mplot3d/proj3d.py +270 -0
  313. matplotlib_rs/offsetbox.py +1726 -0
  314. matplotlib_rs/patches.py +5049 -0
  315. matplotlib_rs/path.py +1147 -0
  316. matplotlib_rs/patheffects.py +512 -0
  317. matplotlib_rs/projections/__init__.py +126 -0
  318. matplotlib_rs/projections/geo.py +512 -0
  319. matplotlib_rs/projections/polar.py +1518 -0
  320. matplotlib_rs/pylab.py +68 -0
  321. matplotlib_rs/pyplot.py +4834 -0
  322. matplotlib_rs/quiver.py +1236 -0
  323. matplotlib_rs/rcsetup.py +3435 -0
  324. matplotlib_rs/sankey.py +815 -0
  325. matplotlib_rs/scale.py +1002 -0
  326. matplotlib_rs/spines.py +618 -0
  327. matplotlib_rs/stackplot.py +144 -0
  328. matplotlib_rs/streamplot.py +768 -0
  329. matplotlib_rs/style/__init__.py +269 -0
  330. matplotlib_rs/style/core.py +28 -0
  331. matplotlib_rs/table.py +860 -0
  332. matplotlib_rs/texmanager.py +375 -0
  333. matplotlib_rs/text.py +2412 -0
  334. matplotlib_rs/textpath.py +377 -0
  335. matplotlib_rs/ticker.py +3111 -0
  336. matplotlib_rs/transforms.py +3069 -0
  337. matplotlib_rs/tri/__init__.py +24 -0
  338. matplotlib_rs/tri/_triangulation.py +248 -0
  339. matplotlib_rs/tri/_tricontour.py +271 -0
  340. matplotlib_rs/tri/_trifinder.py +97 -0
  341. matplotlib_rs/tri/_triinterpolate.py +1575 -0
  342. matplotlib_rs/tri/_tripcolor.py +170 -0
  343. matplotlib_rs/tri/_triplot.py +87 -0
  344. matplotlib_rs/tri/_trirefine.py +308 -0
  345. matplotlib_rs/tri/_tritools.py +264 -0
  346. matplotlib_rs/typing.py +597 -0
  347. matplotlib_rs/units.py +196 -0
  348. matplotlib_rs/widgets.py +4455 -0
  349. matplotlib_rs-0.0.8.dist-info/METADATA +392 -0
  350. matplotlib_rs-0.0.8.dist-info/RECORD +352 -0
  351. matplotlib_rs-0.0.8.dist-info/WHEEL +4 -0
  352. matplotlib_rs-0.0.8.dist-info/sboms/matplotlib-rs.cyclonedx.json +4390 -0
@@ -0,0 +1,3815 @@
1
+ # Vendored from matplotlib 3.11 (see licenses/LICENSE_MATPLOTLIB), adapted for matplotlib_rs.
2
+ """
3
+ `matplotlib.figure` implements the following classes:
4
+
5
+ `Figure`
6
+ Top level `~matplotlib.artist.Artist`, which holds all plot elements.
7
+ Many methods are implemented in `FigureBase`.
8
+
9
+ `SubFigure`
10
+ A logical figure inside a figure, usually added to a figure (or parent `SubFigure`)
11
+ with `Figure.add_subfigure` or `Figure.subfigures` methods.
12
+
13
+ Figures are typically created using pyplot methods `~.pyplot.figure`,
14
+ `~.pyplot.subplots`, and `~.pyplot.subplot_mosaic`.
15
+
16
+ .. plot::
17
+ :include-source:
18
+
19
+ fig, ax = plt.subplots(figsize=(2, 2), facecolor='lightskyblue',
20
+ layout='constrained')
21
+ fig.suptitle('Figure')
22
+ ax.set_title('Axes', loc='left', fontstyle='oblique', fontsize='medium')
23
+
24
+ Some situations call for directly instantiating a `~.figure.Figure` class,
25
+ usually inside an application of some sort (see :ref:`user_interfaces` for a
26
+ list of examples) . More information about Figures can be found at
27
+ :ref:`figure-intro`.
28
+ """
29
+
30
+ from contextlib import ExitStack
31
+ import inspect
32
+ import itertools
33
+ import functools
34
+ import logging
35
+ from numbers import Integral
36
+ import threading
37
+
38
+ import numpy as np
39
+
40
+ import matplotlib_rs as mpl
41
+ from matplotlib_rs import _blocking_input, backend_bases, _docstring, projections
42
+ from matplotlib_rs.artist import (
43
+ Artist, allow_rasterization, _finalize_rasterization)
44
+ from matplotlib_rs.backend_bases import (
45
+ DrawEvent, FigureCanvasBase, NonGuiException, MouseButton, _get_renderer)
46
+ import matplotlib_rs._api as _api
47
+ import matplotlib_rs.cbook as cbook
48
+ import matplotlib_rs.colorbar as cbar
49
+ import matplotlib_rs.image as mimage
50
+
51
+ from matplotlib_rs.axes import Axes
52
+ from matplotlib_rs.gridspec import GridSpec, SubplotParams
53
+ from matplotlib_rs.layout_engine import (
54
+ ConstrainedLayoutEngine, TightLayoutEngine, LayoutEngine,
55
+ PlaceHolderLayoutEngine
56
+ )
57
+ import matplotlib_rs.legend as mlegend
58
+ from matplotlib_rs.patches import Rectangle
59
+ from matplotlib_rs.text import Text
60
+ from matplotlib_rs.transforms import (Affine2D, Bbox, BboxTransformTo,
61
+ TransformedBbox)
62
+
63
+ _log = logging.getLogger(__name__)
64
+
65
+
66
+ def _stale_figure_callback(self, val):
67
+ if (fig := self.get_figure(root=False)) is not None:
68
+ fig.stale = val
69
+
70
+
71
+ class _AxesStack:
72
+ """
73
+ Helper class to track Axes in a figure.
74
+
75
+ Axes are tracked both in the order in which they have been added
76
+ (``self._axes`` insertion/iteration order) and in the separate "gca" stack
77
+ (which is the index to which they map in the ``self._axes`` dict).
78
+ """
79
+
80
+ def __init__(self):
81
+ self._axes = {} # Mapping of Axes to "gca" order.
82
+ self._counter = itertools.count()
83
+
84
+ def as_list(self):
85
+ """List the Axes that have been added to the figure."""
86
+ return [*self._axes] # This relies on dict preserving order.
87
+
88
+ def remove(self, a):
89
+ """Remove the Axes from the stack."""
90
+ self._axes.pop(a)
91
+
92
+ def bubble(self, a):
93
+ """Move an Axes, which must already exist in the stack, to the top."""
94
+ if a not in self._axes:
95
+ raise ValueError("Axes has not been added yet")
96
+ self._axes[a] = next(self._counter)
97
+
98
+ def add(self, a):
99
+ """Add an Axes to the stack, ignoring it if already present."""
100
+ if a not in self._axes:
101
+ self._axes[a] = next(self._counter)
102
+
103
+ def current(self):
104
+ """Return the active Axes, or None if the stack is empty."""
105
+ return max(self._axes, key=self._axes.__getitem__, default=None)
106
+
107
+ def __getstate__(self):
108
+ return {
109
+ **vars(self),
110
+ "_counter": max(self._axes.values(), default=0)
111
+ }
112
+
113
+ def __setstate__(self, state):
114
+ next_counter = state.pop('_counter')
115
+ vars(self).update(state)
116
+ self._counter = itertools.count(next_counter)
117
+
118
+
119
+ class FigureBase(Artist):
120
+ """
121
+ Base class for `.Figure` and `.SubFigure` containing the methods that add
122
+ artists to the figure or subfigure, create Axes, etc.
123
+ """
124
+ def __init__(self, **kwargs):
125
+ super().__init__()
126
+ # remove the non-figure artist _axes property
127
+ # as it makes no sense for a figure to be _in_ an Axes
128
+ # this is used by the property methods in the artist base class
129
+ # which are over-ridden in this class
130
+ del self._axes
131
+
132
+ self._suptitle = None
133
+ self._supxlabel = None
134
+ self._supylabel = None
135
+
136
+ # groupers to keep track of x, y labels and title we want to align.
137
+ # see self.align_xlabels, self.align_ylabels,
138
+ # self.align_titles, and axis._get_tick_boxes_siblings
139
+ self._align_label_groups = {
140
+ "x": cbook.Grouper(),
141
+ "y": cbook.Grouper(),
142
+ "title": cbook.Grouper()
143
+ }
144
+
145
+ self._localaxes = [] # track all Axes
146
+ self.artists = []
147
+ self.lines = []
148
+ self.patches = []
149
+ self.texts = []
150
+ self.images = []
151
+ self.legends = []
152
+ self.subfigs = []
153
+ self.stale = True
154
+ self.suppressComposite = None
155
+ self.set(**kwargs)
156
+
157
+ def _get_draw_artists(self, renderer):
158
+ """Also runs apply_aspect"""
159
+ artists = self.get_children()
160
+
161
+ artists.remove(self.patch)
162
+ artists = sorted(
163
+ (artist for artist in artists if not artist.get_animated()),
164
+ key=lambda artist: artist.get_zorder())
165
+ for ax in self._localaxes:
166
+ locator = ax.get_axes_locator()
167
+ ax.apply_aspect(locator(ax, renderer) if locator else None)
168
+
169
+ # (lines and patches not created yet have no aspect)
170
+ for child in ax._get_existing_children():
171
+ if hasattr(child, 'apply_aspect'):
172
+ locator = child.get_axes_locator()
173
+ child.apply_aspect(
174
+ locator(child, renderer) if locator else None)
175
+ return artists
176
+
177
+ def autofmt_xdate(
178
+ self, bottom=0.2, rotation=30, ha='right', which='major'):
179
+ """
180
+ Date ticklabels often overlap, so it is useful to rotate them
181
+ and right align them. Also, a common use case is a number of
182
+ subplots with shared x-axis where the x-axis is date data. The
183
+ ticklabels are often long, and it helps to rotate them on the
184
+ bottom subplot and turn them off on other subplots, as well as
185
+ turn off xlabels.
186
+
187
+ Parameters
188
+ ----------
189
+ bottom : float, default: 0.2
190
+ The bottom of the subplots for `subplots_adjust`.
191
+ rotation : float, default: 30 degrees
192
+ The rotation angle of the xtick labels in degrees.
193
+ ha : {'left', 'center', 'right'}, default: 'right'
194
+ The horizontal alignment of the xticklabels.
195
+ which : {'major', 'minor', 'both'}, default: 'major'
196
+ Selects which ticklabels to rotate.
197
+ """
198
+ _api.check_in_list(['major', 'minor', 'both'], which=which)
199
+ axes = [ax for ax in self.axes if ax._label != '<colorbar>']
200
+ allsubplots = all(ax.get_subplotspec() for ax in axes)
201
+ if len(axes) == 1:
202
+ for label in self.axes[0].get_xticklabels(which=which):
203
+ label.set_ha(ha)
204
+ label.set_rotation(rotation)
205
+ else:
206
+ if allsubplots:
207
+ for ax in axes:
208
+ if ax.get_subplotspec().is_last_row():
209
+ for label in ax.get_xticklabels(which=which):
210
+ label.set_ha(ha)
211
+ label.set_rotation(rotation)
212
+ else:
213
+ for label in ax.get_xticklabels(which=which):
214
+ label.set_visible(False)
215
+ ax.set_xlabel('')
216
+
217
+ engine = self.get_layout_engine()
218
+ if allsubplots and (engine is None or engine.adjust_compatible):
219
+ self.subplots_adjust(bottom=bottom)
220
+ self.stale = True
221
+
222
+ def get_children(self):
223
+ """Get a list of artists contained in the figure."""
224
+ return [self.patch,
225
+ *self.artists,
226
+ *self._localaxes,
227
+ *self.lines,
228
+ *self.patches,
229
+ *self.texts,
230
+ *self.images,
231
+ *self.legends,
232
+ *self.subfigs]
233
+
234
+ def get_figure(self, root=None):
235
+ """
236
+ Return the `.Figure` or `.SubFigure` instance the (Sub)Figure belongs to.
237
+
238
+ Parameters
239
+ ----------
240
+ root : bool, default=True
241
+ If False, return the (Sub)Figure this artist is on. If True,
242
+ return the root Figure for a nested tree of SubFigures.
243
+
244
+ .. deprecated:: 3.10
245
+
246
+ From version 3.12 *root* will default to False.
247
+ """
248
+ if self._root_figure is self:
249
+ # Top level Figure
250
+ return self
251
+
252
+ if self._parent is self._root_figure:
253
+ # Return early to prevent the deprecation warning when *root* does not
254
+ # matter
255
+ return self._parent
256
+
257
+ if root is None:
258
+ # When deprecation expires, consider removing the docstring and just
259
+ # inheriting the one from Artist.
260
+ message = ('From Matplotlib 3.12 SubFigure.get_figure will by default '
261
+ 'return the direct parent figure, which may be a SubFigure. '
262
+ 'To suppress this warning, pass the root parameter. Pass '
263
+ '`True` to maintain the old behavior and `False` to opt-in to '
264
+ 'the future behavior.')
265
+ _api.warn_deprecated('3.10', message=message)
266
+ root = True
267
+
268
+ if root:
269
+ return self._root_figure
270
+
271
+ return self._parent
272
+
273
+ def set_figure(self, fig):
274
+ """
275
+ .. deprecated:: 3.10
276
+ Currently this method will raise an exception if *fig* is anything other
277
+ than the root `.Figure` this (Sub)Figure is on. In future it will always
278
+ raise an exception.
279
+ """
280
+ no_switch = ("The parent and root figures of a (Sub)Figure are set at "
281
+ "instantiation and cannot be changed.")
282
+ if fig is self._root_figure:
283
+ _api.warn_deprecated(
284
+ "3.10",
285
+ message=(f"{no_switch} From Matplotlib 3.12 this operation will raise "
286
+ "an exception."))
287
+ return
288
+
289
+ raise ValueError(no_switch)
290
+
291
+ figure = property(functools.partial(get_figure, root=True), set_figure,
292
+ doc=("The root `Figure`. To get the parent of a `SubFigure`, "
293
+ "use the `get_figure` method."))
294
+
295
+ def contains(self, mouseevent):
296
+ """
297
+ Test whether the mouse event occurred on the figure.
298
+
299
+ Returns
300
+ -------
301
+ bool, {}
302
+ """
303
+ if self._different_canvas(mouseevent):
304
+ return False, {}
305
+ inside = self.bbox.contains(mouseevent.x, mouseevent.y)
306
+ return inside, {}
307
+
308
+ def get_window_extent(self, renderer=None):
309
+ # docstring inherited
310
+ return self.bbox
311
+
312
+ def _suplabels(self, t, info, **kwargs):
313
+ """
314
+ Add a centered %(name)s to the figure.
315
+
316
+ Parameters
317
+ ----------
318
+ t : str
319
+ The %(name)s text.
320
+ x : float, default: %(x0)s
321
+ The x location of the text in figure coordinates.
322
+ y : float, default: %(y0)s
323
+ The y location of the text in figure coordinates.
324
+ horizontalalignment, ha : {'center', 'left', 'right'}, default: %(ha)s
325
+ The horizontal alignment of the text relative to (*x*, *y*).
326
+ verticalalignment, va : {'top', 'center', 'bottom', 'baseline'}, \
327
+ default: %(va)s
328
+ The vertical alignment of the text relative to (*x*, *y*).
329
+ fontsize, size : default: :rc:`figure.%(rc)ssize`
330
+ The font size of the text. See `.Text.set_size` for possible
331
+ values.
332
+ fontweight, weight : default: :rc:`figure.%(rc)sweight`
333
+ The font weight of the text. See `.Text.set_weight` for possible
334
+ values.
335
+
336
+ Returns
337
+ -------
338
+ text
339
+ The `.Text` instance of the %(name)s.
340
+
341
+ Other Parameters
342
+ ----------------
343
+ fontproperties : None or dict, optional
344
+ A dict of font properties. If *fontproperties* is given the
345
+ default values for font size and weight are taken from the
346
+ `.FontProperties` defaults. :rc:`figure.%(rc)ssize` and
347
+ :rc:`figure.%(rc)sweight` are ignored in this case.
348
+
349
+ **kwargs
350
+ Additional kwargs are `matplotlib.text.Text` properties.
351
+ """
352
+
353
+ x = kwargs.pop('x', None)
354
+ y = kwargs.pop('y', None)
355
+ if info['name'] in ['_supxlabel', '_suptitle']:
356
+ autopos = y is None
357
+ elif info['name'] == '_supylabel':
358
+ autopos = x is None
359
+ if x is None:
360
+ x = info['x0']
361
+ if y is None:
362
+ y = info['y0']
363
+
364
+ kwargs = cbook.normalize_kwargs(kwargs, Text)
365
+ kwargs.setdefault('horizontalalignment', info['ha'])
366
+ kwargs.setdefault('verticalalignment', info['va'])
367
+ kwargs.setdefault('rotation', info['rotation'])
368
+
369
+ if 'fontproperties' not in kwargs:
370
+ kwargs.setdefault('fontsize', mpl.rcParams[info['size']])
371
+ kwargs.setdefault('fontweight', mpl.rcParams[info['weight']])
372
+
373
+ suplab = getattr(self, info['name'])
374
+ if suplab is not None:
375
+ suplab.set_text(t)
376
+ suplab.set_position((x, y))
377
+ suplab.set(**kwargs)
378
+ else:
379
+ suplab = self.text(x, y, t, **kwargs)
380
+ setattr(self, info['name'], suplab)
381
+ suplab._remove_method = functools.partial(self._remove_suplabel,
382
+ name=info['name'])
383
+
384
+ suplab._autopos = autopos
385
+ self.stale = True
386
+ return suplab
387
+
388
+ def _remove_suplabel(self, label, name):
389
+ self.texts.remove(label)
390
+ setattr(self, name, None)
391
+
392
+ @_docstring.Substitution(x0=0.5, y0=0.98, name='super title', ha='center',
393
+ va='top', rc='title')
394
+ @_docstring.copy(_suplabels)
395
+ def suptitle(self, t, **kwargs):
396
+ # docstring from _suplabels...
397
+ info = {'name': '_suptitle', 'x0': 0.5, 'y0': 0.98,
398
+ 'ha': 'center', 'va': 'top', 'rotation': 0,
399
+ 'size': 'figure.titlesize', 'weight': 'figure.titleweight'}
400
+ return self._suplabels(t, info, **kwargs)
401
+
402
+ def get_suptitle(self):
403
+ """Return the suptitle as string or an empty string if not set."""
404
+ text_obj = self._suptitle
405
+ return "" if text_obj is None else text_obj.get_text()
406
+
407
+ @_docstring.Substitution(x0=0.5, y0=0.01, name='super xlabel', ha='center',
408
+ va='bottom', rc='label')
409
+ @_docstring.copy(_suplabels)
410
+ def supxlabel(self, t, **kwargs):
411
+ # docstring from _suplabels...
412
+ info = {'name': '_supxlabel', 'x0': 0.5, 'y0': 0.01,
413
+ 'ha': 'center', 'va': 'bottom', 'rotation': 0,
414
+ 'size': 'figure.labelsize', 'weight': 'figure.labelweight'}
415
+ return self._suplabels(t, info, **kwargs)
416
+
417
+ def get_supxlabel(self):
418
+ """Return the supxlabel as string or an empty string if not set."""
419
+ text_obj = self._supxlabel
420
+ return "" if text_obj is None else text_obj.get_text()
421
+
422
+ @_docstring.Substitution(x0=0.02, y0=0.5, name='super ylabel', ha='left',
423
+ va='center', rc='label')
424
+ @_docstring.copy(_suplabels)
425
+ def supylabel(self, t, **kwargs):
426
+ # docstring from _suplabels...
427
+ info = {'name': '_supylabel', 'x0': 0.02, 'y0': 0.5,
428
+ 'ha': 'left', 'va': 'center', 'rotation': 'vertical',
429
+ 'rotation_mode': 'anchor', 'size': 'figure.labelsize',
430
+ 'weight': 'figure.labelweight'}
431
+ return self._suplabels(t, info, **kwargs)
432
+
433
+ def get_supylabel(self):
434
+ """Return the supylabel as string or an empty string if not set."""
435
+ text_obj = self._supylabel
436
+ return "" if text_obj is None else text_obj.get_text()
437
+
438
+ def get_edgecolor(self):
439
+ """Get the edge color of the Figure rectangle."""
440
+ return self.patch.get_edgecolor()
441
+
442
+ def get_facecolor(self):
443
+ """Get the face color of the Figure rectangle."""
444
+ return self.patch.get_facecolor()
445
+
446
+ def get_frameon(self):
447
+ """
448
+ Return the figure's background patch visibility, i.e.
449
+ whether the figure background will be drawn. Equivalent to
450
+ ``Figure.patch.get_visible()``.
451
+ """
452
+ return self.patch.get_visible()
453
+
454
+ def set_linewidth(self, linewidth):
455
+ """
456
+ Set the line width of the Figure rectangle.
457
+
458
+ Parameters
459
+ ----------
460
+ linewidth : number
461
+ """
462
+ self.patch.set_linewidth(linewidth)
463
+
464
+ def get_linewidth(self):
465
+ """
466
+ Get the line width of the Figure rectangle.
467
+ """
468
+ return self.patch.get_linewidth()
469
+
470
+ def set_edgecolor(self, color):
471
+ """
472
+ Set the edge color of the Figure rectangle.
473
+
474
+ Parameters
475
+ ----------
476
+ color : :mpltype:`color`
477
+ """
478
+ self.patch.set_edgecolor(color)
479
+
480
+ def set_facecolor(self, color):
481
+ """
482
+ Set the face color of the Figure rectangle.
483
+
484
+ Parameters
485
+ ----------
486
+ color : :mpltype:`color`
487
+ """
488
+ self.patch.set_facecolor(color)
489
+
490
+ def set_frameon(self, b):
491
+ """
492
+ Set the figure's background patch visibility, i.e.
493
+ whether the figure background will be drawn. Equivalent to
494
+ ``Figure.patch.set_visible()``.
495
+
496
+ Parameters
497
+ ----------
498
+ b : bool
499
+ """
500
+ self.patch.set_visible(b)
501
+ self.stale = True
502
+
503
+ frameon = property(get_frameon, set_frameon)
504
+
505
+ def add_artist(self, artist, clip=False):
506
+ """
507
+ Add an `.Artist` to the figure.
508
+
509
+ Usually artists are added to `~.axes.Axes` objects using
510
+ `.Axes.add_artist`; this method can be used in the rare cases where
511
+ one needs to add artists directly to the figure instead.
512
+
513
+ Parameters
514
+ ----------
515
+ artist : `~matplotlib.artist.Artist`
516
+ The artist to add to the figure. If the added artist has no
517
+ transform previously set, its transform will be set to
518
+ ``figure.transSubfigure``.
519
+ clip : bool, default: False
520
+ Whether the added artist should be clipped by the figure patch.
521
+
522
+ Returns
523
+ -------
524
+ `~matplotlib.artist.Artist`
525
+ The added artist.
526
+ """
527
+ artist.set_figure(self)
528
+ self.artists.append(artist)
529
+ artist._remove_method = self.artists.remove
530
+
531
+ if not artist.is_transform_set():
532
+ artist.set_transform(self.transSubfigure)
533
+
534
+ if clip and artist.get_clip_path() is None:
535
+ artist.set_clip_path(self.patch)
536
+
537
+ self.stale = True
538
+ return artist
539
+
540
+ @_docstring.interpd
541
+ def add_axes(self, *args, **kwargs):
542
+ """
543
+ Add an `~.axes.Axes` to the figure.
544
+
545
+ Call signatures::
546
+
547
+ add_axes(rect, projection=None, polar=False, **kwargs)
548
+ add_axes(ax)
549
+
550
+ Parameters
551
+ ----------
552
+ rect : tuple (left, bottom, width, height)
553
+ The dimensions (left, bottom, width, height) of the new
554
+ `~.axes.Axes`. All quantities are in fractions of figure width and
555
+ height.
556
+
557
+ projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
558
+ 'polar', 'rectilinear', str}, optional
559
+ The projection type of the `~.axes.Axes`. *str* is the name of
560
+ a custom projection, see `~matplotlib.projections`. The default
561
+ None results in a 'rectilinear' projection.
562
+
563
+ polar : bool, default: False
564
+ If True, equivalent to projection='polar'.
565
+
566
+ axes_class : subclass type of `~.axes.Axes`, optional
567
+ The `.axes.Axes` subclass that is instantiated. This parameter
568
+ is incompatible with *projection* and *polar*. See
569
+ :ref:`axisartist_users-guide-index` for examples.
570
+
571
+ sharex, sharey : `~matplotlib.axes.Axes`, optional
572
+ Share the x or y `~matplotlib.axis` with sharex and/or sharey.
573
+ The axis will have the same limits, ticks, and scale as the axis
574
+ of the shared Axes.
575
+
576
+ label : str
577
+ A label for the returned Axes.
578
+
579
+ Returns
580
+ -------
581
+ `~.axes.Axes`, or a subclass of `~.axes.Axes`
582
+ The returned Axes class depends on the projection used. It is
583
+ `~.axes.Axes` if rectilinear projection is used and
584
+ `.projections.polar.PolarAxes` if polar projection is used.
585
+
586
+ Other Parameters
587
+ ----------------
588
+ **kwargs
589
+ This method also takes the keyword arguments for
590
+ the returned Axes class. The keyword arguments for the
591
+ rectilinear Axes class `~.axes.Axes` can be found in
592
+ the following table but there might also be other keyword
593
+ arguments if another projection is used, see the actual Axes
594
+ class.
595
+
596
+ %(Axes:kwdoc)s
597
+
598
+ Notes
599
+ -----
600
+ In rare circumstances, `.add_axes` may be called with a single
601
+ argument, an Axes instance already created in the present figure but
602
+ not in the figure's list of Axes.
603
+
604
+ See Also
605
+ --------
606
+ .Figure.add_subplot
607
+ .pyplot.subplot
608
+ .pyplot.axes
609
+ .Figure.subplots
610
+ .pyplot.subplots
611
+
612
+ Examples
613
+ --------
614
+ Some simple examples::
615
+
616
+ rect = l, b, w, h
617
+ fig = plt.figure()
618
+ fig.add_axes(rect)
619
+ fig.add_axes(rect, frameon=False, facecolor='g')
620
+ fig.add_axes(rect, polar=True)
621
+ ax = fig.add_axes(rect, projection='polar')
622
+ fig.delaxes(ax)
623
+ fig.add_axes(ax)
624
+ """
625
+
626
+ if not len(args) and 'rect' not in kwargs:
627
+ raise TypeError("add_axes() missing 1 required positional argument: 'rect'")
628
+ elif 'rect' in kwargs:
629
+ if len(args):
630
+ raise TypeError("add_axes() got multiple values for argument 'rect'")
631
+ args = (kwargs.pop('rect'), )
632
+ if len(args) != 1:
633
+ raise _api.nargs_error("add_axes", 1, len(args))
634
+
635
+ if isinstance(args[0], Axes):
636
+ a, = args
637
+ key = a._projection_init
638
+ if a.get_figure(root=False) is not self:
639
+ raise ValueError(
640
+ "The Axes must have been created in the present figure")
641
+ else:
642
+ rect, = args
643
+ if not np.isfinite(rect).all():
644
+ raise ValueError(f'all entries in rect must be finite not {rect}')
645
+ projection_class, pkw = self._process_projection_requirements(**kwargs)
646
+
647
+ # create the new Axes using the Axes class given
648
+ a = projection_class(self, rect, **pkw)
649
+ key = (projection_class, pkw)
650
+
651
+ return self._add_axes_internal(a, key)
652
+
653
+ @_docstring.interpd
654
+ def add_subplot(self, *args, **kwargs):
655
+ """
656
+ Add an `~.axes.Axes` to the figure as part of a subplot arrangement.
657
+
658
+ Call signatures::
659
+
660
+ add_subplot(nrows, ncols, index, **kwargs)
661
+ add_subplot(pos, **kwargs)
662
+ add_subplot(ax)
663
+ add_subplot()
664
+
665
+ Parameters
666
+ ----------
667
+ *args : int, (int, int, *index*), or `.SubplotSpec`, default: (1, 1, 1)
668
+ The position of the subplot described by one of
669
+
670
+ - Three integers (*nrows*, *ncols*, *index*). The subplot will
671
+ take the *index* position on a grid with *nrows* rows and
672
+ *ncols* columns. *index* starts at 1 in the upper left corner
673
+ and increases to the right. *index* can also be a two-tuple
674
+ specifying the (*first*, *last*) indices (1-based, and including
675
+ *last*) of the subplot, e.g., ``fig.add_subplot(3, 1, (1, 2))``
676
+ makes a subplot that spans the upper 2/3 of the figure.
677
+ - A 3-digit integer. The digits are interpreted as if given
678
+ separately as three single-digit integers, i.e.
679
+ ``fig.add_subplot(235)`` is the same as
680
+ ``fig.add_subplot(2, 3, 5)``. Note that this can only be used
681
+ if there are no more than 9 subplots.
682
+ - A `.SubplotSpec`.
683
+
684
+ In rare circumstances, `.add_subplot` may be called with a single
685
+ argument, a subplot Axes instance already created in the
686
+ present figure but not in the figure's list of Axes.
687
+
688
+ projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
689
+ 'polar', 'rectilinear', str}, optional
690
+ The projection type of the subplot (`~.axes.Axes`). *str* is the
691
+ name of a custom projection, see `~matplotlib.projections`. The
692
+ default None results in a 'rectilinear' projection.
693
+
694
+ polar : bool, default: False
695
+ If True, equivalent to projection='polar'.
696
+
697
+ axes_class : subclass type of `~.axes.Axes`, optional
698
+ The `.axes.Axes` subclass that is instantiated. This parameter
699
+ is incompatible with *projection* and *polar*. See
700
+ :ref:`axisartist_users-guide-index` for examples.
701
+
702
+ sharex, sharey : `~matplotlib.axes.Axes`, optional
703
+ Share the x or y `~matplotlib.axis` with sharex and/or sharey.
704
+ The axis will have the same limits, ticks, and scale as the axis
705
+ of the shared Axes.
706
+
707
+ label : str
708
+ A label for the returned Axes.
709
+
710
+ Returns
711
+ -------
712
+ `~.axes.Axes`
713
+
714
+ The Axes of the subplot. The returned Axes can actually be an
715
+ instance of a subclass, such as `.projections.polar.PolarAxes` for
716
+ polar projections.
717
+
718
+ Other Parameters
719
+ ----------------
720
+ **kwargs
721
+ This method also takes the keyword arguments for the returned Axes
722
+ base class; except for the *figure* argument. The keyword arguments
723
+ for the rectilinear base class `~.axes.Axes` can be found in
724
+ the following table but there might also be other keyword
725
+ arguments if another projection is used.
726
+
727
+ %(Axes:kwdoc)s
728
+
729
+ See Also
730
+ --------
731
+ .Figure.add_axes
732
+ .pyplot.subplot
733
+ .pyplot.axes
734
+ .Figure.subplots
735
+ .pyplot.subplots
736
+
737
+ Examples
738
+ --------
739
+ ::
740
+
741
+ fig = plt.figure()
742
+
743
+ fig.add_subplot(231)
744
+ ax1 = fig.add_subplot(2, 3, 1) # equivalent but more general
745
+
746
+ fig.add_subplot(232, frameon=False) # subplot with no frame
747
+ fig.add_subplot(233, projection='polar') # polar subplot
748
+ fig.add_subplot(234, sharex=ax1) # subplot sharing x-axis with ax1
749
+ fig.add_subplot(235, facecolor="red") # red subplot
750
+
751
+ ax1.remove() # delete ax1 from the figure
752
+ fig.add_subplot(ax1) # add ax1 back to the figure
753
+ """
754
+ if 'figure' in kwargs:
755
+ # Axes itself allows for a 'figure' kwarg, but since we want to
756
+ # bind the created Axes to self, it is not allowed here.
757
+ raise _api.kwarg_error("add_subplot", "figure")
758
+
759
+ if (len(args) == 1
760
+ and isinstance(args[0], mpl.axes._base._AxesBase)
761
+ and args[0].get_subplotspec()):
762
+ ax = args[0]
763
+ key = ax._projection_init
764
+ if ax.get_figure(root=False) is not self:
765
+ raise ValueError("The Axes must have been created in "
766
+ "the present figure")
767
+ else:
768
+ if not args:
769
+ args = (1, 1, 1)
770
+ # Normalize correct ijk values to (i, j, k) here so that
771
+ # add_subplot(211) == add_subplot(2, 1, 1). Invalid values will
772
+ # trigger errors later (via SubplotSpec._from_subplot_args).
773
+ if (len(args) == 1 and isinstance(args[0], Integral)
774
+ and 100 <= args[0] <= 999):
775
+ args = tuple(map(int, str(args[0])))
776
+ projection_class, pkw = self._process_projection_requirements(**kwargs)
777
+ ax = projection_class(self, *args, **pkw)
778
+ key = (projection_class, pkw)
779
+ return self._add_axes_internal(ax, key)
780
+
781
+ def _add_axes_internal(self, ax, key):
782
+ """Private helper for `add_axes` and `add_subplot`."""
783
+ self._axstack.add(ax)
784
+ if ax not in self._localaxes:
785
+ self._localaxes.append(ax)
786
+ self.sca(ax)
787
+ ax._remove_method = self.delaxes
788
+ # this is to support plt.subplot's re-selection logic
789
+ ax._projection_init = key
790
+ self.stale = True
791
+ ax.stale_callback = _stale_figure_callback
792
+ return ax
793
+
794
+ def subplots(self, nrows=1, ncols=1, *, sharex=False, sharey=False,
795
+ squeeze=True, width_ratios=None, height_ratios=None,
796
+ subplot_kw=None, gridspec_kw=None):
797
+ """
798
+ Add a set of subplots to this figure.
799
+
800
+ This utility wrapper makes it convenient to create common layouts of
801
+ subplots in a single call.
802
+
803
+ Parameters
804
+ ----------
805
+ nrows, ncols : int, default: 1
806
+ Number of rows/columns of the subplot grid.
807
+
808
+ sharex, sharey : bool or {'none', 'all', 'row', 'col'}, default: False
809
+ Controls sharing of x-axis (*sharex*) or y-axis (*sharey*):
810
+
811
+ - True or 'all': x- or y-axis will be shared among all subplots.
812
+ - False or 'none': each subplot x- or y-axis will be independent.
813
+ - 'row': each subplot row will share an x- or y-axis.
814
+ - 'col': each subplot column will share an x- or y-axis.
815
+
816
+ When subplots have a shared x-axis along a column, only the x tick
817
+ labels of the bottom subplot are created. Similarly, when subplots
818
+ have a shared y-axis along a row, only the y tick labels of the
819
+ first column subplot are created. To later turn other subplots'
820
+ ticklabels on, use `~matplotlib.axes.Axes.tick_params`.
821
+
822
+ When subplots have a shared axis that has units, calling
823
+ `.Axis.set_units` will update each axis with the new units.
824
+
825
+ Note that it is not possible to unshare axes.
826
+
827
+ squeeze : bool, default: True
828
+ - If True, extra dimensions are squeezed out from the returned
829
+ array of Axes:
830
+
831
+ - if only one subplot is constructed (nrows=ncols=1), the
832
+ resulting single Axes object is returned as a scalar.
833
+ - for Nx1 or 1xM subplots, the returned object is a 1D numpy
834
+ object array of Axes objects.
835
+ - for NxM, subplots with N>1 and M>1 are returned as a 2D array.
836
+
837
+ - If False, no squeezing at all is done: the returned Axes object
838
+ is always a 2D array containing Axes instances, even if it ends
839
+ up being 1x1.
840
+
841
+ width_ratios : array-like of length *ncols*, optional
842
+ Defines the relative widths of the columns. Each column gets a
843
+ relative width of ``width_ratios[i] / sum(width_ratios)``.
844
+ If not given, all columns will have the same width. Equivalent
845
+ to ``gridspec_kw={'width_ratios': [...]}``.
846
+
847
+ height_ratios : array-like of length *nrows*, optional
848
+ Defines the relative heights of the rows. Each row gets a
849
+ relative height of ``height_ratios[i] / sum(height_ratios)``.
850
+ If not given, all rows will have the same height. Equivalent
851
+ to ``gridspec_kw={'height_ratios': [...]}``.
852
+
853
+ subplot_kw : dict, optional
854
+ Dict with keywords passed to the `.Figure.add_subplot` call used to
855
+ create each subplot.
856
+
857
+ gridspec_kw : dict, optional
858
+ Dict with keywords passed to the
859
+ `~matplotlib.gridspec.GridSpec` constructor used to create
860
+ the grid the subplots are placed on.
861
+
862
+ Returns
863
+ -------
864
+ `~.axes.Axes` or array of Axes
865
+ Either a single `~matplotlib.axes.Axes` object or an array of Axes
866
+ objects if more than one subplot was created. The dimensions of the
867
+ resulting array can be controlled with the *squeeze* keyword, see
868
+ above.
869
+
870
+ See Also
871
+ --------
872
+ .pyplot.subplots
873
+ .Figure.add_subplot
874
+ .pyplot.subplot
875
+
876
+ Examples
877
+ --------
878
+ ::
879
+
880
+ # First create some toy data:
881
+ x = np.linspace(0, 2*np.pi, 400)
882
+ y = np.sin(x**2)
883
+
884
+ # Create a figure
885
+ fig = plt.figure()
886
+
887
+ # Create a subplot
888
+ ax = fig.subplots()
889
+ ax.plot(x, y)
890
+ ax.set_title('Simple plot')
891
+
892
+ # Create two subplots and unpack the output array immediately
893
+ ax1, ax2 = fig.subplots(1, 2, sharey=True)
894
+ ax1.plot(x, y)
895
+ ax1.set_title('Sharing Y axis')
896
+ ax2.scatter(x, y)
897
+
898
+ # Create four polar Axes and access them through the returned array
899
+ axes = fig.subplots(2, 2, subplot_kw=dict(projection='polar'))
900
+ axes[0, 0].plot(x, y)
901
+ axes[1, 1].scatter(x, y)
902
+
903
+ # Share an X-axis with each column of subplots
904
+ fig.subplots(2, 2, sharex='col')
905
+
906
+ # Share a Y-axis with each row of subplots
907
+ fig.subplots(2, 2, sharey='row')
908
+
909
+ # Share both X- and Y-axes with all subplots
910
+ fig.subplots(2, 2, sharex='all', sharey='all')
911
+
912
+ # Note that this is the same as
913
+ fig.subplots(2, 2, sharex=True, sharey=True)
914
+ """
915
+ gridspec_kw = dict(gridspec_kw or {})
916
+ if height_ratios is not None:
917
+ if 'height_ratios' in gridspec_kw:
918
+ raise ValueError("'height_ratios' must not be defined both as "
919
+ "parameter and as key in 'gridspec_kw'")
920
+ gridspec_kw['height_ratios'] = height_ratios
921
+ if width_ratios is not None:
922
+ if 'width_ratios' in gridspec_kw:
923
+ raise ValueError("'width_ratios' must not be defined both as "
924
+ "parameter and as key in 'gridspec_kw'")
925
+ gridspec_kw['width_ratios'] = width_ratios
926
+
927
+ gs = self.add_gridspec(nrows, ncols, figure=self, **gridspec_kw)
928
+ axs = gs.subplots(sharex=sharex, sharey=sharey, squeeze=squeeze,
929
+ subplot_kw=subplot_kw)
930
+ return axs
931
+
932
+ def delaxes(self, ax):
933
+ """
934
+ Remove the `~.axes.Axes` *ax* from the figure; update the current Axes.
935
+ """
936
+ self._remove_axes(ax, owners=[self._axstack, self._localaxes])
937
+
938
+ def _remove_axes(self, ax, owners):
939
+ """
940
+ Common helper for removal of standard Axes (via delaxes) and of child Axes.
941
+
942
+ Parameters
943
+ ----------
944
+ ax : `~.AxesBase`
945
+ The Axes to remove.
946
+ owners
947
+ List of objects (list or _AxesStack) "owning" the Axes, from which the Axes
948
+ will be remove()d.
949
+ """
950
+ for owner in owners:
951
+ owner.remove(ax)
952
+
953
+ self._axobservers.process("_axes_change_event", self)
954
+ self.stale = True
955
+ self._root_figure.canvas.release_mouse(ax)
956
+
957
+ for name in ax._axis_names: # Break link between any shared Axes
958
+ grouper = ax._shared_axes[name]
959
+ siblings = grouper.get_siblings(ax, include_self=False)
960
+ if not siblings: # Axes was not shared along this axis; we're done.
961
+ continue
962
+ grouper.remove(ax)
963
+ # Formatters and locators may previously have been associated with the now
964
+ # removed axis. Update them to point to an axis still there (we can pick
965
+ # any of them, and use the first sibling).
966
+ remaining_axis = siblings[0]._axis_map[name]
967
+ remaining_axis.get_major_formatter().set_axis(remaining_axis)
968
+ remaining_axis.get_major_locator().set_axis(remaining_axis)
969
+ remaining_axis.get_minor_formatter().set_axis(remaining_axis)
970
+ remaining_axis.get_minor_locator().set_axis(remaining_axis)
971
+
972
+ ax._twinned_axes.remove(ax) # Break link between any twinned Axes.
973
+
974
+ def clear(self, keep_observers=False):
975
+ """
976
+ Clear the figure.
977
+
978
+ Parameters
979
+ ----------
980
+ keep_observers : bool, default: False
981
+ Set *keep_observers* to True if, for example,
982
+ a gui widget is tracking the Axes in the figure.
983
+ """
984
+ self.suppressComposite = None
985
+
986
+ # first clear the Axes in any subfigures
987
+ for subfig in self.subfigs:
988
+ subfig.clear(keep_observers=keep_observers)
989
+ self.subfigs = []
990
+
991
+ for ax in tuple(self.axes): # Iterate over the copy.
992
+ ax.clear()
993
+ self.delaxes(ax) # Remove ax from self._axstack.
994
+
995
+ self.artists = []
996
+ self.lines = []
997
+ self.patches = []
998
+ self.texts = []
999
+ self.images = []
1000
+ self.legends = []
1001
+ self.subplotpars.reset()
1002
+ if not keep_observers:
1003
+ self._axobservers = cbook.CallbackRegistry()
1004
+ self._suptitle = None
1005
+ self._supxlabel = None
1006
+ self._supylabel = None
1007
+
1008
+ self.stale = True
1009
+
1010
+ # synonym for `clear`.
1011
+ def clf(self, keep_observers=False):
1012
+ """
1013
+ [*Discouraged*] Alias for the `clear()` method.
1014
+
1015
+ .. admonition:: Discouraged
1016
+
1017
+ The use of ``clf()`` is discouraged. Use ``clear()`` instead.
1018
+
1019
+ Parameters
1020
+ ----------
1021
+ keep_observers : bool, default: False
1022
+ Set *keep_observers* to True if, for example,
1023
+ a gui widget is tracking the Axes in the figure.
1024
+ """
1025
+ return self.clear(keep_observers=keep_observers)
1026
+
1027
+ # Note: the docstring below is modified with replace for the pyplot
1028
+ # version of this function because the method name differs (plt.figlegend)
1029
+ # the replacements are:
1030
+ # " legend(" -> " figlegend(" for the signatures
1031
+ # "fig.legend(" -> "plt.figlegend" for the code examples
1032
+ # "ax.plot" -> "plt.plot" for consistency in using pyplot when able
1033
+ @_docstring.interpd
1034
+ def legend(self, *args, **kwargs):
1035
+ """
1036
+ Place a legend on the figure.
1037
+
1038
+ Call signatures::
1039
+
1040
+ legend()
1041
+ legend(handles, labels)
1042
+ legend(handles=handles)
1043
+ legend(labels)
1044
+
1045
+ The call signatures correspond to the following different ways to use
1046
+ this method:
1047
+
1048
+ **1. Automatic detection of elements to be shown in the legend**
1049
+
1050
+ The elements to be added to the legend are automatically determined,
1051
+ when you do not pass in any extra arguments.
1052
+
1053
+ In this case, the labels are taken from the artist. You can specify
1054
+ them either at artist creation or by calling the
1055
+ :meth:`~.Artist.set_label` method on the artist::
1056
+
1057
+ ax.plot([1, 2, 3], label='Inline label')
1058
+ fig.legend()
1059
+
1060
+ or::
1061
+
1062
+ line, = ax.plot([1, 2, 3])
1063
+ line.set_label('Label via method')
1064
+ fig.legend()
1065
+
1066
+ Specific lines can be excluded from the automatic legend element
1067
+ selection by defining a label starting with an underscore.
1068
+ This is default for all artists, so calling `.Figure.legend` without
1069
+ any arguments and without setting the labels manually will result in
1070
+ no legend being drawn.
1071
+
1072
+
1073
+ **2. Explicitly listing the artists and labels in the legend**
1074
+
1075
+ For full control of which artists have a legend entry, it is possible
1076
+ to pass an iterable of legend artists followed by an iterable of
1077
+ legend labels respectively::
1078
+
1079
+ fig.legend([line1, line2, line3], ['label1', 'label2', 'label3'])
1080
+
1081
+
1082
+ **3. Explicitly listing the artists in the legend**
1083
+
1084
+ This is similar to 2, but the labels are taken from the artists'
1085
+ label properties. Example::
1086
+
1087
+ line1, = ax1.plot([1, 2, 3], label='label1')
1088
+ line2, = ax2.plot([1, 2, 3], label='label2')
1089
+ fig.legend(handles=[line1, line2])
1090
+
1091
+
1092
+ **4. Labeling existing plot elements**
1093
+
1094
+ .. admonition:: Discouraged
1095
+
1096
+ This call signature is discouraged, because the relation between
1097
+ plot elements and labels is only implicit by their order and can
1098
+ easily be mixed up.
1099
+
1100
+ To make a legend for all artists on all Axes, call this function with
1101
+ an iterable of strings, one for each legend item. For example::
1102
+
1103
+ fig, (ax1, ax2) = plt.subplots(1, 2)
1104
+ ax1.plot([1, 3, 5], color='blue')
1105
+ ax2.plot([2, 4, 6], color='red')
1106
+ fig.legend(['the blues', 'the reds'])
1107
+
1108
+
1109
+ Parameters
1110
+ ----------
1111
+ handles : list of `.Artist`, optional
1112
+ A list of Artists (lines, patches) to be added to the legend.
1113
+ Use this together with *labels*, if you need full control on what
1114
+ is shown in the legend and the automatic mechanism described above
1115
+ is not sufficient.
1116
+
1117
+ The length of handles and labels should be the same in this
1118
+ case. If they are not, they are truncated to the smaller length.
1119
+
1120
+ labels : list of str, optional
1121
+ A list of labels to show next to the artists.
1122
+ Use this together with *handles*, if you need full control on what
1123
+ is shown in the legend and the automatic mechanism described above
1124
+ is not sufficient.
1125
+
1126
+ Returns
1127
+ -------
1128
+ `~matplotlib.legend.Legend`
1129
+
1130
+ Other Parameters
1131
+ ----------------
1132
+ %(_legend_kw_figure)s
1133
+
1134
+ See Also
1135
+ --------
1136
+ .Axes.legend
1137
+
1138
+ Notes
1139
+ -----
1140
+ Some artists are not supported by this function. See
1141
+ :ref:`legend_guide` for details.
1142
+ """
1143
+
1144
+ handles, labels, kwargs = mlegend._parse_legend_args(self.axes, *args, **kwargs)
1145
+ # explicitly set the bbox transform if the user hasn't.
1146
+ kwargs.setdefault("bbox_transform", self.transSubfigure)
1147
+ l = mlegend.Legend(self, handles, labels, **kwargs)
1148
+ self.legends.append(l)
1149
+ l._remove_method = self.legends.remove
1150
+ self.stale = True
1151
+ return l
1152
+
1153
+ @_docstring.interpd
1154
+ def text(self, x, y, s, fontdict=None, **kwargs):
1155
+ """
1156
+ Add text to figure.
1157
+
1158
+ Parameters
1159
+ ----------
1160
+ x, y : float
1161
+ The position to place the text. By default, this is in figure
1162
+ coordinates, floats in [0, 1]. The coordinate system can be changed
1163
+ using the *transform* keyword.
1164
+
1165
+ s : str
1166
+ The text string.
1167
+
1168
+ fontdict : dict, optional
1169
+ A dictionary to override the default text properties. If not given,
1170
+ the defaults are determined by :rc:`font.*`. Properties passed as
1171
+ *kwargs* override the corresponding ones given in *fontdict*.
1172
+
1173
+ Returns
1174
+ -------
1175
+ `~.text.Text`
1176
+
1177
+ Other Parameters
1178
+ ----------------
1179
+ **kwargs : `~matplotlib.text.Text` properties
1180
+ Other miscellaneous text parameters.
1181
+
1182
+ %(Text:kwdoc)s
1183
+
1184
+ See Also
1185
+ --------
1186
+ .Axes.text
1187
+ .pyplot.text
1188
+ """
1189
+ effective_kwargs = {
1190
+ 'transform': self.transSubfigure,
1191
+ **(fontdict if fontdict is not None else {}),
1192
+ **kwargs,
1193
+ }
1194
+ text = Text(x=x, y=y, text=s, **effective_kwargs)
1195
+ text.set_figure(self)
1196
+ text.stale_callback = _stale_figure_callback
1197
+
1198
+ self.texts.append(text)
1199
+ text._remove_method = self.texts.remove
1200
+ self.stale = True
1201
+ return text
1202
+
1203
+ @_docstring.interpd
1204
+ def colorbar(
1205
+ self, mappable, cax=None, ax=None, use_gridspec=True, **kwargs):
1206
+ """
1207
+ Add a colorbar to a plot.
1208
+
1209
+ Parameters
1210
+ ----------
1211
+ mappable
1212
+ The `matplotlib.colorizer.ColorizingArtist` (i.e., `.AxesImage`,
1213
+ `.ContourSet`, etc.) described by this colorbar. This argument is
1214
+ mandatory for the `.Figure.colorbar` method but optional for the
1215
+ `.pyplot.colorbar` function, which sets the default to the current
1216
+ image.
1217
+
1218
+ Note that one can create a `.colorizer.ColorizingArtist` "on-the-fly"
1219
+ to generate colorbars not attached to a previously drawn artist, e.g.
1220
+ ::
1221
+
1222
+ cr = colorizer.Colorizer(norm=norm, cmap=cmap)
1223
+ fig.colorbar(colorizer.ColorizingArtist(cr), ax=ax)
1224
+
1225
+ cax : `~matplotlib.axes.Axes`, optional
1226
+ Axes into which the colorbar will be drawn. If `None`, then a new
1227
+ Axes is created and the space for it will be stolen from the Axes(s)
1228
+ specified in *ax*.
1229
+
1230
+ ax : `~matplotlib.axes.Axes` or iterable or `numpy.ndarray` of Axes, optional
1231
+ The one or more parent Axes from which space for a new colorbar Axes
1232
+ will be stolen. This parameter is only used if *cax* is not set.
1233
+
1234
+ Defaults to the Axes that contains the mappable used to create the
1235
+ colorbar.
1236
+
1237
+ use_gridspec : bool, optional
1238
+ If *cax* is ``None``, a new *cax* is created as an instance of
1239
+ Axes. If *ax* is positioned with a subplotspec and *use_gridspec*
1240
+ is ``True``, then *cax* is also positioned with a subplotspec.
1241
+
1242
+ Returns
1243
+ -------
1244
+ colorbar : `~matplotlib.colorbar.Colorbar`
1245
+
1246
+ Other Parameters
1247
+ ----------------
1248
+ %(_make_axes_kw_doc)s
1249
+ %(_colormap_kw_doc)s
1250
+
1251
+ Notes
1252
+ -----
1253
+ If *mappable* is a `~.contour.ContourSet`, its *extend* kwarg is
1254
+ included automatically.
1255
+
1256
+ The *shrink* kwarg provides a simple way to scale the colorbar with
1257
+ respect to the Axes. Note that if *cax* is specified, it determines the
1258
+ size of the colorbar, and *shrink* and *aspect* are ignored.
1259
+
1260
+ For more precise control, you can manually specify the positions of the
1261
+ axes objects in which the mappable and the colorbar are drawn. In this
1262
+ case, do not use any of the Axes properties kwargs.
1263
+
1264
+ It is known that some vector graphics viewers (svg and pdf) render
1265
+ white gaps between segments of the colorbar. This is due to bugs in
1266
+ the viewers, not Matplotlib. As a workaround, the colorbar can be
1267
+ rendered with overlapping segments::
1268
+
1269
+ cbar = colorbar()
1270
+ cbar.solids.set_edgecolor("face")
1271
+ draw()
1272
+
1273
+ However, this has negative consequences in other circumstances, e.g.
1274
+ with semi-transparent images (alpha < 1) and colorbar extensions;
1275
+ therefore, this workaround is not used by default (see issue #1188).
1276
+
1277
+ """
1278
+
1279
+ if ax is None:
1280
+ ax = getattr(mappable, "axes", None)
1281
+
1282
+ if cax is None:
1283
+ if ax is None:
1284
+ raise ValueError(
1285
+ 'Unable to determine Axes to steal space for Colorbar. '
1286
+ 'Either provide the *cax* argument to use as the Axes for '
1287
+ 'the Colorbar, provide the *ax* argument to steal space '
1288
+ 'from it, or add *mappable* to an Axes.')
1289
+ fig = ( # Figure of first Axes; logic copied from make_axes.
1290
+ [*ax.flat] if isinstance(ax, np.ndarray)
1291
+ else [*ax] if np.iterable(ax)
1292
+ else [ax])[0].get_figure(root=False)
1293
+ current_ax = fig.gca()
1294
+ if (fig.get_layout_engine() is not None and
1295
+ not fig.get_layout_engine().colorbar_gridspec):
1296
+ use_gridspec = False
1297
+ if (use_gridspec
1298
+ and isinstance(ax, mpl.axes._base._AxesBase)
1299
+ and ax.get_subplotspec()):
1300
+ cax, kwargs = cbar.make_axes_gridspec(ax, **kwargs)
1301
+ else:
1302
+ cax, kwargs = cbar.make_axes(ax, **kwargs)
1303
+ # make_axes calls add_{axes,subplot} which changes gca; undo that.
1304
+ fig.sca(current_ax)
1305
+ cax.grid(visible=False, which='both', axis='both')
1306
+
1307
+ if (hasattr(mappable, "get_figure") and
1308
+ (mappable_host_fig := mappable.get_figure(root=True)) is not None):
1309
+ # Warn in case of mismatch
1310
+ if mappable_host_fig is not self._root_figure:
1311
+ _api.warn_external(
1312
+ f'Adding colorbar to a different Figure '
1313
+ f'{repr(mappable_host_fig)} than '
1314
+ f'{repr(self._root_figure)} which '
1315
+ f'fig.colorbar is called on.')
1316
+
1317
+ NON_COLORBAR_KEYS = [ # remove kws that cannot be passed to Colorbar
1318
+ 'fraction', 'pad', 'shrink', 'aspect', 'anchor', 'panchor']
1319
+ cb = cbar.Colorbar(cax, mappable, **{
1320
+ k: v for k, v in kwargs.items() if k not in NON_COLORBAR_KEYS})
1321
+ cax.get_figure(root=False).stale = True
1322
+ return cb
1323
+
1324
+ def subplots_adjust(self, left=None, bottom=None, right=None, top=None,
1325
+ wspace=None, hspace=None):
1326
+ """
1327
+ Adjust the subplot layout parameters.
1328
+
1329
+ Unset parameters are left unmodified; initial values are given by
1330
+ :rc:`figure.subplot.[name]`.
1331
+
1332
+ .. plot:: _embedded_plots/figure_subplots_adjust.py
1333
+
1334
+ Parameters
1335
+ ----------
1336
+ left : float, optional
1337
+ The position of the left edge of the subplots,
1338
+ as a fraction of the figure width.
1339
+ right : float, optional
1340
+ The position of the right edge of the subplots,
1341
+ as a fraction of the figure width.
1342
+ bottom : float, optional
1343
+ The position of the bottom edge of the subplots,
1344
+ as a fraction of the figure height.
1345
+ top : float, optional
1346
+ The position of the top edge of the subplots,
1347
+ as a fraction of the figure height.
1348
+ wspace : float, optional
1349
+ The width of the padding between subplots,
1350
+ as a fraction of the average Axes width.
1351
+ hspace : float, optional
1352
+ The height of the padding between subplots,
1353
+ as a fraction of the average Axes height.
1354
+ """
1355
+ if (self.get_layout_engine() is not None and
1356
+ not self.get_layout_engine().adjust_compatible):
1357
+ _api.warn_external(
1358
+ "This figure was using a layout engine that is "
1359
+ "incompatible with subplots_adjust and/or tight_layout; "
1360
+ "not calling subplots_adjust.")
1361
+ return
1362
+ self.subplotpars.update(left, bottom, right, top, wspace, hspace)
1363
+ for ax in self.axes:
1364
+ if ax.get_subplotspec() is not None:
1365
+ ax._set_position(ax.get_subplotspec().get_position(self))
1366
+ self.stale = True
1367
+
1368
+ def align_xlabels(self, axs=None):
1369
+ """
1370
+ Align the xlabels of subplots in the same subplot row if label
1371
+ alignment is being done automatically (i.e. the label position is
1372
+ not manually set).
1373
+
1374
+ Alignment persists for draw events after this is called.
1375
+
1376
+ If a label is on the bottom, it is aligned with labels on Axes that
1377
+ also have their label on the bottom and that have the same
1378
+ bottom-most subplot row. If the label is on the top,
1379
+ it is aligned with labels on Axes with the same top-most row.
1380
+
1381
+ Parameters
1382
+ ----------
1383
+ axs : list of `~matplotlib.axes.Axes`
1384
+ Optional list of (or `~numpy.ndarray`) `~matplotlib.axes.Axes`
1385
+ to align the xlabels.
1386
+ Default is to align all Axes on the figure.
1387
+
1388
+ See Also
1389
+ --------
1390
+ matplotlib.figure.Figure.align_ylabels
1391
+ matplotlib.figure.Figure.align_titles
1392
+ matplotlib.figure.Figure.align_labels
1393
+
1394
+ Notes
1395
+ -----
1396
+ This assumes that all Axes in ``axs`` are from the same `.GridSpec`,
1397
+ so that their `.SubplotSpec` positions correspond to figure positions.
1398
+
1399
+ Examples
1400
+ --------
1401
+ Example with rotated xtick labels::
1402
+
1403
+ fig, axs = plt.subplots(1, 2)
1404
+ axs[0].tick_params(axis='x', rotation=55)
1405
+ axs[0].set_xlabel('XLabel 0')
1406
+ axs[1].set_xlabel('XLabel 1')
1407
+ fig.align_xlabels()
1408
+ """
1409
+ if axs is None:
1410
+ axs = self.axes
1411
+ axs = [ax for ax in np.ravel(axs) if ax.get_subplotspec() is not None]
1412
+ for ax in axs:
1413
+ _log.debug(' Working on: %s', ax.get_xlabel())
1414
+ rowspan = ax.get_subplotspec().rowspan
1415
+ pos = ax.xaxis.get_label_position() # top or bottom
1416
+ # Search through other Axes for label positions that are same as
1417
+ # this one and that share the appropriate row number.
1418
+ # Add to a grouper associated with each Axes of siblings.
1419
+ # This list is inspected in `axis.draw` by
1420
+ # `axis._update_label_position`.
1421
+ for axc in axs:
1422
+ if axc.xaxis.get_label_position() == pos:
1423
+ rowspanc = axc.get_subplotspec().rowspan
1424
+ if (pos == 'top' and rowspan.start == rowspanc.start or
1425
+ pos == 'bottom' and rowspan.stop == rowspanc.stop):
1426
+ # grouper for groups of xlabels to align
1427
+ self._align_label_groups['x'].join(ax, axc)
1428
+
1429
+ def align_ylabels(self, axs=None):
1430
+ """
1431
+ Align the ylabels of subplots in the same subplot column if label
1432
+ alignment is being done automatically (i.e. the label position is
1433
+ not manually set).
1434
+
1435
+ Alignment persists for draw events after this is called.
1436
+
1437
+ If a label is on the left, it is aligned with labels on Axes that
1438
+ also have their label on the left and that have the same
1439
+ left-most subplot column. If the label is on the right,
1440
+ it is aligned with labels on Axes with the same right-most column.
1441
+
1442
+ Parameters
1443
+ ----------
1444
+ axs : list of `~matplotlib.axes.Axes`
1445
+ Optional list (or `~numpy.ndarray`) of `~matplotlib.axes.Axes`
1446
+ to align the ylabels.
1447
+ Default is to align all Axes on the figure.
1448
+
1449
+ See Also
1450
+ --------
1451
+ matplotlib.figure.Figure.align_xlabels
1452
+ matplotlib.figure.Figure.align_titles
1453
+ matplotlib.figure.Figure.align_labels
1454
+
1455
+ Notes
1456
+ -----
1457
+ This assumes that all Axes in ``axs`` are from the same `.GridSpec`,
1458
+ so that their `.SubplotSpec` positions correspond to figure positions.
1459
+
1460
+ Examples
1461
+ --------
1462
+ Example with large yticks labels::
1463
+
1464
+ fig, axs = plt.subplots(2, 1)
1465
+ axs[0].plot(np.arange(0, 1000, 50))
1466
+ axs[0].set_ylabel('YLabel 0')
1467
+ axs[1].set_ylabel('YLabel 1')
1468
+ fig.align_ylabels()
1469
+ """
1470
+ if axs is None:
1471
+ axs = self.axes
1472
+ axs = [ax for ax in np.ravel(axs) if ax.get_subplotspec() is not None]
1473
+ for ax in axs:
1474
+ _log.debug(' Working on: %s', ax.get_ylabel())
1475
+ colspan = ax.get_subplotspec().colspan
1476
+ pos = ax.yaxis.get_label_position() # left or right
1477
+ # Search through other Axes for label positions that are same as
1478
+ # this one and that share the appropriate column number.
1479
+ # Add to a list associated with each Axes of siblings.
1480
+ # This list is inspected in `axis.draw` by
1481
+ # `axis._update_label_position`.
1482
+ for axc in axs:
1483
+ if axc.yaxis.get_label_position() == pos:
1484
+ colspanc = axc.get_subplotspec().colspan
1485
+ if (pos == 'left' and colspan.start == colspanc.start or
1486
+ pos == 'right' and colspan.stop == colspanc.stop):
1487
+ # grouper for groups of ylabels to align
1488
+ self._align_label_groups['y'].join(ax, axc)
1489
+
1490
+ def align_titles(self, axs=None):
1491
+ """
1492
+ Align the titles of subplots in the same subplot row if title
1493
+ alignment is being done automatically (i.e. the title position is
1494
+ not manually set).
1495
+
1496
+ Alignment persists for draw events after this is called.
1497
+
1498
+ Parameters
1499
+ ----------
1500
+ axs : list of `~matplotlib.axes.Axes`
1501
+ Optional list of (or ndarray) `~matplotlib.axes.Axes`
1502
+ to align the titles.
1503
+ Default is to align all Axes on the figure.
1504
+
1505
+ See Also
1506
+ --------
1507
+ matplotlib.figure.Figure.align_xlabels
1508
+ matplotlib.figure.Figure.align_ylabels
1509
+ matplotlib.figure.Figure.align_labels
1510
+
1511
+ Notes
1512
+ -----
1513
+ This assumes that all Axes in ``axs`` are from the same `.GridSpec`,
1514
+ so that their `.SubplotSpec` positions correspond to figure positions.
1515
+
1516
+ Examples
1517
+ --------
1518
+ Example with titles::
1519
+
1520
+ fig, axs = plt.subplots(1, 2)
1521
+ axs[0].set_aspect('equal')
1522
+ axs[0].set_title('Title 0')
1523
+ axs[1].set_title('Title 1')
1524
+ fig.align_titles()
1525
+ """
1526
+ if axs is None:
1527
+ axs = self.axes
1528
+ axs = [ax for ax in np.ravel(axs) if ax.get_subplotspec() is not None]
1529
+ for ax in axs:
1530
+ _log.debug(' Working on: %s', ax.get_title())
1531
+ rowspan = ax.get_subplotspec().rowspan
1532
+ for axc in axs:
1533
+ rowspanc = axc.get_subplotspec().rowspan
1534
+ if (rowspan.start == rowspanc.start):
1535
+ self._align_label_groups['title'].join(ax, axc)
1536
+
1537
+ def align_labels(self, axs=None):
1538
+ """
1539
+ Align the xlabels and ylabels of subplots with the same subplots
1540
+ row or column (respectively) if label alignment is being
1541
+ done automatically (i.e. the label position is not manually set).
1542
+
1543
+ Alignment persists for draw events after this is called.
1544
+
1545
+ Parameters
1546
+ ----------
1547
+ axs : list of `~matplotlib.axes.Axes`
1548
+ Optional list (or `~numpy.ndarray`) of `~matplotlib.axes.Axes`
1549
+ to align the labels.
1550
+ Default is to align all Axes on the figure.
1551
+
1552
+ See Also
1553
+ --------
1554
+ matplotlib.figure.Figure.align_xlabels
1555
+ matplotlib.figure.Figure.align_ylabels
1556
+ matplotlib.figure.Figure.align_titles
1557
+
1558
+ Notes
1559
+ -----
1560
+ This assumes that all Axes in ``axs`` are from the same `.GridSpec`,
1561
+ so that their `.SubplotSpec` positions correspond to figure positions.
1562
+ """
1563
+ self.align_xlabels(axs=axs)
1564
+ self.align_ylabels(axs=axs)
1565
+
1566
+ def add_gridspec(self, nrows=1, ncols=1, **kwargs):
1567
+ """
1568
+ Low-level API for creating a `.GridSpec` that has this figure as a parent.
1569
+
1570
+ This is a low-level API, allowing you to create a gridspec and
1571
+ subsequently add subplots based on the gridspec. Most users do
1572
+ not need that freedom and should use the higher-level methods
1573
+ `~.Figure.subplots` or `~.Figure.subplot_mosaic`.
1574
+
1575
+ Parameters
1576
+ ----------
1577
+ nrows : int, default: 1
1578
+ Number of rows in grid.
1579
+
1580
+ ncols : int, default: 1
1581
+ Number of columns in grid.
1582
+
1583
+ Returns
1584
+ -------
1585
+ `.GridSpec`
1586
+
1587
+ Other Parameters
1588
+ ----------------
1589
+ **kwargs
1590
+ Keyword arguments are passed to `.GridSpec`.
1591
+
1592
+ See Also
1593
+ --------
1594
+ matplotlib.pyplot.subplots
1595
+
1596
+ Examples
1597
+ --------
1598
+ Adding a subplot that spans two rows::
1599
+
1600
+ fig = plt.figure()
1601
+ gs = fig.add_gridspec(2, 2)
1602
+ ax1 = fig.add_subplot(gs[0, 0])
1603
+ ax2 = fig.add_subplot(gs[1, 0])
1604
+ # spans two rows:
1605
+ ax3 = fig.add_subplot(gs[:, 1])
1606
+
1607
+ """
1608
+
1609
+ _ = kwargs.pop('figure', None) # pop in case user has added this...
1610
+ gs = GridSpec(nrows=nrows, ncols=ncols, figure=self, **kwargs)
1611
+ return gs
1612
+
1613
+ def subfigures(self, nrows=1, ncols=1, squeeze=True,
1614
+ wspace=None, hspace=None,
1615
+ width_ratios=None, height_ratios=None,
1616
+ **kwargs):
1617
+ """
1618
+ Add a set of subfigures to this figure or subfigure.
1619
+
1620
+ A subfigure has the same artist methods as a figure, and is logically
1621
+ the same as a figure, but cannot print itself.
1622
+ See :doc:`/gallery/subplots_axes_and_figures/subfigures`.
1623
+
1624
+ .. versionchanged:: 3.10
1625
+ subfigures are now added in row-major order.
1626
+
1627
+ Parameters
1628
+ ----------
1629
+ nrows, ncols : int, default: 1
1630
+ Number of rows/columns of the subfigure grid.
1631
+
1632
+ squeeze : bool, default: True
1633
+ If True, extra dimensions are squeezed out from the returned
1634
+ array of subfigures.
1635
+
1636
+ wspace, hspace : float, default: None
1637
+ The amount of width/height reserved for space between subfigures,
1638
+ expressed as a fraction of the average subfigure width/height.
1639
+ If not given, the values will be inferred from rcParams if using
1640
+ constrained layout (see `~.ConstrainedLayoutEngine`), or zero if
1641
+ not using a layout engine.
1642
+
1643
+ width_ratios : array-like of length *ncols*, optional
1644
+ Defines the relative widths of the columns. Each column gets a
1645
+ relative width of ``width_ratios[i] / sum(width_ratios)``.
1646
+ If not given, all columns will have the same width.
1647
+
1648
+ height_ratios : array-like of length *nrows*, optional
1649
+ Defines the relative heights of the rows. Each row gets a
1650
+ relative height of ``height_ratios[i] / sum(height_ratios)``.
1651
+ If not given, all rows will have the same height.
1652
+ """
1653
+ gs = GridSpec(nrows=nrows, ncols=ncols, figure=self,
1654
+ wspace=wspace, hspace=hspace,
1655
+ width_ratios=width_ratios,
1656
+ height_ratios=height_ratios,
1657
+ left=0, right=1, bottom=0, top=1)
1658
+
1659
+ sfarr = np.empty((nrows, ncols), dtype=object)
1660
+ for i in range(nrows):
1661
+ for j in range(ncols):
1662
+ sfarr[i, j] = self.add_subfigure(gs[i, j], **kwargs)
1663
+
1664
+ if self.get_layout_engine() is None and (wspace is not None or
1665
+ hspace is not None):
1666
+ # Gridspec wspace and hspace is ignored on subfigure instantiation,
1667
+ # and no space is left. So need to account for it here if required.
1668
+ bottoms, tops, lefts, rights = gs.get_grid_positions(self)
1669
+ for sfrow, bottom, top in zip(sfarr, bottoms, tops):
1670
+ for sf, left, right in zip(sfrow, lefts, rights):
1671
+ bbox = Bbox.from_extents(left, bottom, right, top)
1672
+ sf._redo_transform_rel_fig(bbox=bbox)
1673
+
1674
+ if squeeze:
1675
+ # Discarding unneeded dimensions that equal 1. If we only have one
1676
+ # subfigure, just return it instead of a 1-element array.
1677
+ return sfarr.item() if sfarr.size == 1 else sfarr.squeeze()
1678
+ else:
1679
+ # Returned axis array will be always 2-d, even if nrows=ncols=1.
1680
+ return sfarr
1681
+
1682
+ def add_subfigure(self, subplotspec, **kwargs):
1683
+ """
1684
+ Add a `.SubFigure` to the figure as part of a subplot arrangement.
1685
+
1686
+ Parameters
1687
+ ----------
1688
+ subplotspec : `.gridspec.SubplotSpec`
1689
+ Defines the region in a parent gridspec where the subfigure will
1690
+ be placed.
1691
+
1692
+ Returns
1693
+ -------
1694
+ `.SubFigure`
1695
+
1696
+ Other Parameters
1697
+ ----------------
1698
+ **kwargs
1699
+ Are passed to the `.SubFigure` object.
1700
+
1701
+ See Also
1702
+ --------
1703
+ .Figure.subfigures
1704
+ """
1705
+ sf = SubFigure(self, subplotspec, **kwargs)
1706
+ self.subfigs += [sf]
1707
+ sf._remove_method = self.subfigs.remove
1708
+ sf.stale_callback = _stale_figure_callback
1709
+ self.stale = True
1710
+ return sf
1711
+
1712
+ def sca(self, a):
1713
+ """Set the current Axes to be *a* and return *a*."""
1714
+ self._axstack.bubble(a)
1715
+ self._axobservers.process("_axes_change_event", self)
1716
+ return a
1717
+
1718
+ def gca(self):
1719
+ """
1720
+ Get the current Axes.
1721
+
1722
+ If there is currently no Axes on this Figure, a new one is created
1723
+ using `.Figure.add_subplot`. (To test whether there is currently an
1724
+ Axes on a Figure, check whether ``figure.axes`` is empty. To test
1725
+ whether there is currently a Figure on the pyplot figure stack, check
1726
+ whether `.pyplot.get_fignums()` is empty.)
1727
+ """
1728
+ ax = self._axstack.current()
1729
+ return ax if ax is not None else self.add_subplot()
1730
+
1731
+ def _gci(self):
1732
+ # Helper for `~matplotlib.pyplot.gci`. Do not use elsewhere.
1733
+ """
1734
+ Get the current colorable artist.
1735
+
1736
+ Specifically, returns the current `.ScalarMappable` instance (`.Image`
1737
+ created by `imshow` or `figimage`, `.Collection` created by `pcolor` or
1738
+ `scatter`, etc.), or *None* if no such instance has been defined.
1739
+
1740
+ The current image is an attribute of the current Axes, or the nearest
1741
+ earlier Axes in the current figure that contains an image.
1742
+
1743
+ Notes
1744
+ -----
1745
+ Historically, the only colorable artists were images; hence the name
1746
+ ``gci`` (get current image).
1747
+ """
1748
+ # Look first for an image in the current Axes.
1749
+ ax = self._axstack.current()
1750
+ if ax is None:
1751
+ return None
1752
+ im = ax._gci()
1753
+ if im is not None:
1754
+ return im
1755
+ # If there is no image in the current Axes, search for
1756
+ # one in a previously created Axes. Whether this makes
1757
+ # sense is debatable, but it is the documented behavior.
1758
+ for ax in reversed(self.axes):
1759
+ im = ax._gci()
1760
+ if im is not None:
1761
+ return im
1762
+ return None
1763
+
1764
+ def _process_projection_requirements(self, *, axes_class=None, polar=False,
1765
+ projection=None, **kwargs):
1766
+ """
1767
+ Handle the args/kwargs to add_axes/add_subplot/gca, returning::
1768
+
1769
+ (axes_proj_class, proj_class_kwargs)
1770
+
1771
+ which can be used for new Axes initialization/identification.
1772
+ """
1773
+ if axes_class is not None:
1774
+ if polar or projection is not None:
1775
+ raise ValueError(
1776
+ "Cannot combine 'axes_class' and 'projection' or 'polar'")
1777
+ projection_class = axes_class
1778
+ else:
1779
+
1780
+ if polar:
1781
+ if projection is not None and projection != 'polar':
1782
+ raise ValueError(
1783
+ f"polar={polar}, yet projection={projection!r}. "
1784
+ "Only one of these arguments should be supplied."
1785
+ )
1786
+ projection = 'polar'
1787
+
1788
+ if isinstance(projection, str) or projection is None:
1789
+ projection_class = projections.get_projection_class(projection)
1790
+ elif hasattr(projection, '_as_mpl_axes'):
1791
+ projection_class, extra_kwargs = projection._as_mpl_axes()
1792
+ kwargs.update(**extra_kwargs)
1793
+ else:
1794
+ raise TypeError(
1795
+ f"projection must be a string, None or implement a "
1796
+ f"_as_mpl_axes method, not {projection!r}")
1797
+ return projection_class, kwargs
1798
+
1799
+ def get_default_bbox_extra_artists(self):
1800
+ """
1801
+ Return a list of Artists typically used in `.Figure.get_tightbbox`.
1802
+ """
1803
+ bbox_artists = [artist for artist in self.get_children()
1804
+ if (artist.get_visible() and artist.get_in_layout())]
1805
+ for ax in self.axes:
1806
+ if ax.get_visible():
1807
+ bbox_artists.extend(ax.get_default_bbox_extra_artists())
1808
+ return bbox_artists
1809
+
1810
+ def get_tightbbox(self, renderer=None, *, bbox_extra_artists=None):
1811
+ """
1812
+ Return a (tight) bounding box of the figure *in inches*.
1813
+
1814
+ Note that `.FigureBase` differs from all other artists, which return
1815
+ their `.Bbox` in pixels.
1816
+
1817
+ Artists that have ``artist.set_in_layout(False)`` are not included
1818
+ in the bbox.
1819
+
1820
+ Parameters
1821
+ ----------
1822
+ renderer : `.RendererBase` subclass
1823
+ Renderer that will be used to draw the figures (i.e.
1824
+ ``fig.canvas.get_renderer()``)
1825
+
1826
+ bbox_extra_artists : list of `.Artist` or ``None``
1827
+ List of artists to include in the tight bounding box. If
1828
+ ``None`` (default), then all artist children of each Axes are
1829
+ included in the tight bounding box.
1830
+
1831
+ Returns
1832
+ -------
1833
+ `.BboxBase`
1834
+ containing the bounding box (in figure inches).
1835
+ """
1836
+
1837
+ if renderer is None:
1838
+ renderer = self.get_figure(root=True)._get_renderer()
1839
+
1840
+ bb = []
1841
+ if bbox_extra_artists is None:
1842
+ artists = [artist for artist in self.get_children()
1843
+ if (artist not in self.axes and artist.get_visible()
1844
+ and artist.get_in_layout())]
1845
+ else:
1846
+ artists = bbox_extra_artists
1847
+
1848
+ for a in artists:
1849
+ bbox = a.get_tightbbox(renderer)
1850
+ if bbox is not None:
1851
+ bb.append(bbox)
1852
+
1853
+ for ax in self.axes:
1854
+ if ax.get_visible():
1855
+ # some Axes don't take the bbox_extra_artists kwarg so we
1856
+ # need this conditional....
1857
+ try:
1858
+ bbox = ax.get_tightbbox(
1859
+ renderer, bbox_extra_artists=bbox_extra_artists)
1860
+ except TypeError:
1861
+ bbox = ax.get_tightbbox(renderer)
1862
+ bb.append(bbox)
1863
+ bb = [b for b in bb
1864
+ if (np.isfinite(b.width) and np.isfinite(b.height)
1865
+ and (b.width != 0 or b.height != 0))]
1866
+
1867
+ isfigure = hasattr(self, 'bbox_inches')
1868
+ if len(bb) == 0:
1869
+ if isfigure:
1870
+ return self.bbox_inches
1871
+ else:
1872
+ # subfigures do not have bbox_inches, but do have a bbox
1873
+ bb = [self.bbox]
1874
+
1875
+ _bbox = Bbox.union(bb)
1876
+
1877
+ if isfigure:
1878
+ # transform from pixels to inches...
1879
+ _bbox = TransformedBbox(_bbox, self.dpi_scale_trans.inverted())
1880
+
1881
+ return _bbox
1882
+
1883
+ @staticmethod
1884
+ def _norm_per_subplot_kw(per_subplot_kw):
1885
+ expanded = {}
1886
+ for k, v in per_subplot_kw.items():
1887
+ if isinstance(k, tuple):
1888
+ for sub_key in k:
1889
+ if sub_key in expanded:
1890
+ raise ValueError(f'The key {sub_key!r} appears multiple times.')
1891
+ expanded[sub_key] = v
1892
+ else:
1893
+ if k in expanded:
1894
+ raise ValueError(f'The key {k!r} appears multiple times.')
1895
+ expanded[k] = v
1896
+ return expanded
1897
+
1898
+ @staticmethod
1899
+ def _normalize_grid_string(layout):
1900
+ if '\n' not in layout:
1901
+ # single-line string
1902
+ return [list(ln) for ln in layout.split(';')]
1903
+ else:
1904
+ # multi-line string
1905
+ layout = inspect.cleandoc(layout)
1906
+ return [list(ln) for ln in layout.strip('\n').split('\n')]
1907
+
1908
+ def subplot_mosaic(self, mosaic, *, sharex=False, sharey=False,
1909
+ width_ratios=None, height_ratios=None,
1910
+ empty_sentinel='.',
1911
+ subplot_kw=None, per_subplot_kw=None, gridspec_kw=None):
1912
+ """
1913
+ Build a layout of Axes based on ASCII art or nested lists.
1914
+
1915
+ This is a helper function to build complex GridSpec layouts visually.
1916
+
1917
+ See :ref:`mosaic`
1918
+ for an example and full API documentation
1919
+
1920
+ Parameters
1921
+ ----------
1922
+ mosaic : list of list of {hashable or nested} or str
1923
+
1924
+ A visual layout of how you want your Axes to be arranged
1925
+ labeled as strings. For example ::
1926
+
1927
+ x = [['A panel', 'A panel', 'edge'],
1928
+ ['C panel', '.', 'edge']]
1929
+
1930
+ produces 4 Axes:
1931
+
1932
+ - 'A panel' which is 1 row high and spans the first two columns
1933
+ - 'edge' which is 2 rows high and is on the right edge
1934
+ - 'C panel' which in 1 row and 1 column wide in the bottom left
1935
+ - a blank space 1 row and 1 column wide in the bottom center
1936
+
1937
+ Any of the entries in the layout can be a list of lists
1938
+ of the same form to create nested layouts.
1939
+
1940
+ If input is a str, then it can either be a multi-line string of
1941
+ the form ::
1942
+
1943
+ '''
1944
+ AAE
1945
+ C.E
1946
+ '''
1947
+
1948
+ where each character is a column and each line is a row. Or it
1949
+ can be a single-line string where rows are separated by ``;``::
1950
+
1951
+ 'AB;CC'
1952
+
1953
+ The string notation allows only single character Axes labels and
1954
+ does not support nesting but is very terse.
1955
+
1956
+ The Axes identifiers may be `str` or a non-iterable hashable
1957
+ object (e.g. `tuple` s may not be used).
1958
+
1959
+ sharex, sharey : bool, default: False
1960
+ If True, the x-axis (*sharex*) or y-axis (*sharey*) will be shared
1961
+ among all subplots. In that case, tick label visibility and axis
1962
+ units behave as for `subplots`. If False, each subplot's x- or
1963
+ y-axis will be independent.
1964
+
1965
+ width_ratios : array-like of length *ncols*, optional
1966
+ Defines the relative widths of the columns. Each column gets a
1967
+ relative width of ``width_ratios[i] / sum(width_ratios)``.
1968
+ If not given, all columns will have the same width. Equivalent
1969
+ to ``gridspec_kw={'width_ratios': [...]}``. In the case of nested
1970
+ layouts, this argument applies only to the outer layout.
1971
+
1972
+ height_ratios : array-like of length *nrows*, optional
1973
+ Defines the relative heights of the rows. Each row gets a
1974
+ relative height of ``height_ratios[i] / sum(height_ratios)``.
1975
+ If not given, all rows will have the same height. Equivalent
1976
+ to ``gridspec_kw={'height_ratios': [...]}``. In the case of nested
1977
+ layouts, this argument applies only to the outer layout.
1978
+
1979
+ subplot_kw : dict, optional
1980
+ Dictionary with keywords passed to the `.Figure.add_subplot` call
1981
+ used to create each subplot. These values may be overridden by
1982
+ values in *per_subplot_kw*.
1983
+
1984
+ per_subplot_kw : dict, optional
1985
+ A dictionary mapping the Axes identifiers or tuples of identifiers
1986
+ to a dictionary of keyword arguments to be passed to the
1987
+ `.Figure.add_subplot` call used to create each subplot. The values
1988
+ in these dictionaries have precedence over the values in
1989
+ *subplot_kw*.
1990
+
1991
+ If *mosaic* is a string, and thus all keys are single characters,
1992
+ it is possible to use a single string instead of a tuple as keys;
1993
+ i.e. ``"AB"`` is equivalent to ``("A", "B")``.
1994
+
1995
+ .. versionadded:: 3.7
1996
+
1997
+ gridspec_kw : dict, optional
1998
+ Dictionary with keywords passed to the `.GridSpec` constructor used
1999
+ to create the grid the subplots are placed on. In the case of
2000
+ nested layouts, this argument applies only to the outer layout.
2001
+ For more complex layouts, users should use `.Figure.subfigures`
2002
+ to create the nesting.
2003
+
2004
+ empty_sentinel : object, optional
2005
+ Entry in the layout to mean "leave this space empty". Defaults
2006
+ to ``'.'``. Note, if *layout* is a string, it is processed via
2007
+ `inspect.cleandoc` to remove leading white space, which may
2008
+ interfere with using white-space as the empty sentinel.
2009
+
2010
+ Returns
2011
+ -------
2012
+ dict[label, Axes]
2013
+ A dictionary mapping the labels to the Axes objects. The order of
2014
+ the Axes is left-to-right and top-to-bottom of their position in the
2015
+ total layout.
2016
+
2017
+ """
2018
+ subplot_kw = subplot_kw or {}
2019
+ gridspec_kw = dict(gridspec_kw or {})
2020
+ per_subplot_kw = per_subplot_kw or {}
2021
+
2022
+ if height_ratios is not None:
2023
+ if 'height_ratios' in gridspec_kw:
2024
+ raise ValueError("'height_ratios' must not be defined both as "
2025
+ "parameter and as key in 'gridspec_kw'")
2026
+ gridspec_kw['height_ratios'] = height_ratios
2027
+ if width_ratios is not None:
2028
+ if 'width_ratios' in gridspec_kw:
2029
+ raise ValueError("'width_ratios' must not be defined both as "
2030
+ "parameter and as key in 'gridspec_kw'")
2031
+ gridspec_kw['width_ratios'] = width_ratios
2032
+
2033
+ # special-case string input
2034
+ if isinstance(mosaic, str):
2035
+ mosaic = self._normalize_grid_string(mosaic)
2036
+ per_subplot_kw = {
2037
+ tuple(k): v for k, v in per_subplot_kw.items()
2038
+ }
2039
+
2040
+ per_subplot_kw = self._norm_per_subplot_kw(per_subplot_kw)
2041
+
2042
+ # Only accept strict bools to allow a possible future API expansion.
2043
+ _api.check_isinstance(bool, sharex=sharex, sharey=sharey)
2044
+
2045
+ def _make_array(inp):
2046
+ """
2047
+ Convert input into 2D array
2048
+
2049
+ We need to have this internal function rather than
2050
+ ``np.asarray(..., dtype=object)`` so that a list of lists
2051
+ of lists does not get converted to an array of dimension > 2.
2052
+
2053
+ Returns
2054
+ -------
2055
+ 2D object array
2056
+ """
2057
+ r0, *rest = inp
2058
+ if isinstance(r0, str):
2059
+ raise ValueError('List mosaic specification must be 2D')
2060
+ for j, r in enumerate(rest, start=1):
2061
+ if isinstance(r, str):
2062
+ raise ValueError('List mosaic specification must be 2D')
2063
+ if len(r0) != len(r):
2064
+ raise ValueError(
2065
+ "All of the rows must be the same length, however "
2066
+ f"the first row ({r0!r}) has length {len(r0)} "
2067
+ f"and row {j} ({r!r}) has length {len(r)}."
2068
+ )
2069
+ out = np.zeros((len(inp), len(r0)), dtype=object)
2070
+ for j, r in enumerate(inp):
2071
+ for k, v in enumerate(r):
2072
+ out[j, k] = v
2073
+ return out
2074
+
2075
+ def _identify_keys_and_nested(mosaic):
2076
+ """
2077
+ Given a 2D object array, identify unique IDs and nested mosaics
2078
+
2079
+ Parameters
2080
+ ----------
2081
+ mosaic : 2D object array
2082
+
2083
+ Returns
2084
+ -------
2085
+ unique_ids : tuple
2086
+ The unique non-sub mosaic entries in this mosaic
2087
+ nested : dict[tuple[int, int], 2D object array]
2088
+ """
2089
+ # make sure we preserve the user supplied order
2090
+ unique_ids = cbook._OrderedSet()
2091
+ nested = {}
2092
+ for j, row in enumerate(mosaic):
2093
+ for k, v in enumerate(row):
2094
+ if v == empty_sentinel:
2095
+ continue
2096
+ elif not cbook.is_scalar_or_string(v):
2097
+ nested[(j, k)] = _make_array(v)
2098
+ else:
2099
+ unique_ids.add(v)
2100
+
2101
+ return tuple(unique_ids), nested
2102
+
2103
+ def _do_layout(gs, mosaic, unique_ids, nested):
2104
+ """
2105
+ Recursively do the mosaic.
2106
+
2107
+ Parameters
2108
+ ----------
2109
+ gs : GridSpec
2110
+ mosaic : 2D object array
2111
+ The input converted to a 2D array for this level.
2112
+ unique_ids : tuple
2113
+ The identified scalar labels at this level of nesting.
2114
+ nested : dict[tuple[int, int]], 2D object array
2115
+ The identified nested mosaics, if any.
2116
+
2117
+ Returns
2118
+ -------
2119
+ dict[label, Axes]
2120
+ A flat dict of all of the Axes created.
2121
+ """
2122
+ output = dict()
2123
+
2124
+ # we need to merge together the Axes at this level and the Axes
2125
+ # in the (recursively) nested sub-mosaics so that we can add
2126
+ # them to the figure in the "natural" order if you were to
2127
+ # ravel in c-order all of the Axes that will be created
2128
+ #
2129
+ # This will stash the upper left index of each object (axes or
2130
+ # nested mosaic) at this level
2131
+ this_level = dict()
2132
+
2133
+ # go through the unique keys,
2134
+ for name in unique_ids:
2135
+ # sort out where each axes starts/ends
2136
+ index = np.argwhere(mosaic == name)
2137
+ start_row, start_col = np.min(index, axis=0)
2138
+ end_row, end_col = np.max(index, axis=0) + 1
2139
+ # and construct the slice object
2140
+ slc = (slice(start_row, end_row), slice(start_col, end_col))
2141
+ # some light error checking
2142
+ if (mosaic[slc] != name).any():
2143
+ raise ValueError(
2144
+ f"While trying to layout\n{mosaic!r}\n"
2145
+ f"we found that the label {name!r} specifies a "
2146
+ "non-rectangular or non-contiguous area.")
2147
+ # and stash this slice for later
2148
+ this_level[(start_row, start_col)] = (name, slc, 'axes')
2149
+
2150
+ # do the same thing for the nested mosaics (simpler because these
2151
+ # cannot be spans yet!)
2152
+ for (j, k), nested_mosaic in nested.items():
2153
+ this_level[(j, k)] = (None, nested_mosaic, 'nested')
2154
+
2155
+ # now go through the things in this level and add them
2156
+ # in order left-to-right top-to-bottom
2157
+ for key in sorted(this_level):
2158
+ name, arg, method = this_level[key]
2159
+ # we are doing some hokey function dispatch here based
2160
+ # on the 'method' string stashed above to sort out if this
2161
+ # element is an Axes or a nested mosaic.
2162
+ if method == 'axes':
2163
+ slc = arg
2164
+ # add a single Axes
2165
+ if name in output:
2166
+ raise ValueError(f"There are duplicate keys {name} "
2167
+ f"in the layout\n{mosaic!r}")
2168
+ ax = self.add_subplot(
2169
+ gs[slc], **{
2170
+ 'label': str(name),
2171
+ **subplot_kw,
2172
+ **per_subplot_kw.get(name, {})
2173
+ }
2174
+ )
2175
+ output[name] = ax
2176
+ elif method == 'nested':
2177
+ nested_mosaic = arg
2178
+ j, k = key
2179
+ # recursively add the nested mosaic
2180
+ rows, cols = nested_mosaic.shape
2181
+ nested_output = _do_layout(
2182
+ gs[j, k].subgridspec(rows, cols),
2183
+ nested_mosaic,
2184
+ *_identify_keys_and_nested(nested_mosaic)
2185
+ )
2186
+ overlap = set(output) & set(nested_output)
2187
+ if overlap:
2188
+ raise ValueError(
2189
+ f"There are duplicate keys {overlap} "
2190
+ f"between the outer layout\n{mosaic!r}\n"
2191
+ f"and the nested layout\n{nested_mosaic}"
2192
+ )
2193
+ output.update(nested_output)
2194
+ else:
2195
+ raise RuntimeError("This should never happen")
2196
+ return output
2197
+
2198
+ mosaic = _make_array(mosaic)
2199
+ rows, cols = mosaic.shape
2200
+ gs = self.add_gridspec(rows, cols, **gridspec_kw)
2201
+ ret = _do_layout(gs, mosaic, *_identify_keys_and_nested(mosaic))
2202
+ ax0 = next(iter(ret.values()))
2203
+ for ax in ret.values():
2204
+ if sharex:
2205
+ ax.sharex(ax0)
2206
+ ax._label_outer_xaxis(skip_non_rectangular_axes=True)
2207
+ if sharey:
2208
+ ax.sharey(ax0)
2209
+ ax._label_outer_yaxis(skip_non_rectangular_axes=True)
2210
+ if extra := set(per_subplot_kw) - set(ret):
2211
+ raise ValueError(
2212
+ f"The keys {extra} are in *per_subplot_kw* "
2213
+ "but not in the mosaic."
2214
+ )
2215
+ return ret
2216
+
2217
+ def _set_artist_props(self, a):
2218
+ if a != self:
2219
+ a.set_figure(self)
2220
+ a.stale_callback = _stale_figure_callback
2221
+ a.set_transform(self.transSubfigure)
2222
+
2223
+
2224
+ @_docstring.interpd
2225
+ class SubFigure(FigureBase):
2226
+ """
2227
+ Logical figure that can be placed inside a figure.
2228
+
2229
+ See :ref:`figure-api-subfigure` for an index of methods on this class.
2230
+ Typically instantiated using `.Figure.add_subfigure` or
2231
+ `.SubFigure.add_subfigure`, or `.SubFigure.subfigures`. A subfigure has
2232
+ the same methods as a figure except for those particularly tied to the size
2233
+ or dpi of the figure, and is confined to a prescribed region of the figure.
2234
+ For example the following puts two subfigures side-by-side::
2235
+
2236
+ fig = plt.figure()
2237
+ sfigs = fig.subfigures(1, 2)
2238
+ axsL = sfigs[0].subplots(1, 2)
2239
+ axsR = sfigs[1].subplots(2, 1)
2240
+
2241
+ See :doc:`/gallery/subplots_axes_and_figures/subfigures`
2242
+ """
2243
+
2244
+ def __init__(self, parent, subplotspec, *,
2245
+ facecolor=None,
2246
+ edgecolor=None,
2247
+ linewidth=0.0,
2248
+ frameon=None,
2249
+ **kwargs):
2250
+ """
2251
+ Parameters
2252
+ ----------
2253
+ parent : `.Figure` or `.SubFigure`
2254
+ Figure or subfigure that contains the SubFigure. SubFigures
2255
+ can be nested.
2256
+
2257
+ subplotspec : `.gridspec.SubplotSpec`
2258
+ Defines the region in a parent gridspec where the subfigure will
2259
+ be placed.
2260
+
2261
+ facecolor : default: ``"none"``
2262
+ The figure patch face color; transparent by default.
2263
+
2264
+ edgecolor : default: :rc:`figure.edgecolor`
2265
+ The figure patch edge color.
2266
+
2267
+ linewidth : float
2268
+ The linewidth of the frame (i.e. the edge linewidth of the figure
2269
+ patch).
2270
+
2271
+ frameon : bool, default: :rc:`figure.frameon`
2272
+ If ``False``, suppress drawing the figure background patch.
2273
+
2274
+ Other Parameters
2275
+ ----------------
2276
+ **kwargs : `.SubFigure` properties, optional
2277
+
2278
+ %(SubFigure:kwdoc)s
2279
+ """
2280
+ super().__init__(**kwargs)
2281
+ if facecolor is None:
2282
+ facecolor = "none"
2283
+ edgecolor = mpl._val_or_rc(edgecolor, 'figure.edgecolor')
2284
+ frameon = mpl._val_or_rc(frameon, 'figure.frameon')
2285
+
2286
+ self._subplotspec = subplotspec
2287
+ self._parent = parent
2288
+ self._root_figure = parent._root_figure
2289
+
2290
+ # subfigures use the parent axstack
2291
+ self._axstack = parent._axstack
2292
+ self.subplotpars = parent.subplotpars
2293
+ self.dpi_scale_trans = parent.dpi_scale_trans
2294
+ self._axobservers = parent._axobservers
2295
+ self.transFigure = parent.transFigure
2296
+ self.bbox_relative = Bbox.null()
2297
+ self._redo_transform_rel_fig()
2298
+ self.figbbox = self._parent.figbbox
2299
+ self.bbox = TransformedBbox(self.bbox_relative,
2300
+ self._parent.transSubfigure)
2301
+ self.transSubfigure = BboxTransformTo(self.bbox)
2302
+
2303
+ self.patch = Rectangle(
2304
+ xy=(0, 0), width=1, height=1, visible=frameon,
2305
+ facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth,
2306
+ # Don't let the figure patch influence bbox calculation.
2307
+ in_layout=False, transform=self.transSubfigure)
2308
+ self._set_artist_props(self.patch)
2309
+ self.patch.set_antialiased(False)
2310
+
2311
+ @property
2312
+ def canvas(self):
2313
+ return self._parent.canvas
2314
+
2315
+ @property
2316
+ def dpi(self):
2317
+ return self._parent.dpi
2318
+
2319
+ @dpi.setter
2320
+ def dpi(self, value):
2321
+ self._parent.dpi = value
2322
+
2323
+ def get_dpi(self):
2324
+ """
2325
+ Return the resolution of the parent figure in dots-per-inch as a float.
2326
+ """
2327
+ return self._parent.dpi
2328
+
2329
+ def set_dpi(self, val):
2330
+ """
2331
+ Set the resolution of parent figure in dots-per-inch.
2332
+
2333
+ Parameters
2334
+ ----------
2335
+ val : float
2336
+ """
2337
+ self._parent.dpi = val
2338
+ self.stale = True
2339
+
2340
+ def _get_renderer(self):
2341
+ return self._parent._get_renderer()
2342
+
2343
+ def _redo_transform_rel_fig(self, bbox=None):
2344
+ """
2345
+ Make the transSubfigure bbox relative to Figure transform.
2346
+
2347
+ Parameters
2348
+ ----------
2349
+ bbox : bbox or None
2350
+ If not None, then the bbox is used for relative bounding box.
2351
+ Otherwise, it is calculated from the subplotspec.
2352
+ """
2353
+ if bbox is not None:
2354
+ self.bbox_relative.p0 = bbox.p0
2355
+ self.bbox_relative.p1 = bbox.p1
2356
+ return
2357
+ # need to figure out *where* this subplotspec is.
2358
+ gs = self._subplotspec.get_gridspec()
2359
+ wr = np.asarray(gs.get_width_ratios())
2360
+ hr = np.asarray(gs.get_height_ratios())
2361
+ dx = wr[self._subplotspec.colspan].sum() / wr.sum()
2362
+ dy = hr[self._subplotspec.rowspan].sum() / hr.sum()
2363
+ x0 = wr[:self._subplotspec.colspan.start].sum() / wr.sum()
2364
+ y0 = 1 - hr[:self._subplotspec.rowspan.stop].sum() / hr.sum()
2365
+ self.bbox_relative.p0 = (x0, y0)
2366
+ self.bbox_relative.p1 = (x0 + dx, y0 + dy)
2367
+
2368
+ def get_constrained_layout(self):
2369
+ """
2370
+ Return whether constrained layout is being used.
2371
+
2372
+ See :ref:`constrainedlayout_guide`.
2373
+ """
2374
+ return self._parent.get_constrained_layout()
2375
+
2376
+ def get_constrained_layout_pads(self, relative=False):
2377
+ """
2378
+ Get padding for ``constrained_layout``.
2379
+
2380
+ Returns a list of ``w_pad, h_pad`` in inches and
2381
+ ``wspace`` and ``hspace`` as fractions of the subplot.
2382
+
2383
+ See :ref:`constrainedlayout_guide`.
2384
+
2385
+ Parameters
2386
+ ----------
2387
+ relative : bool
2388
+ If `True`, then convert from inches to figure relative.
2389
+ """
2390
+ return self._parent.get_constrained_layout_pads(relative=relative)
2391
+
2392
+ def get_layout_engine(self):
2393
+ return self._parent.get_layout_engine()
2394
+
2395
+ @property
2396
+ def axes(self):
2397
+ """
2398
+ List of Axes in the SubFigure. You can access and modify the Axes
2399
+ in the SubFigure through this list.
2400
+
2401
+ Modifying this list has no effect. Instead, use `~.SubFigure.add_axes`,
2402
+ `~.SubFigure.add_subplot` or `~.SubFigure.delaxes` to add or remove an
2403
+ Axes.
2404
+
2405
+ Note: The `.SubFigure.axes` property and `~.SubFigure.get_axes` method
2406
+ are equivalent.
2407
+ """
2408
+ return self._localaxes[:]
2409
+
2410
+ get_axes = axes.fget
2411
+
2412
+ def draw(self, renderer):
2413
+ # docstring inherited
2414
+
2415
+ # draw the figure bounding box, perhaps none for white figure
2416
+ if not self.get_visible():
2417
+ return
2418
+
2419
+ artists = self._get_draw_artists(renderer)
2420
+
2421
+ try:
2422
+ renderer.open_group('subfigure', gid=self.get_gid())
2423
+ self.patch.draw(renderer)
2424
+ mimage._draw_list_compositing_images(
2425
+ renderer, self, artists, self.get_figure(root=True).suppressComposite)
2426
+ renderer.close_group('subfigure')
2427
+
2428
+ finally:
2429
+ self.stale = False
2430
+
2431
+
2432
+ @_docstring.interpd
2433
+ class Figure(FigureBase):
2434
+ """
2435
+ The top level container for all the plot elements.
2436
+
2437
+ See `matplotlib.figure` for an index of class methods.
2438
+
2439
+ Attributes
2440
+ ----------
2441
+ patch
2442
+ The `.Rectangle` instance representing the figure background patch.
2443
+
2444
+ suppressComposite
2445
+ For multiple images, the figure will make composite images
2446
+ depending on the renderer option_image_nocomposite function. If
2447
+ *suppressComposite* is a boolean, this will override the renderer.
2448
+ """
2449
+
2450
+ # we want to cache the fonts and mathtext at a global level so that when
2451
+ # multiple figures are created we can reuse them. This helps with a bug on
2452
+ # windows where the creation of too many figures leads to too many open
2453
+ # file handles and improves the performance of parsing mathtext. However,
2454
+ # these global caches are not thread safe. The solution here is to let the
2455
+ # Figure acquire a shared lock at the start of the draw, and release it when it
2456
+ # is done. This allows multiple renderers to share the cached fonts and
2457
+ # parsed text, but only one figure can draw at a time and so the font cache
2458
+ # and mathtext cache are used by only one renderer at a time.
2459
+
2460
+ _render_lock = threading.RLock()
2461
+
2462
+ def __str__(self):
2463
+ return "Figure(%gx%g)" % tuple(self.bbox.size)
2464
+
2465
+ def __repr__(self):
2466
+ return "<{clsname} size {h:g}x{w:g} with {naxes} Axes>".format(
2467
+ clsname=self.__class__.__name__,
2468
+ h=self.bbox.size[0], w=self.bbox.size[1],
2469
+ naxes=len(self.axes),
2470
+ )
2471
+
2472
+ def __init__(self,
2473
+ figsize=None,
2474
+ dpi=None,
2475
+ *,
2476
+ facecolor=None,
2477
+ edgecolor=None,
2478
+ linewidth=0.0,
2479
+ frameon=None,
2480
+ subplotpars=None, # rc figure.subplot.*
2481
+ tight_layout=None, # rc figure.autolayout
2482
+ constrained_layout=None, # rc figure.constrained_layout.use
2483
+ layout=None,
2484
+ **kwargs
2485
+ ):
2486
+ """
2487
+ Parameters
2488
+ ----------
2489
+ figsize : (float, float) or (float, float, str), default: :rc:`figure.figsize`
2490
+ The figure dimensions. This can be
2491
+
2492
+ - a tuple ``(width, height, unit)``, where *unit* is one of "in" (inch),
2493
+ "cm" (centimenter), "px" (pixel).
2494
+ - a tuple ``(width, height)``, which is interpreted in inches, i.e. as
2495
+ ``(width, height, "in")``.
2496
+
2497
+ One of *width* or *height* may be ``None``; the respective value is
2498
+ taken from :rc:`figure.figsize`.
2499
+
2500
+ dpi : float, default: :rc:`figure.dpi`
2501
+ Dots per inch.
2502
+
2503
+ facecolor : default: :rc:`figure.facecolor`
2504
+ The figure patch facecolor.
2505
+
2506
+ edgecolor : default: :rc:`figure.edgecolor`
2507
+ The figure patch edge color.
2508
+
2509
+ linewidth : float
2510
+ The linewidth of the frame (i.e. the edge linewidth of the figure
2511
+ patch).
2512
+
2513
+ frameon : bool, default: :rc:`figure.frameon`
2514
+ If ``False``, suppress drawing the figure background patch.
2515
+
2516
+ subplotpars : `~matplotlib.gridspec.SubplotParams`
2517
+ Subplot parameters. If not given, the default subplot
2518
+ parameters :rc:`figure.subplot.*` are used.
2519
+
2520
+ tight_layout : bool or dict, default: :rc:`figure.autolayout`
2521
+ Whether to use the tight layout mechanism. See `.set_tight_layout`.
2522
+
2523
+ .. admonition:: Discouraged
2524
+
2525
+ The use of this parameter is discouraged. Please use
2526
+ ``layout='tight'`` instead for the common case of
2527
+ ``tight_layout=True`` and use `.set_tight_layout` otherwise.
2528
+
2529
+ constrained_layout : bool, default: :rc:`figure.constrained_layout.use`
2530
+ This is equal to ``layout='constrained'``.
2531
+
2532
+ .. admonition:: Discouraged
2533
+
2534
+ The use of this parameter is discouraged. Please use
2535
+ ``layout='constrained'`` instead.
2536
+
2537
+ layout : {'constrained', 'compressed', 'tight', 'none', `.LayoutEngine`, \
2538
+ None}, default: None
2539
+ The layout mechanism for positioning of plot elements to avoid
2540
+ overlapping Axes decorations (labels, ticks, etc). Note that
2541
+ layout managers can have significant performance penalties.
2542
+
2543
+ - 'constrained': The constrained layout solver adjusts Axes sizes
2544
+ to avoid overlapping Axes decorations. Can handle complex plot
2545
+ layouts and colorbars, and is thus recommended.
2546
+
2547
+ See :ref:`constrainedlayout_guide` for examples.
2548
+
2549
+ - 'compressed': uses the same algorithm as 'constrained', but
2550
+ removes extra space between fixed-aspect-ratio Axes. Best for
2551
+ simple grids of Axes.
2552
+
2553
+ - 'tight': Use the tight layout mechanism. This is a relatively
2554
+ simple algorithm that adjusts the subplot parameters so that
2555
+ decorations do not overlap.
2556
+
2557
+ See :ref:`tight_layout_guide` for examples.
2558
+
2559
+ - 'none': Do not use a layout engine.
2560
+
2561
+ - A `.LayoutEngine` instance. Builtin layout classes are
2562
+ `.ConstrainedLayoutEngine` and `.TightLayoutEngine`, more easily
2563
+ accessible by 'constrained' and 'tight'. Passing an instance
2564
+ allows third parties to provide their own layout engine.
2565
+
2566
+ If not given, fall back to using the parameters *tight_layout* and
2567
+ *constrained_layout*, including their config defaults
2568
+ :rc:`figure.autolayout` and :rc:`figure.constrained_layout.use`.
2569
+
2570
+ Other Parameters
2571
+ ----------------
2572
+ **kwargs : `.Figure` properties, optional
2573
+
2574
+ %(Figure:kwdoc)s
2575
+ """
2576
+ super().__init__(**kwargs)
2577
+ self._root_figure = self
2578
+ self._layout_engine = None
2579
+
2580
+ if layout is not None:
2581
+ if (tight_layout is not None):
2582
+ _api.warn_external(
2583
+ "The Figure parameters 'layout' and 'tight_layout' cannot "
2584
+ "be used together. Please use 'layout' only.")
2585
+ if (constrained_layout is not None):
2586
+ _api.warn_external(
2587
+ "The Figure parameters 'layout' and 'constrained_layout' "
2588
+ "cannot be used together. Please use 'layout' only.")
2589
+ self.set_layout_engine(layout=layout)
2590
+ elif tight_layout is not None:
2591
+ if constrained_layout is not None:
2592
+ _api.warn_external(
2593
+ "The Figure parameters 'tight_layout' and "
2594
+ "'constrained_layout' cannot be used together. Please use "
2595
+ "'layout' parameter")
2596
+ self.set_layout_engine(layout='tight')
2597
+ if isinstance(tight_layout, dict):
2598
+ self.get_layout_engine().set(**tight_layout)
2599
+ elif constrained_layout is not None:
2600
+ if isinstance(constrained_layout, dict):
2601
+ self.set_layout_engine(layout='constrained')
2602
+ self.get_layout_engine().set(**constrained_layout)
2603
+ elif constrained_layout:
2604
+ self.set_layout_engine(layout='constrained')
2605
+
2606
+ else:
2607
+ # everything is None, so use default:
2608
+ self.set_layout_engine(layout=layout)
2609
+
2610
+ # Callbacks traditionally associated with the canvas (and exposed with
2611
+ # a proxy property), but that actually need to be on the figure for
2612
+ # pickling.
2613
+ self._canvas_callbacks = cbook.CallbackRegistry(
2614
+ signals=FigureCanvasBase.events)
2615
+ connect = self._canvas_callbacks._connect_picklable
2616
+ self._mouse_key_ids = [
2617
+ connect('key_press_event', backend_bases._key_handler),
2618
+ connect('key_release_event', backend_bases._key_handler),
2619
+ connect('key_release_event', backend_bases._key_handler),
2620
+ connect('button_press_event', backend_bases._mouse_handler),
2621
+ connect('button_release_event', backend_bases._mouse_handler),
2622
+ connect('scroll_event', backend_bases._mouse_handler),
2623
+ connect('motion_notify_event', backend_bases._mouse_handler),
2624
+ ]
2625
+ self._button_pick_id = connect('button_press_event', self.pick)
2626
+ self._scroll_pick_id = connect('scroll_event', self.pick)
2627
+
2628
+ figsize = mpl._val_or_rc(figsize, 'figure.figsize')
2629
+ dpi = mpl._val_or_rc(dpi, 'figure.dpi')
2630
+ facecolor = mpl._val_or_rc(facecolor, 'figure.facecolor')
2631
+ edgecolor = mpl._val_or_rc(edgecolor, 'figure.edgecolor')
2632
+ frameon = mpl._val_or_rc(frameon, 'figure.frameon')
2633
+
2634
+ figsize = _parse_figsize(figsize, dpi)
2635
+
2636
+ if not np.isfinite(figsize).all() or (np.array(figsize) < 0).any():
2637
+ raise ValueError('figure size must be positive finite not '
2638
+ f'{figsize}')
2639
+ self.bbox_inches = Bbox.from_bounds(0, 0, *figsize)
2640
+
2641
+ self.dpi_scale_trans = Affine2D().scale(dpi)
2642
+ # do not use property as it will trigger
2643
+ self._dpi = dpi
2644
+ self.bbox = TransformedBbox(self.bbox_inches, self.dpi_scale_trans)
2645
+ self.figbbox = self.bbox
2646
+ self.transFigure = BboxTransformTo(self.bbox)
2647
+ self.transSubfigure = self.transFigure
2648
+
2649
+ self.patch = Rectangle(
2650
+ xy=(0, 0), width=1, height=1, visible=frameon,
2651
+ facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth,
2652
+ # Don't let the figure patch influence bbox calculation.
2653
+ in_layout=False)
2654
+ self._set_artist_props(self.patch)
2655
+ self.patch.set_antialiased(False)
2656
+
2657
+ self._set_base_canvas()
2658
+
2659
+ if subplotpars is None:
2660
+ subplotpars = SubplotParams()
2661
+
2662
+ self.subplotpars = subplotpars
2663
+
2664
+ self._axstack = _AxesStack() # track all figure Axes and current Axes
2665
+ self.clear()
2666
+
2667
+ def pick(self, mouseevent):
2668
+ if not self.canvas.widgetlock.locked():
2669
+ super().pick(mouseevent)
2670
+
2671
+ def _check_layout_engines_compat(self, old, new):
2672
+ """
2673
+ Helper for set_layout engine
2674
+
2675
+ If the figure has used the old engine and added a colorbar then the
2676
+ value of colorbar_gridspec must be the same on the new engine.
2677
+ """
2678
+ if old is None or new is None:
2679
+ return True
2680
+ if old.colorbar_gridspec == new.colorbar_gridspec:
2681
+ return True
2682
+ # colorbar layout different, so check if any colorbars are on the
2683
+ # figure...
2684
+ for ax in self.axes:
2685
+ if hasattr(ax, '_colorbar'):
2686
+ # colorbars list themselves as a colorbar.
2687
+ return False
2688
+ return True
2689
+
2690
+ def set_layout_engine(self, layout=None, **kwargs):
2691
+ """
2692
+ Set the layout engine for this figure.
2693
+
2694
+ Parameters
2695
+ ----------
2696
+ layout : {'constrained', 'compressed', 'tight', 'none', `.LayoutEngine`, None}
2697
+
2698
+ - 'constrained' will use `~.ConstrainedLayoutEngine`
2699
+ - 'compressed' will also use `~.ConstrainedLayoutEngine`, but with
2700
+ a correction that attempts to make a good layout for fixed-aspect
2701
+ ratio Axes.
2702
+ - 'tight' uses `~.TightLayoutEngine`
2703
+ - 'none' removes layout engine.
2704
+
2705
+ If a `.LayoutEngine` instance, that instance will be used.
2706
+
2707
+ If `None`, the behavior is controlled by :rc:`figure.autolayout`
2708
+ (which if `True` behaves as if 'tight' was passed) and
2709
+ :rc:`figure.constrained_layout.use` (which if `True` behaves as if
2710
+ 'constrained' was passed). If both are `True`,
2711
+ :rc:`figure.autolayout` takes priority.
2712
+
2713
+ Users and libraries can define their own layout engines and pass
2714
+ the instance directly as well.
2715
+
2716
+ **kwargs
2717
+ The keyword arguments are passed to the layout engine to set things
2718
+ like padding and margin sizes. Only used if *layout* is a string.
2719
+
2720
+ """
2721
+ if layout is None:
2722
+ if mpl.rcParams['figure.autolayout']:
2723
+ layout = 'tight'
2724
+ elif mpl.rcParams['figure.constrained_layout.use']:
2725
+ layout = 'constrained'
2726
+ else:
2727
+ self._layout_engine = None
2728
+ return
2729
+ if layout == 'tight':
2730
+ new_layout_engine = TightLayoutEngine(**kwargs)
2731
+ elif layout == 'constrained':
2732
+ new_layout_engine = ConstrainedLayoutEngine(**kwargs)
2733
+ elif layout == 'compressed':
2734
+ new_layout_engine = ConstrainedLayoutEngine(compress=True,
2735
+ **kwargs)
2736
+ elif layout == 'none':
2737
+ if self._layout_engine is not None:
2738
+ new_layout_engine = PlaceHolderLayoutEngine(
2739
+ self._layout_engine.adjust_compatible,
2740
+ self._layout_engine.colorbar_gridspec
2741
+ )
2742
+ else:
2743
+ new_layout_engine = None
2744
+ elif isinstance(layout, LayoutEngine):
2745
+ new_layout_engine = layout
2746
+ else:
2747
+ raise ValueError(f"Invalid value for 'layout': {layout!r}")
2748
+
2749
+ if self._check_layout_engines_compat(self._layout_engine,
2750
+ new_layout_engine):
2751
+ self._layout_engine = new_layout_engine
2752
+ else:
2753
+ raise RuntimeError('Colorbar layout of new layout engine not '
2754
+ 'compatible with old engine, and a colorbar '
2755
+ 'has been created. Engine not changed.')
2756
+
2757
+ def get_layout_engine(self):
2758
+ return self._layout_engine
2759
+
2760
+ # TODO: I'd like to dynamically add the _repr_html_ method
2761
+ # to the figure in the right context, but then IPython doesn't
2762
+ # use it, for some reason.
2763
+
2764
+ def _repr_html_(self):
2765
+ # We can't use "isinstance" here, because then we'd end up importing
2766
+ # webagg unconditionally.
2767
+ if 'WebAgg' in type(self.canvas).__name__:
2768
+ from matplotlib_rs.backends import backend_webagg
2769
+ return backend_webagg.ipython_inline_display(self)
2770
+
2771
+ def show(self, warn=True):
2772
+ """
2773
+ If using a GUI backend with pyplot, display the figure window.
2774
+
2775
+ If the figure was not created using `~.pyplot.figure`, it will lack
2776
+ a `~.backend_bases.FigureManagerBase`, and this method will raise an
2777
+ AttributeError.
2778
+
2779
+ .. warning::
2780
+
2781
+ This does not manage a GUI event loop. Consequently, the figure
2782
+ may only be shown briefly or not shown at all if you or your
2783
+ environment are not managing an event loop.
2784
+
2785
+ Use cases for `.Figure.show` include running this from a GUI
2786
+ application (where there is persistently an event loop running) or
2787
+ from a shell, like IPython, that install an input hook to allow the
2788
+ interactive shell to accept input while the figure is also being
2789
+ shown and interactive. Some, but not all, GUI toolkits will
2790
+ register an input hook on import. See :ref:`cp_integration` for
2791
+ more details.
2792
+
2793
+ If you're in a shell without input hook integration or executing a
2794
+ python script, you should use `matplotlib.pyplot.show` with
2795
+ ``block=True`` instead, which takes care of starting and running
2796
+ the event loop for you.
2797
+
2798
+ Parameters
2799
+ ----------
2800
+ warn : bool, default: True
2801
+ If ``True`` and we are not running headless (i.e. on Linux with an
2802
+ unset DISPLAY), issue warning when called on a non-GUI backend.
2803
+
2804
+ """
2805
+ if self.canvas.manager is None:
2806
+ raise AttributeError(
2807
+ "Figure.show works only for figures managed by pyplot, "
2808
+ "normally created by pyplot.figure()")
2809
+ try:
2810
+ self.canvas.manager.show()
2811
+ except NonGuiException as exc:
2812
+ if warn:
2813
+ _api.warn_external(str(exc))
2814
+
2815
+ @property
2816
+ def axes(self):
2817
+ """
2818
+ List of Axes in the Figure. You can access and modify the Axes in the
2819
+ Figure through this list.
2820
+
2821
+ Do not modify the list itself. Instead, use `~Figure.add_axes`,
2822
+ `~.Figure.add_subplot` or `~.Figure.delaxes` to add or remove an Axes.
2823
+
2824
+ Note: The `.Figure.axes` property and `~.Figure.get_axes` method are
2825
+ equivalent.
2826
+ """
2827
+ return self._axstack.as_list()
2828
+
2829
+ get_axes = axes.fget
2830
+
2831
+ @property
2832
+ def number(self):
2833
+ """The figure id, used to identify figures in `.pyplot`."""
2834
+ # Historically, pyplot dynamically added a number attribute to figure.
2835
+ # However, this number must stay in sync with the figure manager.
2836
+ # AFAICS overwriting the number attribute does not have the desired
2837
+ # effect for pyplot. But there are some repos in GitHub that do change
2838
+ # number. So let's take it slow and properly migrate away from writing.
2839
+ #
2840
+ # Making the dynamic attribute private and wrapping it in a property
2841
+ # allows to maintain current behavior and deprecate write-access.
2842
+ #
2843
+ # When the deprecation expires, there's no need for duplicate state
2844
+ # anymore and the private _number attribute can be replaced by
2845
+ # `self.canvas.manager.num` if that exists and None otherwise.
2846
+ if hasattr(self, '_number'):
2847
+ return self._number
2848
+ else:
2849
+ raise AttributeError(
2850
+ "'Figure' object has no attribute 'number'. In the future this"
2851
+ "will change to returning 'None' instead.")
2852
+
2853
+ @number.setter
2854
+ def number(self, num):
2855
+ _api.warn_deprecated(
2856
+ "3.10",
2857
+ message="Changing 'Figure.number' is deprecated since %(since)s and "
2858
+ "will raise an error starting %(removal)s")
2859
+ self._number = num
2860
+
2861
+ def _get_renderer(self):
2862
+ if hasattr(self.canvas, 'get_renderer'):
2863
+ return self.canvas.get_renderer()
2864
+ else:
2865
+ return _get_renderer(self)
2866
+
2867
+ def _get_dpi(self):
2868
+ return self._dpi
2869
+
2870
+ def _set_dpi(self, dpi, forward=True):
2871
+ """
2872
+ Parameters
2873
+ ----------
2874
+ dpi : float
2875
+
2876
+ forward : bool
2877
+ Passed on to `~.Figure.set_size_inches`
2878
+ """
2879
+ if dpi == self._dpi:
2880
+ # We don't want to cause undue events in backends.
2881
+ return
2882
+ self._dpi = dpi
2883
+ self.dpi_scale_trans.clear().scale(dpi)
2884
+ w, h = self.get_size_inches()
2885
+ self.set_size_inches(w, h, forward=forward)
2886
+
2887
+ dpi = property(_get_dpi, _set_dpi, doc="The resolution in dots per inch.")
2888
+
2889
+ def get_tight_layout(self):
2890
+ """Return whether `.Figure.tight_layout` is called when drawing."""
2891
+ return isinstance(self.get_layout_engine(), TightLayoutEngine)
2892
+
2893
+ @_api.deprecated("3.6", alternative="set_layout_engine",
2894
+ pending=True)
2895
+ def set_tight_layout(self, tight):
2896
+ """
2897
+ Set whether and how `.Figure.tight_layout` is called when drawing.
2898
+
2899
+ Parameters
2900
+ ----------
2901
+ tight : bool or dict with keys "pad", "w_pad", "h_pad", "rect" or None
2902
+ If a bool, sets whether to call `.Figure.tight_layout` upon drawing.
2903
+ If ``None``, use :rc:`figure.autolayout` instead.
2904
+ If a dict, pass it as kwargs to `.Figure.tight_layout`, overriding the
2905
+ default paddings.
2906
+ """
2907
+ tight = mpl._val_or_rc(tight, 'figure.autolayout')
2908
+ _tight = 'tight' if bool(tight) else 'none'
2909
+ _tight_parameters = tight if isinstance(tight, dict) else {}
2910
+ self.set_layout_engine(_tight, **_tight_parameters)
2911
+ self.stale = True
2912
+
2913
+ def get_constrained_layout(self):
2914
+ """
2915
+ Return whether constrained layout is being used.
2916
+
2917
+ See :ref:`constrainedlayout_guide`.
2918
+ """
2919
+ return isinstance(self.get_layout_engine(), ConstrainedLayoutEngine)
2920
+
2921
+ @_api.deprecated("3.6", alternative="set_layout_engine('constrained')",
2922
+ pending=True)
2923
+ def set_constrained_layout(self, constrained):
2924
+ """
2925
+ Set whether ``constrained_layout`` is used upon drawing.
2926
+
2927
+ If None, :rc:`figure.constrained_layout.use` value will be used.
2928
+
2929
+ When providing a dict containing the keys ``w_pad``, ``h_pad``
2930
+ the default ``constrained_layout`` paddings will be
2931
+ overridden. These pads are in inches and default to 3.0/72.0.
2932
+ ``w_pad`` is the width padding and ``h_pad`` is the height padding.
2933
+
2934
+ Parameters
2935
+ ----------
2936
+ constrained : bool or dict or None
2937
+ """
2938
+ constrained = mpl._val_or_rc(constrained, 'figure.constrained_layout.use')
2939
+ _constrained = 'constrained' if bool(constrained) else 'none'
2940
+ _parameters = constrained if isinstance(constrained, dict) else {}
2941
+ self.set_layout_engine(_constrained, **_parameters)
2942
+ self.stale = True
2943
+
2944
+ @_api.deprecated(
2945
+ "3.6", alternative="figure.get_layout_engine().set()",
2946
+ pending=True)
2947
+ def set_constrained_layout_pads(self, **kwargs):
2948
+ """
2949
+ Set padding for ``constrained_layout``.
2950
+
2951
+ Tip: The parameters can be passed from a dictionary by using
2952
+ ``fig.set_constrained_layout(**pad_dict)``.
2953
+
2954
+ See :ref:`constrainedlayout_guide`.
2955
+
2956
+ Parameters
2957
+ ----------
2958
+ w_pad : float, default: :rc:`figure.constrained_layout.w_pad`
2959
+ Width padding in inches. This is the pad around Axes
2960
+ and is meant to make sure there is enough room for fonts to
2961
+ look good. Defaults to 3 pts = 0.04167 inches
2962
+
2963
+ h_pad : float, default: :rc:`figure.constrained_layout.h_pad`
2964
+ Height padding in inches. Defaults to 3 pts.
2965
+
2966
+ wspace : float, default: :rc:`figure.constrained_layout.wspace`
2967
+ Width padding between subplots, expressed as a fraction of the
2968
+ subplot width. The total padding ends up being w_pad + wspace.
2969
+
2970
+ hspace : float, default: :rc:`figure.constrained_layout.hspace`
2971
+ Height padding between subplots, expressed as a fraction of the
2972
+ subplot width. The total padding ends up being h_pad + hspace.
2973
+
2974
+ """
2975
+ if isinstance(self.get_layout_engine(), ConstrainedLayoutEngine):
2976
+ self.get_layout_engine().set(**kwargs)
2977
+
2978
+ @_api.deprecated("3.6", alternative="fig.get_layout_engine().get()",
2979
+ pending=True)
2980
+ def get_constrained_layout_pads(self, relative=False):
2981
+ """
2982
+ Get padding for ``constrained_layout``.
2983
+
2984
+ Returns a list of ``w_pad, h_pad`` in inches and
2985
+ ``wspace`` and ``hspace`` as fractions of the subplot.
2986
+ All values are None if ``constrained_layout`` is not used.
2987
+
2988
+ See :ref:`constrainedlayout_guide`.
2989
+
2990
+ Parameters
2991
+ ----------
2992
+ relative : bool
2993
+ If `True`, then convert from inches to figure relative.
2994
+ """
2995
+ if not isinstance(self.get_layout_engine(), ConstrainedLayoutEngine):
2996
+ return None, None, None, None
2997
+ info = self.get_layout_engine().get()
2998
+ w_pad = info['w_pad']
2999
+ h_pad = info['h_pad']
3000
+ wspace = info['wspace']
3001
+ hspace = info['hspace']
3002
+
3003
+ if relative and (w_pad is not None or h_pad is not None):
3004
+ renderer = self._get_renderer()
3005
+ dpi = renderer.dpi
3006
+ w_pad = w_pad * dpi / renderer.width
3007
+ h_pad = h_pad * dpi / renderer.height
3008
+
3009
+ return w_pad, h_pad, wspace, hspace
3010
+
3011
+ def _set_base_canvas(self):
3012
+ """
3013
+ Initialize self.canvas with a FigureCanvasBase instance.
3014
+
3015
+ This is used upon initialization of the Figure, but also
3016
+ to reset the canvas when decoupling from pyplot.
3017
+ """
3018
+ FigureCanvasBase(self) # Set self.canvas as a side-effect
3019
+ # undo any high-dpi scaling
3020
+ if self._dpi != self._original_dpi:
3021
+ self.dpi = self._original_dpi
3022
+
3023
+ def set_canvas(self, canvas):
3024
+ """
3025
+ Set the canvas that contains the figure
3026
+
3027
+ Parameters
3028
+ ----------
3029
+ canvas : FigureCanvas
3030
+ """
3031
+ self.canvas = canvas
3032
+
3033
+ @_docstring.interpd
3034
+ def figimage(self, X, xo=0, yo=0, alpha=None, norm=None, cmap=None,
3035
+ vmin=None, vmax=None, origin=None, resize=False, *,
3036
+ colorizer=None, **kwargs):
3037
+ """
3038
+ Add a non-resampled image to the figure.
3039
+
3040
+ The image is attached to the lower or upper left corner depending on
3041
+ *origin*.
3042
+
3043
+ Parameters
3044
+ ----------
3045
+ X
3046
+ The image data. This is an array of one of the following shapes:
3047
+
3048
+ - (M, N): an image with scalar data. Color-mapping is controlled
3049
+ by *cmap*, *norm*, *vmin*, and *vmax*.
3050
+ - (M, N, 3): an image with RGB values (0-1 float or 0-255 int).
3051
+ - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int),
3052
+ i.e. including transparency.
3053
+
3054
+ xo, yo : int
3055
+ The *x*/*y* image offset in pixels.
3056
+
3057
+ alpha : None or float
3058
+ The alpha blending value.
3059
+
3060
+ %(cmap_doc)s
3061
+
3062
+ This parameter is ignored if *X* is RGB(A).
3063
+
3064
+ %(norm_doc)s
3065
+
3066
+ This parameter is ignored if *X* is RGB(A).
3067
+
3068
+ %(vmin_vmax_doc)s
3069
+
3070
+ This parameter is ignored if *X* is RGB(A).
3071
+
3072
+ origin : {'upper', 'lower'}, default: :rc:`image.origin`
3073
+ Indicates where the [0, 0] index of the array is in the upper left
3074
+ or lower left corner of the Axes.
3075
+
3076
+ resize : bool
3077
+ If *True*, resize the figure to match the given image size.
3078
+
3079
+ %(colorizer_doc)s
3080
+
3081
+ This parameter is ignored if *X* is RGB(A).
3082
+
3083
+ Returns
3084
+ -------
3085
+ `matplotlib.image.FigureImage`
3086
+
3087
+ Other Parameters
3088
+ ----------------
3089
+ **kwargs
3090
+ Additional kwargs are `.Artist` kwargs passed on to `.FigureImage`.
3091
+
3092
+ Notes
3093
+ -----
3094
+ figimage complements the Axes image (`~matplotlib.axes.Axes.imshow`)
3095
+ which will be resampled to fit the current Axes. If you want
3096
+ a resampled image to fill the entire figure, you can define an
3097
+ `~matplotlib.axes.Axes` with extent [0, 0, 1, 1].
3098
+
3099
+ Examples
3100
+ --------
3101
+ ::
3102
+
3103
+ f = plt.figure()
3104
+ nx = int(f.get_figwidth() * f.dpi)
3105
+ ny = int(f.get_figheight() * f.dpi)
3106
+ data = np.random.random((ny, nx))
3107
+ f.figimage(data)
3108
+ plt.show()
3109
+ """
3110
+ if resize:
3111
+ dpi = self.get_dpi()
3112
+ figsize = [x / dpi for x in (X.shape[1], X.shape[0])]
3113
+ self.set_size_inches(figsize, forward=True)
3114
+
3115
+ im = mimage.FigureImage(self, cmap=cmap, norm=norm,
3116
+ colorizer=colorizer,
3117
+ offsetx=xo, offsety=yo,
3118
+ origin=origin, **kwargs)
3119
+ im.stale_callback = _stale_figure_callback
3120
+
3121
+ im.set_array(X)
3122
+ im.set_alpha(alpha)
3123
+ if norm is None:
3124
+ im._check_exclusionary_keywords(colorizer, vmin=vmin, vmax=vmax)
3125
+ im.set_clim(vmin, vmax)
3126
+ self.images.append(im)
3127
+ im._remove_method = self.images.remove
3128
+ self.stale = True
3129
+ return im
3130
+
3131
+ def set_size_inches(self, w, h=None, forward=True):
3132
+ """
3133
+ Set the figure size in inches.
3134
+
3135
+ Call signatures::
3136
+
3137
+ fig.set_size_inches(w, h) # OR
3138
+ fig.set_size_inches((w, h))
3139
+
3140
+ Parameters
3141
+ ----------
3142
+ w : (float, float) or float
3143
+ Width and height in inches (if height not specified as a separate
3144
+ argument) or width.
3145
+ h : float
3146
+ Height in inches.
3147
+ forward : bool, default: True
3148
+ If ``True``, the canvas size is automatically updated, e.g.,
3149
+ you can resize the figure window from the shell.
3150
+
3151
+ See Also
3152
+ --------
3153
+ matplotlib.figure.Figure.get_size_inches
3154
+ matplotlib.figure.Figure.set_figwidth
3155
+ matplotlib.figure.Figure.set_figheight
3156
+
3157
+ Notes
3158
+ -----
3159
+ To transform from pixels to inches divide by `Figure.dpi`.
3160
+ """
3161
+ if h is None: # Got called with a single pair as argument.
3162
+ w, h = w
3163
+ if w is None or h is None:
3164
+ raise ValueError(
3165
+ "Figure.set_size_inches does not accept None; provide both "
3166
+ "width and height explicitly")
3167
+ size = np.array([w, h])
3168
+ if not np.isfinite(size).all() or (size < 0).any():
3169
+ raise ValueError(f'figure size must be positive finite not {size}')
3170
+ self.bbox_inches.p1 = size
3171
+ if forward:
3172
+ manager = self.canvas.manager
3173
+ if manager is not None:
3174
+ manager.resize(*(size * self.dpi).astype(int))
3175
+ self.stale = True
3176
+
3177
+ def get_size_inches(self):
3178
+ """
3179
+ Return the current size of the figure in inches.
3180
+
3181
+ Returns
3182
+ -------
3183
+ ndarray
3184
+ The size (width, height) of the figure in inches.
3185
+
3186
+ See Also
3187
+ --------
3188
+ matplotlib.figure.Figure.set_size_inches
3189
+ matplotlib.figure.Figure.get_figwidth
3190
+ matplotlib.figure.Figure.get_figheight
3191
+
3192
+ Notes
3193
+ -----
3194
+ The size in pixels can be obtained by multiplying with `Figure.dpi`.
3195
+ """
3196
+ return np.array(self.bbox_inches.p1)
3197
+
3198
+ def get_figwidth(self):
3199
+ """Return the figure width in inches."""
3200
+ return self.bbox_inches.width
3201
+
3202
+ def get_figheight(self):
3203
+ """Return the figure height in inches."""
3204
+ return self.bbox_inches.height
3205
+
3206
+ def get_dpi(self):
3207
+ """Return the resolution in dots per inch as a float."""
3208
+ return self.dpi
3209
+
3210
+ def set_dpi(self, val):
3211
+ """
3212
+ Set the resolution of the figure in dots-per-inch.
3213
+
3214
+ Parameters
3215
+ ----------
3216
+ val : float
3217
+ """
3218
+ self.dpi = val
3219
+ self.stale = True
3220
+
3221
+ def set_figwidth(self, val, forward=True):
3222
+ """
3223
+ Set the width of the figure in inches.
3224
+
3225
+ Parameters
3226
+ ----------
3227
+ val : float
3228
+ forward : bool
3229
+ See `set_size_inches`.
3230
+
3231
+ See Also
3232
+ --------
3233
+ matplotlib.figure.Figure.set_figheight
3234
+ matplotlib.figure.Figure.set_size_inches
3235
+ """
3236
+ self.set_size_inches(val, self.get_figheight(), forward=forward)
3237
+
3238
+ def set_figheight(self, val, forward=True):
3239
+ """
3240
+ Set the height of the figure in inches.
3241
+
3242
+ Parameters
3243
+ ----------
3244
+ val : float
3245
+ forward : bool
3246
+ See `set_size_inches`.
3247
+
3248
+ See Also
3249
+ --------
3250
+ matplotlib.figure.Figure.set_figwidth
3251
+ matplotlib.figure.Figure.set_size_inches
3252
+ """
3253
+ self.set_size_inches(self.get_figwidth(), val, forward=forward)
3254
+
3255
+ def clear(self, keep_observers=False):
3256
+ # docstring inherited
3257
+ super().clear(keep_observers=keep_observers)
3258
+ # FigureBase.clear does not clear toolbars, as
3259
+ # only Figure can have toolbars
3260
+ toolbar = self.canvas.toolbar
3261
+ if toolbar is not None:
3262
+ toolbar.update()
3263
+
3264
+ @_finalize_rasterization
3265
+ @allow_rasterization
3266
+ def draw(self, renderer):
3267
+ # docstring inherited
3268
+ if not self.get_visible():
3269
+ return
3270
+
3271
+ with self._render_lock:
3272
+
3273
+ artists = self._get_draw_artists(renderer)
3274
+ try:
3275
+ renderer.open_group('figure', gid=self.get_gid())
3276
+ if self.axes and self.get_layout_engine() is not None:
3277
+ try:
3278
+ self.get_layout_engine().execute(self)
3279
+ except ValueError:
3280
+ pass
3281
+ # ValueError can occur when resizing a window.
3282
+
3283
+ self.patch.draw(renderer)
3284
+ mimage._draw_list_compositing_images(
3285
+ renderer, self, artists, self.suppressComposite)
3286
+
3287
+ renderer.close_group('figure')
3288
+ finally:
3289
+ self.stale = False
3290
+
3291
+ DrawEvent("draw_event", self.canvas, renderer)._process()
3292
+
3293
+ def draw_without_rendering(self):
3294
+ """
3295
+ Draw the figure with no output. Useful to get the final size of
3296
+ artists that require a draw before their size is known (e.g. text).
3297
+ """
3298
+ renderer = _get_renderer(self)
3299
+ with renderer._draw_disabled():
3300
+ self.draw(renderer)
3301
+
3302
+ def draw_artist(self, a):
3303
+ """
3304
+ Draw `.Artist` *a* only.
3305
+ """
3306
+ a.draw(self.canvas.get_renderer())
3307
+
3308
+ def __getstate__(self):
3309
+ state = super().__getstate__()
3310
+
3311
+ # The canvas cannot currently be pickled, but this has the benefit
3312
+ # of meaning that a figure can be detached from one canvas, and
3313
+ # re-attached to another.
3314
+ state.pop("canvas")
3315
+
3316
+ # discard any changes to the dpi due to pixel ratio changes
3317
+ state["_dpi"] = state.get('_original_dpi', state['_dpi'])
3318
+
3319
+ # add version information to the state
3320
+ state['__mpl_version__'] = mpl.__version__
3321
+
3322
+ # check whether the figure manager (if any) is registered with pyplot
3323
+ from matplotlib_rs import _pylab_helpers
3324
+ if self.canvas.manager in _pylab_helpers.Gcf.figs.values():
3325
+ state['_restore_to_pylab'] = True
3326
+ return state
3327
+
3328
+ def __setstate__(self, state):
3329
+ version = state.pop('__mpl_version__')
3330
+ restore_to_pylab = state.pop('_restore_to_pylab', False)
3331
+
3332
+ if version != mpl.__version__:
3333
+ _api.warn_external(
3334
+ f"This figure was saved with matplotlib version {version} and "
3335
+ f"loaded with {mpl.__version__} so may not function correctly."
3336
+ )
3337
+ self.__dict__ = state
3338
+
3339
+ # re-initialise some of the unstored state information
3340
+ self._set_base_canvas()
3341
+ # force the bounding boxes to respect current dpi
3342
+ self.dpi_scale_trans.clear().scale(self._dpi)
3343
+ if restore_to_pylab:
3344
+ # lazy import to avoid circularity
3345
+ import matplotlib_rs.pyplot as plt
3346
+ import matplotlib_rs._pylab_helpers as pylab_helpers
3347
+ allnums = plt.get_fignums()
3348
+ num = max(allnums) + 1 if allnums else 1
3349
+ backend = plt._get_backend_mod()
3350
+ mgr = backend.new_figure_manager_given_figure(num, self)
3351
+ pylab_helpers.Gcf._set_new_active_manager(mgr)
3352
+ plt.draw_if_interactive()
3353
+
3354
+ self.stale = True
3355
+
3356
+ def add_axobserver(self, func):
3357
+ """Whenever the Axes state change, ``func(self)`` will be called."""
3358
+ # Connect a wrapper lambda and not func itself, to avoid it being
3359
+ # weakref-collected.
3360
+ self._axobservers.connect("_axes_change_event", lambda arg: func(arg))
3361
+
3362
+ def savefig(self, fname, *, transparent=None, **kwargs):
3363
+ """
3364
+ Save the current figure as an image or vector graphic to a file.
3365
+
3366
+ Call signature::
3367
+
3368
+ savefig(fname, *, transparent=None, dpi='figure', format=None,
3369
+ metadata=None, bbox_inches=None, pad_inches=0.1,
3370
+ facecolor='auto', edgecolor='auto', backend=None,
3371
+ **kwargs
3372
+ )
3373
+
3374
+ The available output formats depend on the backend being used.
3375
+
3376
+ Parameters
3377
+ ----------
3378
+ fname : str or path-like or binary file-like
3379
+ A path, or a Python file-like object, or
3380
+ possibly some backend-dependent object such as
3381
+ `matplotlib.backends.backend_pdf.PdfPages`.
3382
+
3383
+ If *format* is set, it determines the output format, and the file
3384
+ is saved as *fname*. Note that *fname* is used verbatim, and there
3385
+ is no attempt to make the extension, if any, of *fname* match
3386
+ *format*, and no extension is appended.
3387
+
3388
+ If *format* is not set, then the format is inferred from the
3389
+ extension of *fname*, if there is one. If *format* is not
3390
+ set and *fname* has no extension, then the file is saved with
3391
+ :rc:`savefig.format` and the appropriate extension is appended to
3392
+ *fname*.
3393
+
3394
+ Other Parameters
3395
+ ----------------
3396
+ transparent : bool, default: :rc:`savefig.transparent`
3397
+ If *True*, the Axes patches will all be transparent; the
3398
+ Figure patch will also be transparent unless *facecolor*
3399
+ and/or *edgecolor* are specified via kwargs.
3400
+
3401
+ If *False* has no effect and the color of the Axes and
3402
+ Figure patches are unchanged (unless the Figure patch
3403
+ is specified via the *facecolor* and/or *edgecolor* keyword
3404
+ arguments in which case those colors are used).
3405
+
3406
+ The transparency of these patches will be restored to their
3407
+ original values upon exit of this function.
3408
+
3409
+ This is useful, for example, for displaying
3410
+ a plot on top of a colored background on a web page.
3411
+
3412
+ dpi : float or 'figure', default: :rc:`savefig.dpi`
3413
+ The resolution in dots per inch. If 'figure', use the figure's
3414
+ dpi value.
3415
+
3416
+ format : str
3417
+ The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when
3418
+ this is unset is documented under *fname*.
3419
+
3420
+ metadata : dict, optional
3421
+ Key/value pairs to store in the image metadata. The supported keys
3422
+ and defaults depend on the image format and backend:
3423
+
3424
+ - 'png' with Agg backend: See the parameter ``metadata`` of
3425
+ `~.FigureCanvasAgg.print_png`.
3426
+ - 'pdf' with pdf backend: See the parameter ``metadata`` of
3427
+ `~.backend_pdf.PdfPages`.
3428
+ - 'svg' with svg backend: See the parameter ``metadata`` of
3429
+ `~.FigureCanvasSVG.print_svg`.
3430
+ - 'eps' and 'ps' with PS backend: Only 'Creator' is supported.
3431
+
3432
+ Not supported for 'pgf', 'raw', and 'rgba' as those formats do not support
3433
+ embedding metadata.
3434
+ Does not currently support 'jpg', 'tiff', or 'webp', but may include
3435
+ embedding EXIF metadata in the future.
3436
+
3437
+ bbox_inches : str or `.Bbox`, default: :rc:`savefig.bbox`
3438
+ Bounding box in inches: only the given portion of the figure is
3439
+ saved. If 'tight', try to figure out the tight bbox of the figure.
3440
+
3441
+ pad_inches : float or 'layout', default: :rc:`savefig.pad_inches`
3442
+ Amount of padding in inches around the figure when bbox_inches is
3443
+ 'tight'. If 'layout' use the padding from the constrained or
3444
+ compressed layout engine; ignored if one of those engines is not in
3445
+ use.
3446
+
3447
+ facecolor : :mpltype:`color` or 'auto', default: :rc:`savefig.facecolor`
3448
+ The facecolor of the figure. If 'auto', use the current figure
3449
+ facecolor.
3450
+
3451
+ edgecolor : :mpltype:`color` or 'auto', default: :rc:`savefig.edgecolor`
3452
+ The edgecolor of the figure. If 'auto', use the current figure
3453
+ edgecolor.
3454
+
3455
+ backend : str, optional
3456
+ Use a non-default backend to render the file, e.g. to render a
3457
+ png file with the "cairo" backend rather than the default "agg",
3458
+ or a pdf file with the "pgf" backend rather than the default
3459
+ "pdf". Note that the default backend is normally sufficient. See
3460
+ :ref:`the-builtin-backends` for a list of valid backends for each
3461
+ file format. Custom backends can be referenced as "module://...".
3462
+
3463
+ orientation : {'landscape', 'portrait'}
3464
+ Currently only supported by the postscript backend.
3465
+
3466
+ papertype : str
3467
+ One of 'letter', 'legal', 'executive', 'ledger', 'a0' through
3468
+ 'a10', 'b0' through 'b10'. Only supported for postscript
3469
+ output.
3470
+
3471
+ bbox_extra_artists : list of `~matplotlib.artist.Artist`, optional
3472
+ A list of extra artists that will be considered when the
3473
+ tight bbox is calculated.
3474
+
3475
+ pil_kwargs : dict, optional
3476
+ Additional keyword arguments that are passed to
3477
+ `PIL.Image.Image.save` when saving the figure.
3478
+
3479
+ """
3480
+
3481
+ kwargs.setdefault('dpi', mpl.rcParams['savefig.dpi'])
3482
+ transparent = mpl._val_or_rc(transparent, 'savefig.transparent')
3483
+
3484
+ with ExitStack() as stack:
3485
+ if transparent:
3486
+ def _recursively_make_subfig_transparent(exit_stack, subfig):
3487
+ exit_stack.enter_context(
3488
+ subfig.patch._cm_set(
3489
+ facecolor="none", edgecolor="none"))
3490
+ for ax in subfig.axes:
3491
+ exit_stack.enter_context(
3492
+ ax.patch._cm_set(
3493
+ facecolor="none", edgecolor="none"))
3494
+ for sub_subfig in subfig.subfigs:
3495
+ _recursively_make_subfig_transparent(
3496
+ exit_stack, sub_subfig)
3497
+
3498
+ def _recursively_make_axes_transparent(exit_stack, ax):
3499
+ exit_stack.enter_context(
3500
+ ax.patch._cm_set(facecolor="none", edgecolor="none"))
3501
+ for child_ax in ax.child_axes:
3502
+ exit_stack.enter_context(
3503
+ child_ax.patch._cm_set(
3504
+ facecolor="none", edgecolor="none"))
3505
+ for child_childax in ax.child_axes:
3506
+ _recursively_make_axes_transparent(
3507
+ exit_stack, child_childax)
3508
+
3509
+ kwargs.setdefault('facecolor', 'none')
3510
+ kwargs.setdefault('edgecolor', 'none')
3511
+ # set subfigure to appear transparent in printed image
3512
+ for subfig in self.subfigs:
3513
+ _recursively_make_subfig_transparent(stack, subfig)
3514
+ # set Axes to be transparent
3515
+ for ax in self.axes:
3516
+ _recursively_make_axes_transparent(stack, ax)
3517
+ self.canvas.print_figure(fname, **kwargs)
3518
+
3519
+ def ginput(self, n=1, timeout=30, show_clicks=True,
3520
+ mouse_add=MouseButton.LEFT,
3521
+ mouse_pop=MouseButton.RIGHT,
3522
+ mouse_stop=MouseButton.MIDDLE):
3523
+ """
3524
+ Blocking call to interact with a figure.
3525
+
3526
+ Wait until the user clicks *n* times on the figure, and return the
3527
+ coordinates of each click in a list.
3528
+
3529
+ There are three possible interactions:
3530
+
3531
+ - Add a point.
3532
+ - Remove the most recently added point.
3533
+ - Stop the interaction and return the points added so far.
3534
+
3535
+ The actions are assigned to mouse buttons via the arguments
3536
+ *mouse_add*, *mouse_pop* and *mouse_stop*.
3537
+
3538
+ Parameters
3539
+ ----------
3540
+ n : int, default: 1
3541
+ Number of mouse clicks to accumulate. If negative, accumulate
3542
+ clicks until the input is terminated manually.
3543
+ timeout : float, default: 30 seconds
3544
+ Number of seconds to wait before timing out. If zero or negative
3545
+ will never time out.
3546
+ show_clicks : bool, default: True
3547
+ If True, show a red cross at the location of each click.
3548
+ mouse_add : `.MouseButton` or None, default: `.MouseButton.LEFT`
3549
+ Mouse button used to add points.
3550
+ mouse_pop : `.MouseButton` or None, default: `.MouseButton.RIGHT`
3551
+ Mouse button used to remove the most recently added point.
3552
+ mouse_stop : `.MouseButton` or None, default: `.MouseButton.MIDDLE`
3553
+ Mouse button used to stop input.
3554
+
3555
+ Returns
3556
+ -------
3557
+ list of tuples
3558
+ A list of the clicked (x, y) coordinates.
3559
+
3560
+ Notes
3561
+ -----
3562
+ The keyboard can also be used to select points in case your mouse
3563
+ does not have one or more of the buttons. The delete and backspace
3564
+ keys act like right-clicking (i.e., remove last point), the enter key
3565
+ terminates input and any other key (not already used by the window
3566
+ manager) selects a point.
3567
+ """
3568
+ clicks = []
3569
+ marks = []
3570
+
3571
+ def handler(event):
3572
+ is_button = event.name == "button_press_event"
3573
+ is_key = event.name == "key_press_event"
3574
+ # Quit (even if not in infinite mode; this is consistent with
3575
+ # MATLAB and sometimes quite useful, but will require the user to
3576
+ # test how many points were actually returned before using data).
3577
+ if (is_button and event.button == mouse_stop
3578
+ or is_key and event.key in ["escape", "enter"]):
3579
+ self.canvas.stop_event_loop()
3580
+ # Pop last click.
3581
+ elif (is_button and event.button == mouse_pop
3582
+ or is_key and event.key in ["backspace", "delete"]):
3583
+ if clicks:
3584
+ clicks.pop()
3585
+ if show_clicks:
3586
+ marks.pop().remove()
3587
+ self.canvas.draw()
3588
+ # Add new click.
3589
+ elif (is_button and event.button == mouse_add
3590
+ # On macOS/gtk, some keys return None.
3591
+ or is_key and event.key is not None):
3592
+ if event.inaxes:
3593
+ clicks.append((event.xdata, event.ydata))
3594
+ _log.info("input %i: %f, %f",
3595
+ len(clicks), event.xdata, event.ydata)
3596
+ if show_clicks:
3597
+ line = mpl.lines.Line2D([event.xdata], [event.ydata],
3598
+ marker="+", color="r")
3599
+ event.inaxes.add_line(line)
3600
+ marks.append(line)
3601
+ self.canvas.draw()
3602
+ if len(clicks) == n and n > 0:
3603
+ self.canvas.stop_event_loop()
3604
+
3605
+ _blocking_input.blocking_input_loop(
3606
+ self, ["button_press_event", "key_press_event"], timeout, handler)
3607
+
3608
+ # Cleanup.
3609
+ for mark in marks:
3610
+ mark.remove()
3611
+ self.canvas.draw()
3612
+
3613
+ return clicks
3614
+
3615
+ def waitforbuttonpress(self, timeout=-1):
3616
+ """
3617
+ Blocking call to interact with the figure.
3618
+
3619
+ Wait for user input and return True if a key was pressed, False if a
3620
+ mouse button was pressed and None if no input was given within
3621
+ *timeout* seconds. Negative values deactivate *timeout*.
3622
+ """
3623
+ event = None
3624
+
3625
+ def handler(ev):
3626
+ nonlocal event
3627
+ event = ev
3628
+ self.canvas.stop_event_loop()
3629
+
3630
+ _blocking_input.blocking_input_loop(
3631
+ self, ["button_press_event", "key_press_event"], timeout, handler)
3632
+
3633
+ return None if event is None else event.name == "key_press_event"
3634
+
3635
+ def tight_layout(self, *, pad=1.08, h_pad=None, w_pad=None, rect=None):
3636
+ """
3637
+ Adjust the padding between and around subplots.
3638
+
3639
+ To exclude an artist on the Axes from the bounding box calculation
3640
+ that determines the subplot parameters (i.e. legend, or annotation),
3641
+ set ``a.set_in_layout(False)`` for that artist.
3642
+
3643
+ Parameters
3644
+ ----------
3645
+ pad : float, default: 1.08
3646
+ Padding between the figure edge and the edges of subplots,
3647
+ as a fraction of the font size.
3648
+ h_pad, w_pad : float, default: *pad*
3649
+ Padding (height/width) between edges of adjacent subplots,
3650
+ as a fraction of the font size.
3651
+ rect : tuple (left, bottom, right, top), default: (0, 0, 1, 1)
3652
+ A rectangle in normalized figure coordinates into which the whole
3653
+ subplots area (including labels) will fit.
3654
+
3655
+ See Also
3656
+ --------
3657
+ .Figure.set_layout_engine
3658
+ .pyplot.tight_layout
3659
+ """
3660
+ # note that here we do not permanently set the figures engine to
3661
+ # tight_layout but rather just perform the layout in place and remove
3662
+ # any previous engines.
3663
+ engine = TightLayoutEngine(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
3664
+ try:
3665
+ previous_engine = self.get_layout_engine()
3666
+ self.set_layout_engine(engine)
3667
+ engine.execute(self)
3668
+ if previous_engine is not None and not isinstance(
3669
+ previous_engine, (TightLayoutEngine, PlaceHolderLayoutEngine)
3670
+ ):
3671
+ _api.warn_external('The figure layout has changed to tight')
3672
+ finally:
3673
+ self.set_layout_engine('none')
3674
+
3675
+
3676
+ def figaspect(arg):
3677
+ """
3678
+ Calculate the width and height for a figure with a specified aspect ratio.
3679
+
3680
+ While the height is taken from :rc:`figure.figsize`, the width is
3681
+ adjusted to match the desired aspect ratio. Additionally, it is ensured
3682
+ that the width is in the range [4., 16.] and the height is in the range
3683
+ [2., 16.]. If necessary, the default height is adjusted to ensure this.
3684
+
3685
+ Parameters
3686
+ ----------
3687
+ arg : float or 2D array
3688
+ If a float, this defines the aspect ratio (i.e. the ratio height /
3689
+ width).
3690
+ In case of an array the aspect ratio is number of rows / number of
3691
+ columns, so that the array could be fitted in the figure undistorted.
3692
+
3693
+ Returns
3694
+ -------
3695
+ size : (2,) array
3696
+ The width and height of the figure in inches.
3697
+
3698
+ Notes
3699
+ -----
3700
+ If you want to create an Axes within the figure, that still preserves the
3701
+ aspect ratio, be sure to create it with equal width and height. See
3702
+ examples below.
3703
+
3704
+ Thanks to Fernando Perez for this function.
3705
+
3706
+ Examples
3707
+ --------
3708
+ Make a figure twice as tall as it is wide::
3709
+
3710
+ w, h = figaspect(2.)
3711
+ fig = Figure(figsize=(w, h))
3712
+ ax = fig.add_axes((0.1, 0.1, 0.8, 0.8))
3713
+ ax.imshow(A, **kwargs)
3714
+
3715
+ Make a figure with the proper aspect for an array::
3716
+
3717
+ A = rand(5, 3)
3718
+ w, h = figaspect(A)
3719
+ fig = Figure(figsize=(w, h))
3720
+ ax = fig.add_axes((0.1, 0.1, 0.8, 0.8))
3721
+ ax.imshow(A, **kwargs)
3722
+ """
3723
+
3724
+ isarray = hasattr(arg, 'shape') and not np.isscalar(arg)
3725
+
3726
+ # min/max sizes to respect when autoscaling. If John likes the idea, they
3727
+ # could become rc parameters, for now they're hardwired.
3728
+ figsize_min = np.array((4.0, 2.0)) # min length for width/height
3729
+ figsize_max = np.array((16.0, 16.0)) # max length for width/height
3730
+
3731
+ # Extract the aspect ratio of the array
3732
+ if isarray:
3733
+ nr, nc = arg.shape[:2]
3734
+ arr_ratio = nr / nc
3735
+ else:
3736
+ arr_ratio = arg
3737
+
3738
+ # Height of user figure defaults
3739
+ fig_height = mpl.rcParams['figure.figsize'][1]
3740
+
3741
+ # New size for the figure, keeping the aspect ratio of the caller
3742
+ newsize = np.array((fig_height / arr_ratio, fig_height))
3743
+
3744
+ # Sanity checks, don't drop either dimension below figsize_min
3745
+ newsize /= min(1.0, *(newsize / figsize_min))
3746
+
3747
+ # Avoid humongous windows as well
3748
+ newsize /= max(1.0, *(newsize / figsize_max))
3749
+
3750
+ # Finally, if we have a really funky aspect ratio, break it but respect
3751
+ # the min/max dimensions (we don't want figures 10 feet tall!)
3752
+ newsize = np.clip(newsize, figsize_min, figsize_max)
3753
+ return newsize
3754
+
3755
+
3756
+ def _parse_figsize(figsize, dpi):
3757
+ """
3758
+ Convert a figsize expression to (width, height) in inches.
3759
+
3760
+ Parameters
3761
+ ----------
3762
+ figsize : (float, float) or (float, float, str)
3763
+ This can be
3764
+
3765
+ - a tuple ``(width, height, unit)``, where *unit* is one of "in" (inch),
3766
+ "cm" (centimenter), "px" (pixel).
3767
+ - a tuple ``(width, height)``, which is interpreted in inches, i.e. as
3768
+ ``(width, height, "in")``.
3769
+
3770
+ dpi : float
3771
+ The dots-per-inch; used for converting 'px' to 'in'.
3772
+ """
3773
+ num_parts = len(figsize)
3774
+ if num_parts == 2:
3775
+ x, y = figsize
3776
+ elif num_parts == 3:
3777
+ x, y, unit = figsize
3778
+ if unit == 'in':
3779
+ pass
3780
+ elif unit == 'cm':
3781
+ if x is not None:
3782
+ x /= 2.54
3783
+ if y is not None:
3784
+ y /= 2.54
3785
+ elif unit == 'px':
3786
+ if x is not None:
3787
+ x /= dpi
3788
+ if y is not None:
3789
+ y /= dpi
3790
+ else:
3791
+ raise ValueError(
3792
+ f"Invalid unit {unit!r} in 'figsize'; "
3793
+ "supported units are 'in', 'cm', 'px'"
3794
+ )
3795
+ else:
3796
+ raise ValueError(
3797
+ "Invalid figsize format, expected (x, y) or (x, y, unit) but got "
3798
+ f"{figsize!r}"
3799
+ )
3800
+
3801
+ if x is None and y is None:
3802
+ raise ValueError(
3803
+ "figsize=(None, None) is invalid; at least one of width or "
3804
+ "height must be provided")
3805
+
3806
+ default_width, default_height = mpl.rcParams["figure.figsize"]
3807
+ if x is None:
3808
+ x = default_width
3809
+ if y is None:
3810
+ y = default_height
3811
+ return x, y
3812
+
3813
+
3814
+ from ._figure_rs import _patch_figure # noqa: E402
3815
+ _patch_figure(FigureBase, Figure, SubFigure)