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,1683 @@
1
+ # Vendored from matplotlib 3.11 (see licenses/LICENSE_MATPLOTLIB), adapted for matplotlib_rs.
2
+ """
3
+ An object-oriented plotting library.
4
+
5
+ A procedural interface is provided by the companion pyplot module,
6
+ which may be imported directly, e.g.::
7
+
8
+ import matplotlib_rs.pyplot as plt
9
+
10
+ or using ipython::
11
+
12
+ ipython
13
+
14
+ at your terminal, followed by::
15
+
16
+ In [1]: %matplotlib
17
+ In [2]: import matplotlib.pyplot as plt
18
+
19
+ at the ipython shell prompt.
20
+
21
+ For the most part, direct use of the explicit object-oriented library is
22
+ encouraged when programming; the implicit pyplot interface is primarily for
23
+ working interactively. The exceptions to this suggestion are the pyplot
24
+ functions `.pyplot.figure`, `.pyplot.subplot`, `.pyplot.subplots`, and
25
+ `.pyplot.savefig`, which can greatly simplify scripting. See
26
+ :ref:`api_interfaces` for an explanation of the tradeoffs between the implicit
27
+ and explicit interfaces.
28
+
29
+ Modules include:
30
+
31
+ :mod:`matplotlib.axes`
32
+ The `~.axes.Axes` class. Most pyplot functions are wrappers for
33
+ `~.axes.Axes` methods. The axes module is the highest level of OO
34
+ access to the library.
35
+
36
+ :mod:`matplotlib.figure`
37
+ The `.Figure` class.
38
+
39
+ :mod:`matplotlib.artist`
40
+ The `.Artist` base class for all classes that draw things.
41
+
42
+ :mod:`matplotlib.lines`
43
+ The `.Line2D` class for drawing lines and markers.
44
+
45
+ :mod:`matplotlib.patches`
46
+ Classes for drawing polygons.
47
+
48
+ :mod:`matplotlib.text`
49
+ The `.Text` and `.Annotation` classes.
50
+
51
+ :mod:`matplotlib.image`
52
+ The `.AxesImage` and `.FigureImage` classes.
53
+
54
+ :mod:`matplotlib.collections`
55
+ Classes for efficient drawing of groups of lines or polygons.
56
+
57
+ :mod:`matplotlib.colors`
58
+ Color specifications and making colormaps.
59
+
60
+ :mod:`matplotlib.cm`
61
+ Colormaps, and the `.ScalarMappable` mixin class for providing color
62
+ mapping functionality to other classes.
63
+
64
+ :mod:`matplotlib.ticker`
65
+ Calculation of tick mark locations and formatting of tick labels.
66
+
67
+ :mod:`matplotlib.backends`
68
+ A subpackage with modules for various GUI libraries and output formats.
69
+
70
+ The base matplotlib namespace includes:
71
+
72
+ `~matplotlib.rcParams`
73
+ Default configuration settings; their defaults may be overridden using
74
+ a :file:`matplotlibrc` file.
75
+
76
+ `~matplotlib.use`
77
+ Setting the Matplotlib backend. This should be called before any
78
+ figure is created, because it is not possible to switch between
79
+ different GUI backends after that.
80
+
81
+ The following environment variables can be used to customize the behavior:
82
+
83
+ :envvar:`MPLBACKEND`
84
+ This optional variable can be set to choose the Matplotlib backend. See
85
+ :ref:`what-is-a-backend`.
86
+
87
+ :envvar:`MPLCONFIGDIR`
88
+ This is the directory used to store user customizations to
89
+ Matplotlib, as well as some caches to improve performance. If
90
+ :envvar:`MPLCONFIGDIR` is not defined, :file:`{HOME}/.config/matplotlib`
91
+ and :file:`{HOME}/.cache/matplotlib` are used on Linux, and
92
+ :file:`{HOME}/.matplotlib` on other platforms, if they are
93
+ writable. Otherwise, the Python standard library's `tempfile.gettempdir`
94
+ is used to find a base directory in which the :file:`matplotlib`
95
+ subdirectory is created.
96
+
97
+ Matplotlib was initially written by John D. Hunter (1968-2012) and is now
98
+ developed and maintained by a host of others.
99
+
100
+ Occasionally the internal documentation (python docstrings) will refer
101
+ to MATLAB®, a registered trademark of The MathWorks, Inc.
102
+
103
+ """
104
+
105
+ __all__ = [
106
+ "__bibtex__",
107
+ "__version__",
108
+ "__version_info__",
109
+ "set_loglevel",
110
+ "ExecutableNotFoundError",
111
+ "get_configdir",
112
+ "get_cachedir",
113
+ "get_data_path",
114
+ "matplotlib_fname",
115
+ "MatplotlibDeprecationWarning",
116
+ "RcParams",
117
+ "rc_params",
118
+ "rc_params_from_file",
119
+ "rcParamsDefault",
120
+ "rcParams",
121
+ "rcParamsOrig",
122
+ "defaultParams",
123
+ "rc",
124
+ "rcdefaults",
125
+ "rc_file_defaults",
126
+ "rc_file",
127
+ "rc_context",
128
+ "use",
129
+ "get_backend",
130
+ "interactive",
131
+ "is_interactive",
132
+ "colormaps",
133
+ "multivar_colormaps",
134
+ "bivar_colormaps",
135
+ "color_sequences",
136
+ ]
137
+
138
+
139
+ import atexit
140
+ from collections import namedtuple
141
+ from collections.abc import MutableMapping
142
+ import contextlib
143
+ import functools
144
+ import importlib
145
+ import inspect
146
+ from inspect import Parameter
147
+ import locale
148
+ import logging
149
+ import os
150
+ from pathlib import Path
151
+ import pprint
152
+ import re
153
+ import shutil
154
+ import subprocess
155
+ import sys
156
+ import tempfile
157
+
158
+ try:
159
+ from packaging.version import parse as parse_version
160
+ except ImportError: # pragma: no cover
161
+ def parse_version(s):
162
+ class _V:
163
+ pass
164
+ v = _V()
165
+ parts = [int(p) for p in re.findall(r'\d+', s)[:3]] + [0, 0, 0]
166
+ v.major, v.minor, v.micro = parts[:3]
167
+ v.release = tuple(parts[:3])
168
+ v.pre = v.post = v.dev = None
169
+ return v
170
+
171
+ # cbook must import matplotlib only within function
172
+ # definitions, so it is safe to import from it here.
173
+ from . import _api, cbook, rcsetup
174
+ from . import _mplrs
175
+ from ._api import MatplotlibDeprecationWarning
176
+ from .colors import _color_sequences as color_sequences
177
+ from .rcsetup import cycler # noqa: F401
178
+
179
+
180
+ _log = logging.getLogger(__name__)
181
+
182
+ __bibtex__ = r"""@Article{Hunter:2007,
183
+ Author = {Hunter, J. D.},
184
+ Title = {Matplotlib: A 2D graphics environment},
185
+ Journal = {Computing in Science \& Engineering},
186
+ Volume = {9},
187
+ Number = {3},
188
+ Pages = {90--95},
189
+ abstract = {Matplotlib is a 2D graphics package used for Python
190
+ for application development, interactive scripting, and
191
+ publication-quality image generation across user
192
+ interfaces and operating systems.},
193
+ publisher = {IEEE COMPUTER SOC},
194
+ year = 2007
195
+ }"""
196
+
197
+ # modelled after sys.version_info
198
+ _VersionInfo = namedtuple('_VersionInfo',
199
+ 'major, minor, micro, releaselevel, serial')
200
+
201
+
202
+ def _parse_to_version_info(version_str):
203
+ """
204
+ Parse a version string to a namedtuple analogous to sys.version_info.
205
+
206
+ See:
207
+ https://packaging.pypa.io/en/latest/version.html#packaging.version.parse
208
+ https://docs.python.org/3/library/sys.html#sys.version_info
209
+ """
210
+ v = parse_version(version_str)
211
+ if v.pre is None and v.post is None and v.dev is None:
212
+ return _VersionInfo(v.major, v.minor, v.micro, 'final', 0)
213
+ elif v.dev is not None:
214
+ return _VersionInfo(v.major, v.minor, v.micro, 'alpha', v.dev)
215
+ elif v.pre is not None:
216
+ releaselevel = {
217
+ 'a': 'alpha',
218
+ 'b': 'beta',
219
+ 'rc': 'candidate'}.get(v.pre[0], 'alpha')
220
+ return _VersionInfo(v.major, v.minor, v.micro, releaselevel, v.pre[1])
221
+ else:
222
+ # fallback for v.post: guess-next-dev scheme from setuptools_scm
223
+ return _VersionInfo(v.major, v.minor, v.micro + 1, 'alpha', v.post)
224
+
225
+
226
+ def _get_version():
227
+ """Return the version string used for __version__."""
228
+ return "3.11.2"
229
+
230
+
231
+
232
+ @_api.caching_module_getattr
233
+ class __getattr__:
234
+ __version__ = property(lambda self: _get_version())
235
+ __version_info__ = property(
236
+ lambda self: _parse_to_version_info(self.__version__))
237
+
238
+
239
+ def _check_versions():
240
+
241
+ # Quickfix to ensure Microsoft Visual C++ redistributable
242
+ # DLLs are loaded before importing kiwisolver
243
+ from . import ft2font # noqa: F401
244
+
245
+ for modname, minver in [
246
+ ("cycler", "0.10"),
247
+ ("dateutil", "2.7"),
248
+ ("kiwisolver", "1.3.1"),
249
+ ("numpy", "1.25"),
250
+ ("pyparsing", "2.3.1"),
251
+ ]:
252
+ module = importlib.import_module(modname)
253
+ if parse_version(module.__version__) < parse_version(minver):
254
+ raise ImportError(f"Matplotlib requires {modname}>={minver}; "
255
+ f"you have {module.__version__}")
256
+
257
+
258
+ # version checks are not needed for matplotlib_rs
259
+
260
+
261
+ # The decorator ensures this always returns the same handler (and it is only
262
+ # attached once).
263
+ @functools.cache
264
+ def _ensure_handler():
265
+ """
266
+ The first time this function is called, attach a `StreamHandler` using the
267
+ same format as `logging.basicConfig` to the Matplotlib root logger.
268
+
269
+ Return this handler every time this function is called.
270
+ """
271
+ handler = logging.StreamHandler()
272
+ handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
273
+ _log.addHandler(handler)
274
+ return handler
275
+
276
+
277
+ def set_loglevel(level):
278
+ """
279
+ Configure Matplotlib's logging levels.
280
+
281
+ Matplotlib uses the standard library `logging` framework under the root
282
+ logger 'matplotlib'. This is a helper function to:
283
+
284
+ - set Matplotlib's root logger level
285
+ - set the root logger handler's level, creating the handler
286
+ if it does not exist yet
287
+
288
+ Typically, one should call ``set_loglevel("INFO")`` or
289
+ ``set_loglevel("DEBUG")`` to get additional debugging information.
290
+
291
+ Users or applications that are installing their own logging handlers
292
+ may want to directly manipulate ``logging.getLogger('matplotlib')`` rather
293
+ than use this function.
294
+
295
+ Parameters
296
+ ----------
297
+ level : {"NOTSET", "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"}
298
+ The log level as defined in `Python logging levels
299
+ <https://docs.python.org/3/library/logging.html#logging-levels>`__.
300
+
301
+ For backwards compatibility, the levels are case-insensitive, but
302
+ the capitalized version is preferred in analogy to `logging.Logger.setLevel`.
303
+
304
+ Notes
305
+ -----
306
+ The first time this function is called, an additional handler is attached
307
+ to Matplotlib's root handler; this handler is reused every time and this
308
+ function simply manipulates the logger and handler's level.
309
+
310
+ """
311
+ _log.setLevel(level.upper())
312
+ _ensure_handler().setLevel(level.upper())
313
+
314
+
315
+ def _logged_cached(fmt, func=None):
316
+ """
317
+ Decorator that logs a function's return value, and memoizes that value.
318
+
319
+ After ::
320
+
321
+ @_logged_cached(fmt)
322
+ def func(): ...
323
+
324
+ the first call to *func* will log its return value at the DEBUG level using
325
+ %-format string *fmt*, and memoize it; later calls to *func* will directly
326
+ return that value.
327
+ """
328
+ if func is None: # Return the actual decorator.
329
+ return functools.partial(_logged_cached, fmt)
330
+
331
+ called = False
332
+ ret = None
333
+
334
+ @functools.wraps(func)
335
+ def wrapper(**kwargs):
336
+ nonlocal called, ret
337
+ if not called:
338
+ ret = func(**kwargs)
339
+ called = True
340
+ _log.debug(fmt, ret)
341
+ return ret
342
+
343
+ return wrapper
344
+
345
+
346
+ _ExecInfo = namedtuple("_ExecInfo", "executable raw_version version")
347
+
348
+
349
+ class ExecutableNotFoundError(FileNotFoundError):
350
+ """
351
+ Error raised when an executable that Matplotlib optionally
352
+ depends on can't be found.
353
+ """
354
+ pass
355
+
356
+
357
+ @functools.cache
358
+ def _get_executable_info(name):
359
+ """
360
+ Get the version of some executable that Matplotlib optionally depends on.
361
+
362
+ .. warning::
363
+ The list of executables that this function supports is set according to
364
+ Matplotlib's internal needs, and may change without notice.
365
+
366
+ Parameters
367
+ ----------
368
+ name : str
369
+ The executable to query. The following values are currently supported:
370
+ "dvipng", "gs", "inkscape", "magick", "pdftocairo", "pdftops". This
371
+ list is subject to change without notice.
372
+
373
+ Returns
374
+ -------
375
+ tuple
376
+ A namedtuple with fields ``executable`` (`str`) and ``version``
377
+ (`packaging.Version`, or ``None`` if the version cannot be determined).
378
+
379
+ Raises
380
+ ------
381
+ ExecutableNotFoundError
382
+ If the executable is not found or older than the oldest version
383
+ supported by Matplotlib. For debugging purposes, it is also
384
+ possible to "hide" an executable from Matplotlib by adding it to the
385
+ :envvar:`_MPLHIDEEXECUTABLES` environment variable (a comma-separated
386
+ list), which must be set prior to any calls to this function.
387
+ ValueError
388
+ If the executable is not one that we know how to query.
389
+ """
390
+
391
+ def impl(args, regex, min_ver=None, ignore_exit_code=False):
392
+ # Execute the subprocess specified by args; capture stdout and stderr.
393
+ # Search for a regex match in the output; if the match succeeds, the
394
+ # first group of the match is the version.
395
+ # Return an _ExecInfo if the executable exists, and has a version of
396
+ # at least min_ver (if set); else, raise ExecutableNotFoundError.
397
+ try:
398
+ output = subprocess.check_output(
399
+ args, stderr=subprocess.STDOUT,
400
+ text=True, errors="replace", timeout=30)
401
+ except subprocess.CalledProcessError as _cpe:
402
+ if ignore_exit_code:
403
+ output = _cpe.output
404
+ else:
405
+ raise ExecutableNotFoundError(str(_cpe)) from _cpe
406
+ except subprocess.TimeoutExpired as _te:
407
+ msg = f"Timed out running {cbook._pformat_subprocess(args)}"
408
+ raise ExecutableNotFoundError(msg) from _te
409
+ except OSError as _ose:
410
+ raise ExecutableNotFoundError(str(_ose)) from _ose
411
+ match = re.search(regex, output)
412
+ if match:
413
+ raw_version = match.group(1)
414
+ version = parse_version(raw_version)
415
+ if min_ver is not None and version < parse_version(min_ver):
416
+ raise ExecutableNotFoundError(
417
+ f"You have {args[0]} version {version} but the minimum "
418
+ f"version supported by Matplotlib is {min_ver}")
419
+ return _ExecInfo(args[0], raw_version, version)
420
+ else:
421
+ raise ExecutableNotFoundError(
422
+ f"Failed to determine the version of {args[0]} from "
423
+ f"{' '.join(args)}, which output {output}")
424
+
425
+ if name in os.environ.get("_MPLHIDEEXECUTABLES", "").split(","):
426
+ raise ExecutableNotFoundError(f"{name} was hidden")
427
+
428
+ if name == "dvipng":
429
+ return impl(["dvipng", "-version"], "(?m)^dvipng(?: .*)? (.+)", "1.6")
430
+ elif name == "gs":
431
+ execs = (["gswin32c", "gswin64c", "mgs", "gs"] # "mgs" for miktex.
432
+ if sys.platform == "win32" else
433
+ ["gs"])
434
+ for e in execs:
435
+ try:
436
+ return impl([e, "--version"], "(.*)", "9")
437
+ except ExecutableNotFoundError:
438
+ pass
439
+ message = "Failed to find a Ghostscript installation"
440
+ raise ExecutableNotFoundError(message)
441
+ elif name == "inkscape":
442
+ try:
443
+ # Try headless option first (needed for Inkscape version < 1.0):
444
+ return impl(["inkscape", "--without-gui", "-V"],
445
+ "Inkscape ([^ ]*)")
446
+ except ExecutableNotFoundError:
447
+ pass # Suppress exception chaining.
448
+ # If --without-gui is not accepted, we may be using Inkscape >= 1.0 so
449
+ # try without it:
450
+ return impl(["inkscape", "-V"], "Inkscape ([^ ]*)")
451
+ elif name == "magick":
452
+ if sys.platform == "win32":
453
+ # Check the registry to avoid confusing ImageMagick's convert with
454
+ # Windows's builtin convert.exe.
455
+ import winreg
456
+ binpath = ""
457
+ for flag in [0, winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY]:
458
+ try:
459
+ with winreg.OpenKeyEx(
460
+ winreg.HKEY_LOCAL_MACHINE,
461
+ r"Software\Imagemagick\Current",
462
+ 0, winreg.KEY_QUERY_VALUE | flag) as hkey:
463
+ binpath = winreg.QueryValueEx(hkey, "BinPath")[0]
464
+ except OSError:
465
+ pass
466
+ path = None
467
+ if binpath:
468
+ for name in ["convert.exe", "magick.exe"]:
469
+ candidate = Path(binpath, name)
470
+ if candidate.exists():
471
+ path = str(candidate)
472
+ break
473
+ if path is None:
474
+ raise ExecutableNotFoundError(
475
+ "Failed to find an ImageMagick installation")
476
+ else:
477
+ path = "convert"
478
+ # Ignore deprecation warning for "convert" on IM>=7.1.1-33.
479
+ info = impl([path, "--version"], r"(?sm:.*^)Version: ImageMagick (\S*)")
480
+ if info.raw_version == "7.0.10-34":
481
+ # https://github.com/ImageMagick/ImageMagick/issues/2720
482
+ raise ExecutableNotFoundError(
483
+ f"You have ImageMagick {info.version}, which is unsupported")
484
+ return info
485
+ elif name == "pdftocairo":
486
+ return impl(["pdftocairo", "-v"], "pdftocairo version (.*)")
487
+ elif name == "pdftops":
488
+ info = impl(["pdftops", "-v"], "^pdftops version (.*)",
489
+ ignore_exit_code=True)
490
+ if info and not (
491
+ 3 <= info.version.major or
492
+ # poppler version numbers.
493
+ parse_version("0.9") <= info.version < parse_version("1.0")):
494
+ raise ExecutableNotFoundError(
495
+ f"You have pdftops version {info.version} but the minimum "
496
+ f"version supported by Matplotlib is 3.0")
497
+ return info
498
+ else:
499
+ raise ValueError(f"Unknown executable: {name!r}")
500
+
501
+
502
+ def _get_xdg_config_dir():
503
+ """
504
+ Return the XDG configuration directory, according to the XDG base
505
+ directory spec:
506
+
507
+ https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
508
+ """
509
+ return os.environ.get('XDG_CONFIG_HOME') or str(Path.home() / ".config")
510
+
511
+
512
+ def _get_xdg_cache_dir():
513
+ """
514
+ Return the XDG cache directory, according to the XDG base directory spec:
515
+
516
+ https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
517
+ """
518
+ return os.environ.get('XDG_CACHE_HOME') or str(Path.home() / ".cache")
519
+
520
+
521
+ def _get_config_or_cache_dir(xdg_base_getter):
522
+ configdir = os.environ.get('MPLCONFIGDIR')
523
+ if configdir:
524
+ configdir = Path(configdir)
525
+ elif sys.platform.startswith(('linux', 'freebsd')):
526
+ # Only call _xdg_base_getter here so that MPLCONFIGDIR is tried first,
527
+ # as _xdg_base_getter can throw.
528
+ try:
529
+ configdir = Path(xdg_base_getter(), "matplotlib")
530
+ except RuntimeError: # raised if Path.home() is not available
531
+ pass
532
+ elif sys.platform == 'win32':
533
+ # On Windows, prefer %LOCALAPPDATA%\matplotlib which is the proper
534
+ # location for non-roaming application data (cache and config).
535
+ # See: https://docs.microsoft.com/en-us/windows/apps/design/app-settings/store-and-retrieve-app-data
536
+ #
537
+ # However, for backwards compatibility, if the old location
538
+ # (%USERPROFILE%\.matplotlib) exists, continue using it so existing
539
+ # users don't lose their config.
540
+ try:
541
+ old_configdir = Path.home() / ".matplotlib"
542
+ if old_configdir.is_dir():
543
+ configdir = old_configdir
544
+ else:
545
+ localappdata = os.environ.get('LOCALAPPDATA')
546
+ if localappdata:
547
+ configdir = Path(localappdata) / "matplotlib"
548
+ else:
549
+ configdir = old_configdir
550
+ except RuntimeError: # raised if Path.home() is not available
551
+ localappdata = os.environ.get('LOCALAPPDATA')
552
+ if localappdata:
553
+ configdir = Path(localappdata) / "matplotlib"
554
+ else:
555
+ try:
556
+ configdir = Path.home() / ".matplotlib"
557
+ except RuntimeError: # raised if Path.home() is not available
558
+ pass
559
+
560
+ if configdir:
561
+ # Resolve the path to handle potential issues with inaccessible symlinks.
562
+ configdir = configdir.resolve()
563
+ try:
564
+ configdir.mkdir(parents=True, exist_ok=True)
565
+ except OSError as exc:
566
+ _log.warning("mkdir -p failed for path %s: %s", configdir, exc)
567
+ else:
568
+ if os.access(str(configdir), os.W_OK) and configdir.is_dir():
569
+ return str(configdir)
570
+ _log.warning("%s is not a writable directory", configdir)
571
+ if os.environ.get('MPLCONFIGDIR'):
572
+ issue_msg = f"MPLCONFIGDIR ({configdir})"
573
+ else:
574
+ issue_msg = f"the default path ({configdir})"
575
+ else:
576
+ issue_msg = "resolving the home directory"
577
+ # If the config or cache directory cannot be created or is not a writable
578
+ # directory, create a temporary one.
579
+ try:
580
+ tmpdir = tempfile.mkdtemp(prefix="matplotlib-")
581
+ except OSError as exc:
582
+ raise OSError(
583
+ f"Matplotlib requires access to a writable cache directory, but there "
584
+ f"was an issue with {issue_msg}, and a temporary "
585
+ f"directory could not be created; set the MPLCONFIGDIR environment "
586
+ f"variable to a writable directory") from exc
587
+ os.environ["MPLCONFIGDIR"] = tmpdir
588
+ atexit.register(shutil.rmtree, tmpdir)
589
+ _log.warning(
590
+ "Matplotlib created a temporary cache directory at %s because there was "
591
+ "an issue with %s; it is highly recommended to set the "
592
+ "MPLCONFIGDIR environment variable to a writable directory, in particular to "
593
+ "speed up the import of Matplotlib and to better support multiprocessing.",
594
+ tmpdir, issue_msg)
595
+ return tmpdir
596
+
597
+
598
+ @_logged_cached('CONFIGDIR=%s')
599
+ def get_configdir():
600
+ """
601
+ Return the string path of the configuration directory.
602
+
603
+ The directory is chosen as follows:
604
+
605
+ 1. If the MPLCONFIGDIR environment variable is supplied, choose that.
606
+ 2. On Linux, follow the XDG specification and look first in
607
+ ``$XDG_CONFIG_HOME``, if defined, or ``$HOME/.config``. On Windows,
608
+ use ``%LOCALAPPDATA%\\matplotlib``. On other platforms, choose
609
+ ``$HOME/.matplotlib``.
610
+ 3. If the chosen directory exists and is writable, use that as the
611
+ configuration directory.
612
+ 4. Else, create a temporary directory, and use it as the configuration
613
+ directory.
614
+ """
615
+ return _get_config_or_cache_dir(_get_xdg_config_dir)
616
+
617
+
618
+ @_logged_cached('CACHEDIR=%s')
619
+ def get_cachedir():
620
+ """
621
+ Return the string path of the cache directory.
622
+
623
+ The procedure used to find the directory is the same as for
624
+ `get_configdir`, except using ``$XDG_CACHE_HOME``/``$HOME/.cache`` instead
625
+ on Linux. On Windows, uses ``%LOCALAPPDATA%\\matplotlib`` (same as config).
626
+ """
627
+ return _get_config_or_cache_dir(_get_xdg_cache_dir)
628
+
629
+
630
+ @_logged_cached('matplotlib data path: %s')
631
+ def get_data_path():
632
+ """Return the path to Matplotlib data."""
633
+ return str(Path(__file__).with_name("mpl-data"))
634
+
635
+
636
+ def matplotlib_fname():
637
+ """
638
+ Get the location of the config file.
639
+
640
+ The file location is determined in the following order
641
+
642
+ - ``$PWD/matplotlibrc``
643
+ - ``$MATPLOTLIBRC`` if it is not a directory
644
+ - ``$MATPLOTLIBRC/matplotlibrc``
645
+ - ``$MPLCONFIGDIR/matplotlibrc``
646
+ - On Linux,
647
+ - ``$XDG_CONFIG_HOME/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME``
648
+ is defined)
649
+ - or ``$HOME/.config/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME``
650
+ is not defined)
651
+ - On other platforms,
652
+ - ``$HOME/.matplotlib/matplotlibrc`` if ``$HOME`` is defined
653
+ - Lastly, it looks in ``$MATPLOTLIBDATA/matplotlibrc``, which should always
654
+ exist.
655
+ """
656
+
657
+ def gen_candidates():
658
+ # rely on down-stream code to make absolute. This protects us
659
+ # from having to directly get the current working directory
660
+ # which can fail if the user has ended up with a cwd that is
661
+ # non-existent.
662
+ yield 'matplotlibrc'
663
+ try:
664
+ matplotlibrc = os.environ['MATPLOTLIBRC']
665
+ except KeyError:
666
+ pass
667
+ else:
668
+ yield matplotlibrc
669
+ yield os.path.join(matplotlibrc, 'matplotlibrc')
670
+ yield os.path.join(get_configdir(), 'matplotlibrc')
671
+ yield os.path.join(get_data_path(), 'matplotlibrc')
672
+
673
+ for fname in gen_candidates():
674
+ if os.path.exists(fname) and not os.path.isdir(fname):
675
+ return fname
676
+
677
+ raise RuntimeError("Could not find matplotlibrc file; your Matplotlib "
678
+ "install is broken")
679
+
680
+
681
+ class RcParams(MutableMapping, dict):
682
+ """
683
+ A dict-like key-value store for config parameters, including validation.
684
+
685
+ This is the data structure behind `matplotlib.rcParams`.
686
+
687
+ The complete list of rcParams can be found in :doc:`/users/explain/configuration`.
688
+ """
689
+
690
+ validate = rcsetup._validators
691
+
692
+ # validate values on the way in
693
+ def __init__(self, *args, **kwargs):
694
+ self.update(*args, **kwargs)
695
+
696
+ def _set(self, key, val):
697
+ """
698
+ Directly write data bypassing deprecation and validation logic.
699
+
700
+ Notes
701
+ -----
702
+ As end user or downstream library you almost always should use
703
+ ``rcParams[key] = val`` and not ``_set()``.
704
+
705
+ There are only very few special cases that need direct data access.
706
+ These cases previously used ``dict.__setitem__(rcParams, key, val)``,
707
+ which is now deprecated and replaced by ``rcParams._set(key, val)``.
708
+
709
+ Even though private, we guarantee API stability for ``rcParams._set``,
710
+ i.e. it is subject to Matplotlib's API and deprecation policy.
711
+
712
+ :meta public:
713
+ """
714
+ dict.__setitem__(self, key, val)
715
+ if self is globals().get("rcParams"):
716
+ from . import _rcpush
717
+ _rcpush.push(key, val)
718
+
719
+ def _get(self, key):
720
+ """
721
+ Directly read data bypassing deprecation, backend and validation
722
+ logic.
723
+
724
+ Notes
725
+ -----
726
+ As end user or downstream library you almost always should use
727
+ ``val = rcParams[key]`` and not ``_get()``.
728
+
729
+ There are only very few special cases that need direct data access.
730
+ These cases previously used ``dict.__getitem__(rcParams, key, val)``,
731
+ which is now deprecated and replaced by ``rcParams._get(key)``.
732
+
733
+ Even though private, we guarantee API stability for ``rcParams._get``,
734
+ i.e. it is subject to Matplotlib's API and deprecation policy.
735
+
736
+ :meta public:
737
+ """
738
+ return dict.__getitem__(self, key)
739
+
740
+ def _update_raw(self, other_params):
741
+ """
742
+ Directly update the data from *other_params*, bypassing deprecation,
743
+ backend and validation logic on both sides.
744
+
745
+ This ``rcParams._update_raw(params)`` replaces the previous pattern
746
+ ``dict.update(rcParams, params)``.
747
+
748
+ Parameters
749
+ ----------
750
+ other_params : dict or `.RcParams`
751
+ The input mapping from which to update.
752
+ """
753
+ if isinstance(other_params, RcParams):
754
+ other_params = dict.items(other_params)
755
+ dict.update(self, other_params)
756
+ if self is globals().get("rcParams") and "_rcpush" in globals():
757
+ _rcpush.push_all(self)
758
+
759
+ def _ensure_has_backend(self):
760
+ """
761
+ Ensure that a "backend" entry exists.
762
+
763
+ Normally, the default matplotlibrc file contains *no* entry for "backend" (the
764
+ corresponding line starts with ##, not #; we fill in _auto_backend_sentinel
765
+ in that case. However, packagers can set a different default backend
766
+ (resulting in a normal `#backend: foo` line) in which case we should *not*
767
+ fill in _auto_backend_sentinel.
768
+ """
769
+ dict.setdefault(self, "backend", rcsetup._auto_backend_sentinel)
770
+
771
+ def __setitem__(self, key, val):
772
+ if (key == "backend"
773
+ and val is rcsetup._auto_backend_sentinel
774
+ and "backend" in self):
775
+ return
776
+ valid_key = _api.getitem_checked(
777
+ self.validate, rcParam=key, _error_cls=KeyError
778
+ )
779
+ try:
780
+ cval = valid_key(val)
781
+ except ValueError as ve:
782
+ raise ValueError(f"Key {key}: {ve}") from None
783
+ if key in {"text.hinting_factor", "text.kerning_factor"} and cval is not None:
784
+ _api.warn_deprecated("3.11", name=key, obj_type="rcParam")
785
+ self._set(key, cval)
786
+
787
+ def __getitem__(self, key):
788
+ # In theory, this should only ever be used after the global rcParams
789
+ # has been set up, but better be safe e.g. in presence of breakpoints.
790
+ if key == "backend" and self is globals().get("rcParams"):
791
+ val = self._get(key)
792
+ if val is rcsetup._auto_backend_sentinel:
793
+ from . import pyplot as plt
794
+ plt.switch_backend(rcsetup._auto_backend_sentinel)
795
+ return self._get(key)
796
+
797
+ def _get_backend_or_none(self):
798
+ """Get the requested backend, if any, without triggering resolution."""
799
+ backend = self._get("backend")
800
+ return None if backend is rcsetup._auto_backend_sentinel else backend
801
+
802
+ def __repr__(self):
803
+ class_name = self.__class__.__name__
804
+ indent = len(class_name) + 1
805
+ with _api.suppress_matplotlib_deprecation_warning():
806
+ repr_split = pprint.pformat(dict(self), indent=1,
807
+ width=80 - indent).split('\n')
808
+ repr_indented = ('\n' + ' ' * indent).join(repr_split)
809
+ return f'{class_name}({repr_indented})'
810
+
811
+ def __str__(self):
812
+ return '\n'.join(map('{0[0]}: {0[1]}'.format, sorted(self.items())))
813
+
814
+ def __iter__(self):
815
+ """Yield sorted list of keys."""
816
+ # Deprecation warnings are silenced to cover the case where some
817
+ # rcParams entries are being deprecated.
818
+ with _api.suppress_matplotlib_deprecation_warning():
819
+ yield from sorted(dict.__iter__(self))
820
+
821
+ def __len__(self):
822
+ return dict.__len__(self)
823
+
824
+ def find_all(self, pattern):
825
+ """
826
+ Return the subset of this RcParams dictionary whose keys match,
827
+ using :func:`re.search`, the given ``pattern``.
828
+
829
+ .. note::
830
+
831
+ Changes to the returned dictionary are *not* propagated to
832
+ the parent RcParams dictionary.
833
+
834
+ """
835
+ pattern_re = re.compile(pattern)
836
+ return self.__class__(
837
+ (key, value) for key, value in self.items() if pattern_re.search(key)
838
+ )
839
+
840
+ def copy(self):
841
+ """Copy this RcParams instance."""
842
+ rccopy = self.__class__()
843
+ for k in self: # Skip deprecations and revalidation.
844
+ rccopy._set(k, self._get(k))
845
+ return rccopy
846
+
847
+
848
+ def rc_params(fail_on_error=False):
849
+ """Construct a `RcParams` instance from the default Matplotlib rc file."""
850
+ return rc_params_from_file(matplotlib_fname(), fail_on_error)
851
+
852
+
853
+ @functools.cache
854
+ def _get_ssl_context():
855
+ try:
856
+ import certifi
857
+ except ImportError:
858
+ _log.debug("Could not import certifi.")
859
+ return None
860
+ import ssl
861
+ return ssl.create_default_context(cafile=certifi.where())
862
+
863
+
864
+ @contextlib.contextmanager
865
+ def _open_file_or_url(fname):
866
+ if (isinstance(fname, str)
867
+ and fname.startswith(('http://', 'https://', 'ftp://', 'file:'))):
868
+ import urllib.request
869
+ ssl_ctx = _get_ssl_context()
870
+ if ssl_ctx is None:
871
+ _log.debug(
872
+ "Could not get certifi ssl context, https may not work."
873
+ )
874
+ with urllib.request.urlopen(fname, context=ssl_ctx) as f:
875
+ yield (line.decode('utf-8') for line in f)
876
+ else:
877
+ fname = os.path.expanduser(fname)
878
+ with open(fname, encoding='utf-8') as f:
879
+ yield f
880
+
881
+
882
+ def _rc_params_in_file(fname, transform=lambda x: x, fail_on_error=False):
883
+ """
884
+ Construct a `RcParams` instance from file *fname*.
885
+
886
+ Unlike `rc_params_from_file`, the configuration class only contains the
887
+ parameters specified in the file (i.e. default values are not filled in).
888
+
889
+ Parameters
890
+ ----------
891
+ fname : path-like
892
+ The loaded file.
893
+ transform : callable, default: the identity function
894
+ A function called on each individual line of the file to transform it,
895
+ before further parsing.
896
+ fail_on_error : bool, default: False
897
+ Whether invalid entries should result in an exception or a warning.
898
+ """
899
+ import matplotlib_rs as mpl
900
+ rc_temp = {}
901
+ with _open_file_or_url(fname) as fd:
902
+ try:
903
+ for line_no, line in enumerate(fd, 1):
904
+ line = transform(line)
905
+ strippedline = cbook._strip_comment(line)
906
+ if not strippedline:
907
+ continue
908
+ tup = strippedline.split(':', 1)
909
+ if len(tup) != 2:
910
+ _log.warning('Missing colon in file %r, line %d (%r)',
911
+ fname, line_no, line.rstrip('\n'))
912
+ continue
913
+ key, val = tup
914
+ key = key.strip()
915
+ val = val.strip()
916
+ if val.startswith('"') and val.endswith('"'):
917
+ val = val[1:-1] # strip double quotes
918
+ if key in rc_temp:
919
+ _log.warning('Duplicate key in file %r, line %d (%r)',
920
+ fname, line_no, line.rstrip('\n'))
921
+ rc_temp[key] = (val, line, line_no)
922
+ except UnicodeDecodeError:
923
+ _log.warning('Cannot decode configuration file %r as utf-8.',
924
+ fname)
925
+ raise
926
+
927
+ config = RcParams()
928
+
929
+ for key, (val, line, line_no) in rc_temp.items():
930
+ if key in rcsetup._validators:
931
+ if fail_on_error:
932
+ config[key] = val # try to convert to proper type or raise
933
+ else:
934
+ try:
935
+ config[key] = val # try to convert to proper type or skip
936
+ except Exception as msg:
937
+ _log.warning('Bad value in file %r, line %d (%r): %s',
938
+ fname, line_no, line.rstrip('\n'), msg)
939
+ else:
940
+ # __version__ must be looked up as an attribute to trigger the
941
+ # module-level __getattr__.
942
+ version = ('main' if '.post' in mpl.__version__
943
+ else f'v{mpl.__version__}')
944
+ _log.warning("""
945
+ Bad key %(key)s in file %(fname)s, line %(line_no)s (%(line)r)
946
+ You probably need to get an updated matplotlibrc file from
947
+ https://github.com/matplotlib/matplotlib/blob/%(version)s/lib/matplotlib/mpl-data/matplotlibrc
948
+ or from the matplotlib source distribution""",
949
+ dict(key=key, fname=fname, line_no=line_no,
950
+ line=line.rstrip('\n'), version=version))
951
+ return config
952
+
953
+
954
+ def rc_params_from_file(fname, fail_on_error=False, use_default_template=True):
955
+ """
956
+ Construct a `RcParams` from file *fname*.
957
+
958
+ Parameters
959
+ ----------
960
+ fname : str or path-like
961
+ A file with Matplotlib rc settings.
962
+ fail_on_error : bool
963
+ If True, raise an error when the parser fails to convert a parameter.
964
+ use_default_template : bool
965
+ If True, initialize with default parameters before updating with those
966
+ in the given file. If False, the configuration class only contains the
967
+ parameters specified in the file. (Useful for updating dicts.)
968
+ """
969
+ config_from_file = _rc_params_in_file(fname, fail_on_error=fail_on_error)
970
+
971
+ if not use_default_template:
972
+ return config_from_file
973
+
974
+ with _api.suppress_matplotlib_deprecation_warning():
975
+ config = RcParams({**rcParamsDefault, **config_from_file})
976
+
977
+ if "".join(config['text.latex.preamble']):
978
+ _log.info("""
979
+ *****************************************************************
980
+ You have the following UNSUPPORTED LaTeX preamble customizations:
981
+ %s
982
+ Please do not ask for support with these customizations active.
983
+ *****************************************************************
984
+ """, '\n'.join(config['text.latex.preamble']))
985
+ _log.debug('loaded rc file %s', fname)
986
+
987
+ return config
988
+
989
+
990
+ rcParamsDefault = _rc_params_in_file(
991
+ cbook._get_data_path("matplotlibrc"),
992
+ # Strip leading comment.
993
+ transform=lambda line: line[1:] if line.startswith("#") else line,
994
+ fail_on_error=True)
995
+ rcParamsDefault._update_raw(rcsetup._hardcoded_defaults)
996
+ rcParamsDefault._ensure_has_backend()
997
+
998
+ rcParams = RcParams() # The global instance.
999
+ rcParams._update_raw(rcParamsDefault)
1000
+ rcParams._update_raw(_rc_params_in_file(matplotlib_fname()))
1001
+ rcParamsOrig = rcParams.copy()
1002
+ with _api.suppress_matplotlib_deprecation_warning():
1003
+ # This also checks that all rcParams are indeed listed in the template.
1004
+ # Assigning to rcsetup.defaultParams is left only for backcompat.
1005
+ defaultParams = rcsetup.defaultParams = {
1006
+ # We want to resolve deprecated rcParams, but not backend...
1007
+ key: [(rcsetup._auto_backend_sentinel if key == "backend" else
1008
+ rcParamsDefault[key]),
1009
+ validator]
1010
+ for key, validator in rcsetup._validators.items()}
1011
+ if rcParams['axes.formatter.use_locale']:
1012
+ locale.setlocale(locale.LC_ALL, '')
1013
+
1014
+
1015
+ def rc(group, **kwargs):
1016
+ """
1017
+ Set the current `.rcParams`. *group* is the grouping for the rc, e.g.,
1018
+ for ``lines.linewidth`` the group is ``lines``, for
1019
+ ``axes.facecolor``, the group is ``axes``, and so on. Group may
1020
+ also be a list or tuple of group names, e.g., (*xtick*, *ytick*).
1021
+ *kwargs* is a dictionary attribute name/value pairs, e.g.,::
1022
+
1023
+ rc('lines', linewidth=2, color='r')
1024
+
1025
+ sets the current `.rcParams` and is equivalent to::
1026
+
1027
+ rcParams['lines.linewidth'] = 2
1028
+ rcParams['lines.color'] = 'r'
1029
+
1030
+ The following aliases are available to save typing for interactive users:
1031
+
1032
+ ====== =================
1033
+ Alias Property
1034
+ ====== =================
1035
+ 'lw' 'linewidth'
1036
+ 'ls' 'linestyle'
1037
+ 'c' 'color'
1038
+ 'fc' 'facecolor'
1039
+ 'ec' 'edgecolor'
1040
+ 'mew' 'markeredgewidth'
1041
+ 'aa' 'antialiased'
1042
+ 'sans' 'sans-serif'
1043
+ ====== =================
1044
+
1045
+ Thus you could abbreviate the above call as::
1046
+
1047
+ rc('lines', lw=2, c='r')
1048
+
1049
+ Note you can use python's kwargs dictionary facility to store
1050
+ dictionaries of default parameters. e.g., you can customize the
1051
+ font rc as follows::
1052
+
1053
+ font = {'family' : 'monospace',
1054
+ 'weight' : 'bold',
1055
+ 'size' : 'large'}
1056
+ rc('font', **font) # pass in the font dict as kwargs
1057
+
1058
+ This enables you to easily switch between several configurations. Use
1059
+ ``matplotlib.style.use('default')`` or :func:`~matplotlib.rcdefaults` to
1060
+ restore the default `.rcParams` after changes.
1061
+
1062
+ Notes
1063
+ -----
1064
+ Similar functionality is available by using the normal dict interface, i.e.
1065
+ ``rcParams.update({"lines.linewidth": 2, ...})`` (but ``rcParams.update``
1066
+ does not support abbreviations or grouping).
1067
+ """
1068
+
1069
+ aliases = {
1070
+ 'lw': 'linewidth',
1071
+ 'ls': 'linestyle',
1072
+ 'c': 'color',
1073
+ 'fc': 'facecolor',
1074
+ 'ec': 'edgecolor',
1075
+ 'mew': 'markeredgewidth',
1076
+ 'aa': 'antialiased',
1077
+ 'sans': 'sans-serif',
1078
+ }
1079
+
1080
+ if isinstance(group, str):
1081
+ group = (group,)
1082
+ for g in group:
1083
+ for k, v in kwargs.items():
1084
+ name = aliases.get(k) or k
1085
+ key = f'{g}.{name}'
1086
+ try:
1087
+ rcParams[key] = v
1088
+ except KeyError as err:
1089
+ raise KeyError(('Unrecognized key "%s" for group "%s" and '
1090
+ 'name "%s"') % (key, g, name)) from err
1091
+
1092
+
1093
+ def rcdefaults():
1094
+ """
1095
+ Restore the `.rcParams` from Matplotlib's internal default style.
1096
+
1097
+ Style-blacklisted `.rcParams` (defined in
1098
+ ``matplotlib.style.core.STYLE_BLACKLIST``) are not updated.
1099
+
1100
+ See Also
1101
+ --------
1102
+ matplotlib.rc_file_defaults
1103
+ Restore the `.rcParams` from the rc file originally loaded by
1104
+ Matplotlib.
1105
+ matplotlib.style.use
1106
+ Use a specific style file. Call ``style.use('default')`` to restore
1107
+ the default style.
1108
+ """
1109
+ # Deprecation warnings were already handled when creating rcParamsDefault,
1110
+ # no need to reemit them here.
1111
+ with _api.suppress_matplotlib_deprecation_warning():
1112
+ from .style.core import STYLE_BLACKLIST
1113
+ rcParams.clear()
1114
+ rcParams.update({k: v for k, v in rcParamsDefault.items()
1115
+ if k not in STYLE_BLACKLIST})
1116
+
1117
+
1118
+ def rc_file_defaults():
1119
+ """
1120
+ Restore the `.rcParams` from the original rc file loaded by Matplotlib.
1121
+
1122
+ Style-blacklisted `.rcParams` (defined in
1123
+ ``matplotlib.style.core.STYLE_BLACKLIST``) are not updated.
1124
+ """
1125
+ # Deprecation warnings were already handled when creating rcParamsOrig, no
1126
+ # need to reemit them here.
1127
+ with _api.suppress_matplotlib_deprecation_warning():
1128
+ from .style.core import STYLE_BLACKLIST
1129
+ rcParams.update({k: rcParamsOrig[k] for k in rcParamsOrig
1130
+ if k not in STYLE_BLACKLIST})
1131
+
1132
+
1133
+ def rc_file(fname, *, use_default_template=True):
1134
+ """
1135
+ Update `.rcParams` from file.
1136
+
1137
+ Style-blacklisted `.rcParams` (defined in
1138
+ ``matplotlib.style.core.STYLE_BLACKLIST``) are not updated.
1139
+
1140
+ Parameters
1141
+ ----------
1142
+ fname : str or path-like
1143
+ A file with Matplotlib rc settings.
1144
+
1145
+ use_default_template : bool
1146
+ If True, initialize with default parameters before updating with those
1147
+ in the given file. If False, the current configuration persists
1148
+ and only the parameters specified in the file are updated.
1149
+ """
1150
+ # Deprecation warnings were already handled in rc_params_from_file, no need
1151
+ # to reemit them here.
1152
+ with _api.suppress_matplotlib_deprecation_warning():
1153
+ from .style.core import STYLE_BLACKLIST
1154
+ rc_from_file = rc_params_from_file(
1155
+ fname, use_default_template=use_default_template)
1156
+ rcParams.update({k: rc_from_file[k] for k in rc_from_file
1157
+ if k not in STYLE_BLACKLIST})
1158
+
1159
+
1160
+ @contextlib.contextmanager
1161
+ def rc_context(rc=None, fname=None):
1162
+ """
1163
+ Return a context manager for temporarily changing rcParams.
1164
+
1165
+ The :rc:`backend` will not be reset by the context manager.
1166
+
1167
+ rcParams changed both through the context manager invocation and
1168
+ in the body of the context will be reset on context exit.
1169
+
1170
+ Parameters
1171
+ ----------
1172
+ rc : dict
1173
+ The rcParams to temporarily set.
1174
+ fname : str or path-like
1175
+ A file with Matplotlib rc settings. If both *fname* and *rc* are given,
1176
+ settings from *rc* take precedence.
1177
+
1178
+ See Also
1179
+ --------
1180
+ :ref:`customizing-with-matplotlibrc-files`
1181
+
1182
+ Examples
1183
+ --------
1184
+ Passing explicit values via a dict::
1185
+
1186
+ with mpl.rc_context({'interactive': False}):
1187
+ fig, ax = plt.subplots()
1188
+ ax.plot(range(3), range(3))
1189
+ fig.savefig('example.png')
1190
+ plt.close(fig)
1191
+
1192
+ Loading settings from a file::
1193
+
1194
+ with mpl.rc_context(fname='print.rc'):
1195
+ plt.plot(x, y) # uses 'print.rc'
1196
+
1197
+ Setting in the context body::
1198
+
1199
+ with mpl.rc_context():
1200
+ # will be reset
1201
+ mpl.rcParams['lines.linewidth'] = 5
1202
+ plt.plot(x, y)
1203
+
1204
+ """
1205
+ orig = dict(rcParams.copy())
1206
+ del orig['backend']
1207
+ try:
1208
+ if fname:
1209
+ rc_file(fname)
1210
+ if rc:
1211
+ rcParams.update(rc)
1212
+ yield
1213
+ finally:
1214
+ rcParams._update_raw(orig) # Revert to the original rcs.
1215
+
1216
+
1217
+ def use(backend, *, force=True):
1218
+ """
1219
+ Select the backend used for rendering and GUI integration.
1220
+
1221
+ If pyplot is already imported, `~matplotlib.pyplot.switch_backend` is used
1222
+ to switch the backend.
1223
+
1224
+ Parameters
1225
+ ----------
1226
+ backend : str
1227
+ The backend to switch to. This can either be one of the standard
1228
+ backend names, which are case-insensitive:
1229
+
1230
+ - interactive backends:
1231
+ GTK3Agg, GTK3Cairo, GTK4Agg, GTK4Cairo, MacOSX, nbAgg, notebook, QtAgg,
1232
+ QtCairo, TkAgg, TkCairo, WebAgg, WX, WXAgg, WXCairo, Qt5Agg, Qt5Cairo
1233
+
1234
+ - non-interactive backends:
1235
+ agg, cairo, pdf, pgf, ps, svg, template
1236
+
1237
+ or a string of the form: ``module://my.module.name``.
1238
+
1239
+ notebook is a synonym for nbAgg.
1240
+
1241
+ Switching to an interactive backend is not possible if an unrelated
1242
+ event loop has already been started (e.g., switching to GTK3Agg if a
1243
+ TkAgg window has already been opened). Switching to a non-interactive
1244
+ backend is always possible.
1245
+
1246
+ force : bool, default: True
1247
+ If True (the default), raise an `ImportError` if the backend cannot be
1248
+ set up (either because it fails to import, or because an incompatible
1249
+ GUI interactive framework is already running); if False, silently
1250
+ ignore the failure.
1251
+
1252
+ See Also
1253
+ --------
1254
+ :ref:`backends`
1255
+ matplotlib.get_backend
1256
+ matplotlib.pyplot.switch_backend
1257
+
1258
+ """
1259
+ name = rcsetup.validate_backend(backend)
1260
+ # don't (prematurely) resolve the "auto" backend setting
1261
+ if rcParams._get_backend_or_none() == name:
1262
+ # Nothing to do if the requested backend is already set
1263
+ pass
1264
+ else:
1265
+ # if pyplot is not already imported, do not import it. Doing
1266
+ # so may trigger a `plt.switch_backend` to the _default_ backend
1267
+ # before we get a chance to change to the one the user just requested
1268
+ plt = sys.modules.get('matplotlib.pyplot')
1269
+ # if pyplot is imported, then try to change backends
1270
+ if plt is not None:
1271
+ try:
1272
+ # we need this import check here to re-raise if the
1273
+ # user does not have the libraries to support their
1274
+ # chosen backend installed.
1275
+ plt.switch_backend(name)
1276
+ except ImportError:
1277
+ if force:
1278
+ raise
1279
+ # if we have not imported pyplot, then we can set the rcParam
1280
+ # value which will be respected when the user finally imports
1281
+ # pyplot
1282
+ else:
1283
+ rcParams['backend'] = backend
1284
+ # if the user has asked for a given backend, do not helpfully
1285
+ # fallback
1286
+ rcParams['backend_fallback'] = False
1287
+
1288
+
1289
+ if os.environ.get('MPLBACKEND'):
1290
+ rcParams['backend'] = os.environ.get('MPLBACKEND')
1291
+
1292
+
1293
+ def get_backend(*, auto_select=True):
1294
+ """
1295
+ Return the name of the current backend.
1296
+
1297
+ Parameters
1298
+ ----------
1299
+ auto_select : bool, default: True
1300
+ Whether to trigger backend resolution if no backend has been
1301
+ selected so far. If True, this ensures that a valid backend
1302
+ is returned. If False, this returns None if no backend has been
1303
+ selected so far.
1304
+
1305
+ .. versionadded:: 3.10
1306
+
1307
+ .. admonition:: Provisional
1308
+
1309
+ The *auto_select* flag is provisional. It may be changed or removed
1310
+ without prior warning.
1311
+
1312
+ See Also
1313
+ --------
1314
+ matplotlib.use
1315
+ """
1316
+ if auto_select:
1317
+ return rcParams['backend']
1318
+ else:
1319
+ backend = rcParams._get('backend')
1320
+ if backend is rcsetup._auto_backend_sentinel:
1321
+ return None
1322
+ else:
1323
+ return backend
1324
+
1325
+
1326
+ def interactive(b):
1327
+ """
1328
+ Set whether to redraw after every plotting command (e.g. `.pyplot.xlabel`).
1329
+ """
1330
+ rcParams['interactive'] = b
1331
+
1332
+
1333
+ def is_interactive():
1334
+ """
1335
+ Return whether to redraw after every plotting command.
1336
+
1337
+ .. note::
1338
+
1339
+ This function is only intended for use in backends. End users should
1340
+ use `.pyplot.isinteractive` instead.
1341
+ """
1342
+ return rcParams['interactive']
1343
+
1344
+
1345
+ def _val_or_rc(val, *rc_names):
1346
+ """
1347
+ If *val* is None, the first not-None value in ``mpl.rcParams[rc_names[i]]``.
1348
+ If all are None returns ``mpl.rcParams[rc_names[-1]]``.
1349
+ """
1350
+ if val is not None:
1351
+ return val
1352
+
1353
+ for rc_name in rc_names[:-1]:
1354
+ if rcParams[rc_name] is not None:
1355
+ return rcParams[rc_name]
1356
+ return rcParams[rc_names[-1]]
1357
+
1358
+
1359
+ def _init_tests():
1360
+ # The version of FreeType to install locally for running the tests. This must match
1361
+ # the value in `subprojects/freetype2.wrap`.
1362
+ LOCAL_FREETYPE_VERSION = '2.14.3'
1363
+
1364
+ from . import ft2font
1365
+ if (ft2font.__freetype_version__ != LOCAL_FREETYPE_VERSION or
1366
+ ft2font.__freetype_build_type__ != 'local'):
1367
+ _log.warning(
1368
+ "Matplotlib is not built with the correct FreeType version to run tests. "
1369
+ "Rebuild without setting system-freetype=true in Meson setup options. "
1370
+ "Expect many image comparison failures below. "
1371
+ "Expected freetype version %s. "
1372
+ "Found freetype version %s. "
1373
+ "Freetype build type is %slocal.",
1374
+ LOCAL_FREETYPE_VERSION,
1375
+ ft2font.__freetype_version__,
1376
+ "" if ft2font.__freetype_build_type__ == 'local' else "not ")
1377
+
1378
+ # Generate a shortcut for classic testing style.
1379
+ from .style import _base_library, library
1380
+ _base_library['_classic_test'] = library['_classic_test'] = RcParams(
1381
+ _base_library['classic'] | _base_library['_classic_test_patch'])
1382
+
1383
+
1384
+ def _replacer(data, value):
1385
+ """
1386
+ Either returns ``data[value]`` or passes ``data`` back, converting any
1387
+ ``MappingView`` to a sequence.
1388
+ """
1389
+ try:
1390
+ # if key isn't a string don't bother
1391
+ if isinstance(value, str):
1392
+ # try to use __getitem__
1393
+ value = data[value]
1394
+ except Exception:
1395
+ # key does not exist, silently fall back to key
1396
+ pass
1397
+ return cbook.sanitize_sequence(value)
1398
+
1399
+
1400
+ def _label_from_arg(y, default_name):
1401
+ try:
1402
+ return y.name
1403
+ except AttributeError:
1404
+ if isinstance(default_name, str):
1405
+ return default_name
1406
+ return None
1407
+
1408
+
1409
+ def _add_data_doc(docstring, replace_names):
1410
+ """
1411
+ Add documentation for a *data* field to the given docstring.
1412
+
1413
+ Parameters
1414
+ ----------
1415
+ docstring : str
1416
+ The input docstring.
1417
+ replace_names : list of str or None
1418
+ The list of parameter names which arguments should be replaced by
1419
+ ``data[name]`` (if ``data[name]`` does not throw an exception). If
1420
+ None, replacement is attempted for all arguments.
1421
+
1422
+ Returns
1423
+ -------
1424
+ str
1425
+ The augmented docstring.
1426
+ """
1427
+ if (docstring is None
1428
+ or replace_names is not None and len(replace_names) == 0):
1429
+ return docstring
1430
+ docstring = inspect.cleandoc(docstring)
1431
+
1432
+ data_doc = ("""\
1433
+ If given, all parameters also accept a string ``s``, which is
1434
+ interpreted as ``data[s]`` if ``s`` is a key in ``data``."""
1435
+ if replace_names is None else f"""\
1436
+ If given, the following parameters also accept a string ``s``, which is
1437
+ interpreted as ``data[s]`` if ``s`` is a key in ``data``:
1438
+
1439
+ {', '.join(map('*{}*'.format, replace_names))}""")
1440
+ # using string replacement instead of formatting has the advantages
1441
+ # 1) simpler indent handling
1442
+ # 2) prevent problems with formatting characters '{', '%' in the docstring
1443
+ if _log.level <= logging.DEBUG:
1444
+ # test_data_parameter_replacement() tests against these log messages
1445
+ # make sure to keep message and test in sync
1446
+ if "data : indexable object, optional" not in docstring:
1447
+ _log.debug("data parameter docstring error: no data parameter")
1448
+ if 'DATA_PARAMETER_PLACEHOLDER' not in docstring:
1449
+ _log.debug("data parameter docstring error: missing placeholder")
1450
+ return docstring.replace(' DATA_PARAMETER_PLACEHOLDER', data_doc)
1451
+
1452
+
1453
+ def _preprocess_data(func=None, *, replace_names=None, label_namer=None):
1454
+ """
1455
+ A decorator to add a 'data' kwarg to a function.
1456
+
1457
+ When applied::
1458
+
1459
+ @_preprocess_data()
1460
+ def func(ax, *args, **kwargs): ...
1461
+
1462
+ the signature is modified to ``decorated(ax, *args, data=None, **kwargs)``
1463
+ with the following behavior:
1464
+
1465
+ - if called with ``data=None``, forward the other arguments to ``func``;
1466
+ - otherwise, *data* must be a mapping; for any argument passed in as a
1467
+ string ``name``, replace the argument by ``data[name]`` (if this does not
1468
+ throw an exception), then forward the arguments to ``func``.
1469
+
1470
+ In either case, any argument that is a `MappingView` is also converted to a
1471
+ list.
1472
+
1473
+ Parameters
1474
+ ----------
1475
+ replace_names : list of str or None, default: None
1476
+ The list of parameter names for which lookup into *data* should be
1477
+ attempted. If None, replacement is attempted for all arguments.
1478
+ label_namer : str, default: None
1479
+ If set e.g. to "namer" (which must be a kwarg in the function's
1480
+ signature -- not as ``**kwargs``), if the *namer* argument passed in is
1481
+ a (string) key of *data* and no *label* kwarg is passed, then use the
1482
+ (string) value of the *namer* as *label*. ::
1483
+
1484
+ @_preprocess_data(label_namer="foo")
1485
+ def func(foo, label=None): ...
1486
+
1487
+ func("key", data={"key": value})
1488
+ # is equivalent to
1489
+ func.__wrapped__(value, label="key")
1490
+ """
1491
+
1492
+ if func is None: # Return the actual decorator.
1493
+ return functools.partial(
1494
+ _preprocess_data,
1495
+ replace_names=replace_names, label_namer=label_namer)
1496
+
1497
+ sig = inspect.signature(func)
1498
+ varargs_name = None
1499
+ varkwargs_name = None
1500
+ arg_names = []
1501
+ params = list(sig.parameters.values())
1502
+ for p in params:
1503
+ if p.kind is Parameter.VAR_POSITIONAL:
1504
+ varargs_name = p.name
1505
+ elif p.kind is Parameter.VAR_KEYWORD:
1506
+ varkwargs_name = p.name
1507
+ else:
1508
+ arg_names.append(p.name)
1509
+ data_param = Parameter("data", Parameter.KEYWORD_ONLY, default=None)
1510
+ if varkwargs_name:
1511
+ params.insert(-1, data_param)
1512
+ else:
1513
+ params.append(data_param)
1514
+ new_sig = sig.replace(parameters=params)
1515
+ arg_names = arg_names[1:] # remove the first "ax" / self arg
1516
+
1517
+ assert {*arg_names}.issuperset(replace_names or []) or varkwargs_name, (
1518
+ "Matplotlib internal error: invalid replace_names "
1519
+ f"({replace_names!r}) for {func.__name__!r}")
1520
+ assert label_namer is None or label_namer in arg_names, (
1521
+ "Matplotlib internal error: invalid label_namer "
1522
+ f"({label_namer!r}) for {func.__name__!r}")
1523
+
1524
+ @functools.wraps(func)
1525
+ def inner(ax, *args, data=None, **kwargs):
1526
+ __tracebackhide__ = True
1527
+
1528
+ if data is None:
1529
+ return func(
1530
+ ax,
1531
+ *map(cbook.sanitize_sequence, args),
1532
+ **{k: cbook.sanitize_sequence(v) for k, v in kwargs.items()})
1533
+
1534
+ bound = new_sig.bind(ax, *args, **kwargs)
1535
+ auto_label = (bound.arguments.get(label_namer)
1536
+ or bound.kwargs.get(label_namer))
1537
+
1538
+ for k, v in bound.arguments.items():
1539
+ if k == varkwargs_name:
1540
+ for k1, v1 in v.items():
1541
+ if replace_names is None or k1 in replace_names:
1542
+ v[k1] = _replacer(data, v1)
1543
+ elif k == varargs_name:
1544
+ if replace_names is None:
1545
+ bound.arguments[k] = tuple(_replacer(data, v1) for v1 in v)
1546
+ else:
1547
+ if replace_names is None or k in replace_names:
1548
+ bound.arguments[k] = _replacer(data, v)
1549
+
1550
+ new_args = bound.args
1551
+ new_kwargs = bound.kwargs
1552
+
1553
+ args_and_kwargs = {**bound.arguments, **bound.kwargs}
1554
+ if label_namer and "label" not in args_and_kwargs:
1555
+ new_kwargs["label"] = _label_from_arg(
1556
+ args_and_kwargs.get(label_namer), auto_label)
1557
+
1558
+ return func(*new_args, **new_kwargs)
1559
+
1560
+ inner.__doc__ = _add_data_doc(inner.__doc__, replace_names)
1561
+ inner.__signature__ = new_sig
1562
+ return inner
1563
+
1564
+
1565
+ _log.debug('interactive is %s', is_interactive())
1566
+ _log.debug('platform is %s', sys.platform)
1567
+
1568
+
1569
+ @_api.deprecated("3.10", alternative="matplotlib.cbook.sanitize_sequence")
1570
+ def sanitize_sequence(data):
1571
+ return cbook.sanitize_sequence(data)
1572
+
1573
+
1574
+ @_api.deprecated("3.10", alternative="matplotlib.rcsetup.validate_backend")
1575
+ def validate_backend(s):
1576
+ return rcsetup.validate_backend(s)
1577
+
1578
+
1579
+ # workaround: we must defer colormaps import to after loading rcParams, because
1580
+ # colormap creation depends on rcParams
1581
+ from .cm import _colormaps as colormaps # noqa: E402
1582
+ from .cm import _multivar_colormaps as multivar_colormaps # noqa: E402
1583
+ from .cm import _bivar_colormaps as bivar_colormaps # noqa: E402
1584
+ from . import _rcpush # noqa: E402
1585
+ _rcpush.push_all(rcParams)
1586
+
1587
+
1588
+ def _dot_uses_fma():
1589
+ import numpy as np
1590
+ """Whether numpy's 3x3 ``np.dot`` uses fused multiply-adds (the Rust
1591
+ transforms then compose matrices the same way)."""
1592
+ rng = np.random.default_rng(0)
1593
+ for _ in range(200):
1594
+ a = rng.standard_normal((3, 3))
1595
+ b = rng.standard_normal((3, 3))
1596
+ r = np.dot(b, a)
1597
+ for i in range(3):
1598
+ for j in range(3):
1599
+ if r[i, j] != b[i, 0] * a[0, j] + b[i, 1] * a[1, j] + b[i, 2] * a[2, j]:
1600
+ return True
1601
+ return False
1602
+
1603
+
1604
+ _mplrs.set_dot_uses_fma(_dot_uses_fma())
1605
+
1606
+
1607
+ def _rs_mathtext_layout(s, dpi, prop):
1608
+ """Mathtext layout for the Rust renderer (``MathTextParser('path')``)."""
1609
+ global _rs_mathtext_parser
1610
+ from .font_manager import FontProperties
1611
+ if _rs_mathtext_parser is None:
1612
+ from .mathtext import MathTextParser
1613
+ _rs_mathtext_parser = MathTextParser("path")
1614
+ family, style, variant, weight, stretch, size, fname, math_fontfamily = prop
1615
+ fp = FontProperties(family=family, style=style, variant=variant, weight=weight,
1616
+ stretch=stretch, size=size, fname=fname,
1617
+ math_fontfamily=math_fontfamily)
1618
+ parse = _rs_mathtext_parser.parse(s, dpi, fp)
1619
+ glyphs = [(font.fname, int(getattr(font, "face_index", 0)), float(fontsize),
1620
+ int(glyph_index), float(ox), float(oy))
1621
+ for font, fontsize, _num, glyph_index, ox, oy in parse.glyphs]
1622
+ rects = [tuple(map(float, r)) for r in parse.rects]
1623
+ return (float(parse.width), float(parse.height), float(parse.depth), glyphs, rects)
1624
+
1625
+
1626
+ _rs_mathtext_parser = None
1627
+ _mplrs.set_mathtext_handler(_rs_mathtext_layout)
1628
+
1629
+ _rs_scale_transforms = {}
1630
+ _rs_py_scale_transforms = {}
1631
+ _rs_py_scale_ids = __import__("itertools").count(1)
1632
+
1633
+
1634
+ def _rs_register_scale_transform(t):
1635
+ """Register the transform of a scale implemented in Python; returns the
1636
+ id under which the Rust core evaluates it."""
1637
+ import weakref
1638
+ cid = next(_rs_py_scale_ids)
1639
+ _rs_py_scale_transforms[cid] = weakref.ref(
1640
+ t, lambda _, cid=cid: _rs_py_scale_transforms.pop(cid, None))
1641
+ return cid
1642
+
1643
+
1644
+ def _rs_scale_transform(kind, params, values):
1645
+ """The non-affine part of a scale transform, computed by matplotlib's
1646
+ scale classes (i.e. with numpy) for the Rust renderer."""
1647
+ if kind in ("py", "invpy"):
1648
+ import numpy as np
1649
+ ref = _rs_py_scale_transforms.get(int(params[0]))
1650
+ t = ref() if ref is not None else None
1651
+ if t is None:
1652
+ return values
1653
+ if kind == "invpy":
1654
+ t = t.inverted()
1655
+ return np.ascontiguousarray(t.transform(values), dtype=float).reshape(-1)
1656
+ t = _rs_scale_transforms.get((kind, params))
1657
+ if t is None:
1658
+ from . import scale as mscale
1659
+ if kind == "log":
1660
+ t = mscale.LogTransform(params[0], "clip" if params[1] else "mask")
1661
+ elif kind == "invlog":
1662
+ t = mscale.InvertedLogTransform(params[0])
1663
+ elif kind == "symlog":
1664
+ t = mscale.SymmetricalLogTransform(*params)
1665
+ elif kind == "invsymlog":
1666
+ t = mscale.InvertedSymmetricalLogTransform(*params)
1667
+ elif kind == "logit":
1668
+ t = mscale.LogitTransform("clip" if params[0] else "mask")
1669
+ elif kind == "logistic":
1670
+ t = mscale.LogisticTransform()
1671
+ elif kind == "asinh":
1672
+ t = mscale.AsinhTransform(params[0])
1673
+ elif kind == "invasinh":
1674
+ t = mscale.InvertedAsinhTransform(params[0])
1675
+ else:
1676
+ raise ValueError(kind)
1677
+ _rs_scale_transforms[(kind, params)] = t
1678
+ import numpy as np
1679
+ return np.ascontiguousarray(t.transform_non_affine(values), dtype=float)
1680
+
1681
+
1682
+ _mplrs.set_scale_hook(_rs_scale_transform)
1683
+ from ._hook import install, uninstall # noqa: E402