pyplot.py 146 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644
  1. # Note: The first part of this file can be modified in place, but the latter
  2. # part is autogenerated by the boilerplate.py script.
  3. """
  4. `matplotlib.pyplot` is a state-based interface to matplotlib. It provides
  5. an implicit, MATLAB-like, way of plotting. It also opens figures on your
  6. screen, and acts as the figure GUI manager.
  7. pyplot is mainly intended for interactive plots and simple cases of
  8. programmatic plot generation::
  9. import numpy as np
  10. import matplotlib.pyplot as plt
  11. x = np.arange(0, 5, 0.1)
  12. y = np.sin(x)
  13. plt.plot(x, y)
  14. plt.show()
  15. The explicit object-oriented API is recommended for complex plots, though
  16. pyplot is still usually used to create the figure and often the Axes in the
  17. figure. See `.pyplot.figure`, `.pyplot.subplots`, and
  18. `.pyplot.subplot_mosaic` to create figures, and
  19. :doc:`Axes API </api/axes_api>` for the plotting methods on an Axes::
  20. import numpy as np
  21. import matplotlib.pyplot as plt
  22. x = np.arange(0, 5, 0.1)
  23. y = np.sin(x)
  24. fig, ax = plt.subplots()
  25. ax.plot(x, y)
  26. plt.show()
  27. See :ref:`api_interfaces` for an explanation of the tradeoffs between the
  28. implicit and explicit interfaces.
  29. """
  30. # fmt: off
  31. from __future__ import annotations
  32. from contextlib import AbstractContextManager, ExitStack
  33. from enum import Enum
  34. import functools
  35. import importlib
  36. import inspect
  37. import logging
  38. import sys
  39. import threading
  40. import time
  41. from typing import TYPE_CHECKING, cast, overload
  42. from cycler import cycler # noqa: F401
  43. import matplotlib
  44. import matplotlib.image
  45. from matplotlib import _api
  46. # Re-exported (import x as x) for typing.
  47. from matplotlib import get_backend as get_backend, rcParams as rcParams
  48. from matplotlib import cm as cm # noqa: F401
  49. from matplotlib import style as style # noqa: F401
  50. from matplotlib import _pylab_helpers
  51. from matplotlib import interactive # noqa: F401
  52. from matplotlib import cbook
  53. from matplotlib import _docstring
  54. from matplotlib.backend_bases import (
  55. FigureCanvasBase, FigureManagerBase, MouseButton)
  56. from matplotlib.figure import Figure, FigureBase, figaspect
  57. from matplotlib.gridspec import GridSpec, SubplotSpec
  58. from matplotlib import rcsetup, rcParamsDefault, rcParamsOrig
  59. from matplotlib.artist import Artist
  60. from matplotlib.axes import Axes
  61. from matplotlib.axes import Subplot # noqa: F401
  62. from matplotlib.backends import BackendFilter, backend_registry
  63. from matplotlib.projections import PolarAxes
  64. from matplotlib.colorizer import _ColorizerInterface, ColorizingArtist, Colorizer
  65. from matplotlib import mlab # for detrend_none, window_hanning
  66. from matplotlib.scale import get_scale_names # noqa: F401
  67. from matplotlib.cm import _colormaps
  68. from matplotlib.colors import _color_sequences, Colormap
  69. import numpy as np
  70. if TYPE_CHECKING:
  71. from collections.abc import Callable, Hashable, Iterable, Sequence
  72. import datetime
  73. import pathlib
  74. import os
  75. from typing import Any, BinaryIO, Literal, TypeVar
  76. from typing_extensions import ParamSpec
  77. import PIL.Image
  78. from numpy.typing import ArrayLike
  79. import matplotlib.axes
  80. import matplotlib.artist
  81. import matplotlib.backend_bases
  82. from matplotlib.axis import Tick
  83. from matplotlib.axes._base import _AxesBase
  84. from matplotlib.backend_bases import Event
  85. from matplotlib.cm import ScalarMappable
  86. from matplotlib.contour import ContourSet, QuadContourSet
  87. from matplotlib.collections import (
  88. Collection,
  89. FillBetweenPolyCollection,
  90. LineCollection,
  91. PolyCollection,
  92. PathCollection,
  93. EventCollection,
  94. QuadMesh,
  95. )
  96. from matplotlib.colorbar import Colorbar
  97. from matplotlib.container import (
  98. BarContainer,
  99. ErrorbarContainer,
  100. StemContainer,
  101. )
  102. from matplotlib.figure import SubFigure
  103. from matplotlib.legend import Legend
  104. from matplotlib.mlab import GaussianKDE
  105. from matplotlib.image import AxesImage, FigureImage
  106. from matplotlib.patches import FancyArrow, StepPatch, Wedge
  107. from matplotlib.quiver import Barbs, Quiver, QuiverKey
  108. from matplotlib.scale import ScaleBase
  109. from matplotlib.typing import (
  110. ColorType,
  111. CoordsType,
  112. HashableList,
  113. LineStyleType,
  114. MarkerType,
  115. )
  116. from matplotlib.widgets import SubplotTool
  117. _P = ParamSpec('_P')
  118. _R = TypeVar('_R')
  119. _T = TypeVar('_T')
  120. # We may not need the following imports here:
  121. from matplotlib.colors import Normalize
  122. from matplotlib.lines import Line2D, AxLine
  123. from matplotlib.text import Text, Annotation
  124. from matplotlib.patches import Arrow, Circle, Rectangle # noqa: F401
  125. from matplotlib.patches import Polygon
  126. from matplotlib.widgets import Button, Slider, Widget # noqa: F401
  127. from .ticker import ( # noqa: F401
  128. TickHelper, Formatter, FixedFormatter, NullFormatter, FuncFormatter,
  129. FormatStrFormatter, ScalarFormatter, LogFormatter, LogFormatterExponent,
  130. LogFormatterMathtext, Locator, IndexLocator, FixedLocator, NullLocator,
  131. LinearLocator, LogLocator, AutoLocator, MultipleLocator, MaxNLocator)
  132. _log = logging.getLogger(__name__)
  133. # Explicit rename instead of import-as for typing's sake.
  134. colormaps = _colormaps
  135. color_sequences = _color_sequences
  136. @overload
  137. def _copy_docstring_and_deprecators(
  138. method: Any,
  139. func: Literal[None] = None
  140. ) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ...
  141. @overload
  142. def _copy_docstring_and_deprecators(
  143. method: Any, func: Callable[_P, _R]) -> Callable[_P, _R]: ...
  144. def _copy_docstring_and_deprecators(
  145. method: Any,
  146. func: Callable[_P, _R] | None = None
  147. ) -> Callable[[Callable[_P, _R]], Callable[_P, _R]] | Callable[_P, _R]:
  148. if func is None:
  149. return cast('Callable[[Callable[_P, _R]], Callable[_P, _R]]',
  150. functools.partial(_copy_docstring_and_deprecators, method))
  151. decorators: list[Callable[[Callable[_P, _R]], Callable[_P, _R]]] = [
  152. _docstring.copy(method)
  153. ]
  154. # Check whether the definition of *method* includes @_api.rename_parameter
  155. # or @_api.make_keyword_only decorators; if so, propagate them to the
  156. # pyplot wrapper as well.
  157. while hasattr(method, "__wrapped__"):
  158. potential_decorator = _api.deprecation.DECORATORS.get(method)
  159. if potential_decorator:
  160. decorators.append(potential_decorator)
  161. method = method.__wrapped__
  162. for decorator in decorators[::-1]:
  163. func = decorator(func)
  164. _add_pyplot_note(func, method)
  165. return func
  166. _NO_PYPLOT_NOTE = [
  167. 'FigureBase._gci', # wrapped_func is private
  168. '_AxesBase._sci', # wrapped_func is private
  169. 'Artist.findobj', # not a standard pyplot wrapper because it does not operate
  170. # on the current Figure / Axes. Explanation of relation would
  171. # be more complex and is not too important.
  172. ]
  173. def _add_pyplot_note(func, wrapped_func):
  174. """
  175. Add a note to the docstring of *func* that it is a pyplot wrapper.
  176. The note is added to the "Notes" section of the docstring. If that does
  177. not exist, a "Notes" section is created. In numpydoc, the "Notes"
  178. section is the third last possible section, only potentially followed by
  179. "References" and "Examples".
  180. """
  181. if not func.__doc__:
  182. return # nothing to do
  183. qualname = wrapped_func.__qualname__
  184. if qualname in _NO_PYPLOT_NOTE:
  185. return
  186. wrapped_func_is_method = True
  187. if "." not in qualname:
  188. # method qualnames are prefixed by the class and ".", e.g. "Axes.plot"
  189. wrapped_func_is_method = False
  190. link = f"{wrapped_func.__module__}.{qualname}"
  191. elif qualname.startswith("Axes."): # e.g. "Axes.plot"
  192. link = ".axes." + qualname
  193. elif qualname.startswith("_AxesBase."): # e.g. "_AxesBase.set_xlabel"
  194. link = ".axes.Axes" + qualname[9:]
  195. elif qualname.startswith("Figure."): # e.g. "Figure.figimage"
  196. link = "." + qualname
  197. elif qualname.startswith("FigureBase."): # e.g. "FigureBase.gca"
  198. link = ".Figure" + qualname[10:]
  199. elif qualname.startswith("FigureCanvasBase."): # "FigureBaseCanvas.mpl_connect"
  200. link = "." + qualname
  201. else:
  202. raise RuntimeError(f"Wrapped method from unexpected class: {qualname}")
  203. if wrapped_func_is_method:
  204. message = f"This is the :ref:`pyplot wrapper <pyplot_interface>` for `{link}`."
  205. else:
  206. message = f"This is equivalent to `{link}`."
  207. # Find the correct insert position:
  208. # - either we already have a "Notes" section into which we can insert
  209. # - or we create one before the next present section. Note that in numpydoc, the
  210. # "Notes" section is the third last possible section, only potentially followed
  211. # by "References" and "Examples".
  212. # - or we append a new "Notes" section at the end.
  213. doc = inspect.cleandoc(func.__doc__)
  214. if "\nNotes\n-----" in doc:
  215. before, after = doc.split("\nNotes\n-----", 1)
  216. elif (index := doc.find("\nReferences\n----------")) != -1:
  217. before, after = doc[:index], doc[index:]
  218. elif (index := doc.find("\nExamples\n--------")) != -1:
  219. before, after = doc[:index], doc[index:]
  220. else:
  221. # No "Notes", "References", or "Examples" --> append to the end.
  222. before = doc + "\n"
  223. after = ""
  224. func.__doc__ = f"{before}\nNotes\n-----\n\n.. note::\n\n {message}\n{after}"
  225. ## Global ##
  226. # The state controlled by {,un}install_repl_displayhook().
  227. _ReplDisplayHook = Enum("_ReplDisplayHook", ["NONE", "PLAIN", "IPYTHON"])
  228. _REPL_DISPLAYHOOK = _ReplDisplayHook.NONE
  229. def _draw_all_if_interactive() -> None:
  230. if matplotlib.is_interactive():
  231. draw_all()
  232. def install_repl_displayhook() -> None:
  233. """
  234. Connect to the display hook of the current shell.
  235. The display hook gets called when the read-evaluate-print-loop (REPL) of
  236. the shell has finished the execution of a command. We use this callback
  237. to be able to automatically update a figure in interactive mode.
  238. This works both with IPython and with vanilla python shells.
  239. """
  240. global _REPL_DISPLAYHOOK
  241. if _REPL_DISPLAYHOOK is _ReplDisplayHook.IPYTHON:
  242. return
  243. # See if we have IPython hooks around, if so use them.
  244. # Use ``sys.modules.get(name)`` rather than ``name in sys.modules`` as
  245. # entries can also have been explicitly set to None.
  246. mod_ipython = sys.modules.get("IPython")
  247. if not mod_ipython:
  248. _REPL_DISPLAYHOOK = _ReplDisplayHook.PLAIN
  249. return
  250. ip = mod_ipython.get_ipython()
  251. if not ip:
  252. _REPL_DISPLAYHOOK = _ReplDisplayHook.PLAIN
  253. return
  254. ip.events.register("post_execute", _draw_all_if_interactive)
  255. _REPL_DISPLAYHOOK = _ReplDisplayHook.IPYTHON
  256. if mod_ipython.version_info[:2] < (8, 24):
  257. # Use of backend2gui is not needed for IPython >= 8.24 as that functionality
  258. # has been moved to Matplotlib.
  259. # This code can be removed when Python 3.12, the latest version supported by
  260. # IPython < 8.24, reaches end-of-life in late 2028.
  261. from IPython.core.pylabtools import backend2gui
  262. ipython_gui_name = backend2gui.get(get_backend())
  263. else:
  264. _, ipython_gui_name = backend_registry.resolve_backend(get_backend())
  265. # trigger IPython's eventloop integration, if available
  266. if ipython_gui_name:
  267. ip.enable_gui(ipython_gui_name)
  268. def uninstall_repl_displayhook() -> None:
  269. """Disconnect from the display hook of the current shell."""
  270. global _REPL_DISPLAYHOOK
  271. if _REPL_DISPLAYHOOK is _ReplDisplayHook.IPYTHON:
  272. from IPython import get_ipython
  273. ip = get_ipython()
  274. ip.events.unregister("post_execute", _draw_all_if_interactive)
  275. _REPL_DISPLAYHOOK = _ReplDisplayHook.NONE
  276. draw_all = _pylab_helpers.Gcf.draw_all
  277. # Ensure this appears in the pyplot docs.
  278. @_copy_docstring_and_deprecators(matplotlib.set_loglevel)
  279. def set_loglevel(*args, **kwargs) -> None:
  280. return matplotlib.set_loglevel(*args, **kwargs)
  281. @_copy_docstring_and_deprecators(Artist.findobj)
  282. def findobj(
  283. o: Artist | None = None,
  284. match: Callable[[Artist], bool] | type[Artist] | None = None,
  285. include_self: bool = True
  286. ) -> list[Artist]:
  287. if o is None:
  288. o = gcf()
  289. return o.findobj(match, include_self=include_self)
  290. _backend_mod: type[matplotlib.backend_bases._Backend] | None = None
  291. def _get_backend_mod() -> type[matplotlib.backend_bases._Backend]:
  292. """
  293. Ensure that a backend is selected and return it.
  294. This is currently private, but may be made public in the future.
  295. """
  296. if _backend_mod is None:
  297. # Use rcParams._get("backend") to avoid going through the fallback
  298. # logic (which will (re)import pyplot and then call switch_backend if
  299. # we need to resolve the auto sentinel)
  300. switch_backend(rcParams._get("backend"))
  301. return cast(type[matplotlib.backend_bases._Backend], _backend_mod)
  302. def switch_backend(newbackend: str) -> None:
  303. """
  304. Set the pyplot backend.
  305. Switching to an interactive backend is possible only if no event loop for
  306. another interactive backend has started. Switching to and from
  307. non-interactive backends is always possible.
  308. If the new backend is different than the current backend then all open
  309. Figures will be closed via ``plt.close('all')``.
  310. Parameters
  311. ----------
  312. newbackend : str
  313. The case-insensitive name of the backend to use.
  314. """
  315. global _backend_mod
  316. # make sure the init is pulled up so we can assign to it later
  317. import matplotlib.backends
  318. if newbackend is rcsetup._auto_backend_sentinel:
  319. current_framework = cbook._get_running_interactive_framework()
  320. if (current_framework and
  321. (backend := backend_registry.backend_for_gui_framework(
  322. current_framework))):
  323. candidates = [backend]
  324. else:
  325. candidates = []
  326. candidates += [
  327. "macosx", "qtagg", "gtk4agg", "gtk3agg", "tkagg", "wxagg"]
  328. # Don't try to fallback on the cairo-based backends as they each have
  329. # an additional dependency (pycairo) over the agg-based backend, and
  330. # are of worse quality.
  331. for candidate in candidates:
  332. try:
  333. switch_backend(candidate)
  334. except ImportError:
  335. continue
  336. else:
  337. rcParamsOrig['backend'] = candidate
  338. return
  339. else:
  340. # Switching to Agg should always succeed; if it doesn't, let the
  341. # exception propagate out.
  342. switch_backend("agg")
  343. rcParamsOrig["backend"] = "agg"
  344. return
  345. old_backend = rcParams._get('backend') # get without triggering backend resolution
  346. module = backend_registry.load_backend_module(newbackend)
  347. canvas_class = module.FigureCanvas
  348. required_framework = canvas_class.required_interactive_framework
  349. if required_framework is not None:
  350. current_framework = cbook._get_running_interactive_framework()
  351. if (current_framework and required_framework
  352. and current_framework != required_framework):
  353. raise ImportError(
  354. "Cannot load backend {!r} which requires the {!r} interactive "
  355. "framework, as {!r} is currently running".format(
  356. newbackend, required_framework, current_framework))
  357. # Load the new_figure_manager() and show() functions from the backend.
  358. # Classically, backends can directly export these functions. This should
  359. # keep working for backcompat.
  360. new_figure_manager = getattr(module, "new_figure_manager", None)
  361. show = getattr(module, "show", None)
  362. # In that classical approach, backends are implemented as modules, but
  363. # "inherit" default method implementations from backend_bases._Backend.
  364. # This is achieved by creating a "class" that inherits from
  365. # backend_bases._Backend and whose body is filled with the module globals.
  366. class backend_mod(matplotlib.backend_bases._Backend):
  367. locals().update(vars(module))
  368. # However, the newer approach for defining new_figure_manager and
  369. # show is to derive them from canvas methods. In that case, also
  370. # update backend_mod accordingly; also, per-backend customization of
  371. # draw_if_interactive is disabled.
  372. if new_figure_manager is None:
  373. def new_figure_manager_given_figure(num, figure):
  374. return canvas_class.new_manager(figure, num)
  375. def new_figure_manager(num, *args, FigureClass=Figure, **kwargs):
  376. fig = FigureClass(*args, **kwargs)
  377. return new_figure_manager_given_figure(num, fig)
  378. def draw_if_interactive() -> None:
  379. if matplotlib.is_interactive():
  380. manager = _pylab_helpers.Gcf.get_active()
  381. if manager:
  382. manager.canvas.draw_idle()
  383. backend_mod.new_figure_manager_given_figure = ( # type: ignore[method-assign]
  384. new_figure_manager_given_figure)
  385. backend_mod.new_figure_manager = ( # type: ignore[method-assign]
  386. new_figure_manager)
  387. backend_mod.draw_if_interactive = ( # type: ignore[method-assign]
  388. draw_if_interactive)
  389. # If the manager explicitly overrides pyplot_show, use it even if a global
  390. # show is already present, as the latter may be here for backcompat.
  391. manager_class = getattr(canvas_class, "manager_class", None)
  392. # We can't compare directly manager_class.pyplot_show and FMB.pyplot_show because
  393. # pyplot_show is a classmethod so the above constructs are bound classmethods, and
  394. # thus always different (being bound to different classes). We also have to use
  395. # getattr_static instead of vars as manager_class could have no __dict__.
  396. manager_pyplot_show = inspect.getattr_static(manager_class, "pyplot_show", None)
  397. base_pyplot_show = inspect.getattr_static(FigureManagerBase, "pyplot_show", None)
  398. if (show is None
  399. or (manager_pyplot_show is not None
  400. and manager_pyplot_show != base_pyplot_show)):
  401. if not manager_pyplot_show:
  402. raise ValueError(
  403. f"Backend {newbackend} defines neither FigureCanvas.manager_class nor "
  404. f"a toplevel show function")
  405. _pyplot_show = cast('Any', manager_class).pyplot_show
  406. backend_mod.show = _pyplot_show # type: ignore[method-assign]
  407. _log.debug("Loaded backend %s version %s.",
  408. newbackend, backend_mod.backend_version)
  409. if newbackend in ("ipympl", "widget"):
  410. # ipympl < 0.9.4 expects rcParams["backend"] to be the fully-qualified backend
  411. # name "module://ipympl.backend_nbagg" not short names "ipympl" or "widget".
  412. import importlib.metadata as im
  413. from matplotlib import _parse_to_version_info # type: ignore[attr-defined]
  414. try:
  415. module_version = im.version("ipympl")
  416. if _parse_to_version_info(module_version) < (0, 9, 4):
  417. newbackend = "module://ipympl.backend_nbagg"
  418. except im.PackageNotFoundError:
  419. pass
  420. rcParams['backend'] = rcParamsDefault['backend'] = newbackend
  421. _backend_mod = backend_mod
  422. for func_name in ["new_figure_manager", "draw_if_interactive", "show"]:
  423. globals()[func_name].__signature__ = inspect.signature(
  424. getattr(backend_mod, func_name))
  425. # Need to keep a global reference to the backend for compatibility reasons.
  426. # See https://github.com/matplotlib/matplotlib/issues/6092
  427. matplotlib.backends.backend = newbackend # type: ignore[attr-defined]
  428. # Make sure the repl display hook is installed in case we become interactive.
  429. install_repl_displayhook()
  430. def _warn_if_gui_out_of_main_thread() -> None:
  431. warn = False
  432. canvas_class = cast(type[FigureCanvasBase], _get_backend_mod().FigureCanvas)
  433. if canvas_class.required_interactive_framework:
  434. if hasattr(threading, 'get_native_id'):
  435. # This compares native thread ids because even if Python-level
  436. # Thread objects match, the underlying OS thread (which is what
  437. # really matters) may be different on Python implementations with
  438. # green threads.
  439. if threading.get_native_id() != threading.main_thread().native_id:
  440. warn = True
  441. else:
  442. # Fall back to Python-level Thread if native IDs are unavailable,
  443. # mainly for PyPy.
  444. if threading.current_thread() is not threading.main_thread():
  445. warn = True
  446. if warn:
  447. _api.warn_external(
  448. "Starting a Matplotlib GUI outside of the main thread will likely "
  449. "fail.")
  450. # This function's signature is rewritten upon backend-load by switch_backend.
  451. def new_figure_manager(*args, **kwargs):
  452. """Create a new figure manager instance."""
  453. _warn_if_gui_out_of_main_thread()
  454. return _get_backend_mod().new_figure_manager(*args, **kwargs)
  455. # This function's signature is rewritten upon backend-load by switch_backend.
  456. def draw_if_interactive(*args, **kwargs):
  457. """
  458. Redraw the current figure if in interactive mode.
  459. .. warning::
  460. End users will typically not have to call this function because the
  461. the interactive mode takes care of this.
  462. """
  463. return _get_backend_mod().draw_if_interactive(*args, **kwargs)
  464. # This function's signature is rewritten upon backend-load by switch_backend.
  465. def show(*args, **kwargs) -> None:
  466. """
  467. Display all open figures.
  468. Parameters
  469. ----------
  470. block : bool, optional
  471. Whether to wait for all figures to be closed before returning.
  472. If `True` block and run the GUI main loop until all figure windows
  473. are closed.
  474. If `False` ensure that all figure windows are displayed and return
  475. immediately. In this case, you are responsible for ensuring
  476. that the event loop is running to have responsive figures.
  477. Defaults to True in non-interactive mode and to False in interactive
  478. mode (see `.pyplot.isinteractive`).
  479. See Also
  480. --------
  481. ion : Enable interactive mode, which shows / updates the figure after
  482. every plotting command, so that calling ``show()`` is not necessary.
  483. ioff : Disable interactive mode.
  484. savefig : Save the figure to an image file instead of showing it on screen.
  485. Notes
  486. -----
  487. **Saving figures to file and showing a window at the same time**
  488. If you want an image file as well as a user interface window, use
  489. `.pyplot.savefig` before `.pyplot.show`. At the end of (a blocking)
  490. ``show()`` the figure is closed and thus unregistered from pyplot. Calling
  491. `.pyplot.savefig` afterwards would save a new and thus empty figure. This
  492. limitation of command order does not apply if the show is non-blocking or
  493. if you keep a reference to the figure and use `.Figure.savefig`.
  494. **Auto-show in jupyter notebooks**
  495. The jupyter backends (activated via ``%matplotlib inline``,
  496. ``%matplotlib notebook``, or ``%matplotlib widget``), call ``show()`` at
  497. the end of every cell by default. Thus, you usually don't have to call it
  498. explicitly there.
  499. """
  500. _warn_if_gui_out_of_main_thread()
  501. return _get_backend_mod().show(*args, **kwargs)
  502. def isinteractive() -> bool:
  503. """
  504. Return whether plots are updated after every plotting command.
  505. The interactive mode is mainly useful if you build plots from the command
  506. line and want to see the effect of each command while you are building the
  507. figure.
  508. In interactive mode:
  509. - newly created figures will be shown immediately;
  510. - figures will automatically redraw on change;
  511. - `.pyplot.show` will not block by default.
  512. In non-interactive mode:
  513. - newly created figures and changes to figures will not be reflected until
  514. explicitly asked to be;
  515. - `.pyplot.show` will block by default.
  516. See Also
  517. --------
  518. ion : Enable interactive mode.
  519. ioff : Disable interactive mode.
  520. show : Show all figures (and maybe block).
  521. pause : Show all figures, and block for a time.
  522. """
  523. return matplotlib.is_interactive()
  524. # Note: The return type of ioff being AbstractContextManager
  525. # instead of ExitStack is deliberate.
  526. # See https://github.com/matplotlib/matplotlib/issues/27659
  527. # and https://github.com/matplotlib/matplotlib/pull/27667 for more info.
  528. def ioff() -> AbstractContextManager:
  529. """
  530. Disable interactive mode.
  531. See `.pyplot.isinteractive` for more details.
  532. See Also
  533. --------
  534. ion : Enable interactive mode.
  535. isinteractive : Whether interactive mode is enabled.
  536. show : Show all figures (and maybe block).
  537. pause : Show all figures, and block for a time.
  538. Notes
  539. -----
  540. For a temporary change, this can be used as a context manager::
  541. # if interactive mode is on
  542. # then figures will be shown on creation
  543. plt.ion()
  544. # This figure will be shown immediately
  545. fig = plt.figure()
  546. with plt.ioff():
  547. # interactive mode will be off
  548. # figures will not automatically be shown
  549. fig2 = plt.figure()
  550. # ...
  551. To enable optional usage as a context manager, this function returns a
  552. context manager object, which is not intended to be stored or
  553. accessed by the user.
  554. """
  555. stack = ExitStack()
  556. stack.callback(ion if isinteractive() else ioff)
  557. matplotlib.interactive(False)
  558. uninstall_repl_displayhook()
  559. return stack
  560. # Note: The return type of ion being AbstractContextManager
  561. # instead of ExitStack is deliberate.
  562. # See https://github.com/matplotlib/matplotlib/issues/27659
  563. # and https://github.com/matplotlib/matplotlib/pull/27667 for more info.
  564. def ion() -> AbstractContextManager:
  565. """
  566. Enable interactive mode.
  567. See `.pyplot.isinteractive` for more details.
  568. See Also
  569. --------
  570. ioff : Disable interactive mode.
  571. isinteractive : Whether interactive mode is enabled.
  572. show : Show all figures (and maybe block).
  573. pause : Show all figures, and block for a time.
  574. Notes
  575. -----
  576. For a temporary change, this can be used as a context manager::
  577. # if interactive mode is off
  578. # then figures will not be shown on creation
  579. plt.ioff()
  580. # This figure will not be shown immediately
  581. fig = plt.figure()
  582. with plt.ion():
  583. # interactive mode will be on
  584. # figures will automatically be shown
  585. fig2 = plt.figure()
  586. # ...
  587. To enable optional usage as a context manager, this function returns a
  588. context manager object, which is not intended to be stored or
  589. accessed by the user.
  590. """
  591. stack = ExitStack()
  592. stack.callback(ion if isinteractive() else ioff)
  593. matplotlib.interactive(True)
  594. install_repl_displayhook()
  595. return stack
  596. def pause(interval: float) -> None:
  597. """
  598. Run the GUI event loop for *interval* seconds.
  599. If there is an active figure, it will be updated and displayed before the
  600. pause, and the GUI event loop (if any) will run during the pause.
  601. This can be used for crude animation. For more complex animation use
  602. :mod:`matplotlib.animation`.
  603. If there is no active figure, sleep for *interval* seconds instead.
  604. See Also
  605. --------
  606. matplotlib.animation : Proper animations
  607. show : Show all figures and optional block until all figures are closed.
  608. """
  609. manager = _pylab_helpers.Gcf.get_active()
  610. if manager is not None:
  611. canvas = manager.canvas
  612. if canvas.figure.stale:
  613. canvas.draw_idle()
  614. show(block=False)
  615. canvas.start_event_loop(interval)
  616. else:
  617. time.sleep(interval)
  618. @_copy_docstring_and_deprecators(matplotlib.rc)
  619. def rc(group: str, **kwargs) -> None:
  620. matplotlib.rc(group, **kwargs)
  621. @_copy_docstring_and_deprecators(matplotlib.rc_context)
  622. def rc_context(
  623. rc: dict[str, Any] | None = None,
  624. fname: str | pathlib.Path | os.PathLike | None = None,
  625. ) -> AbstractContextManager[None]:
  626. return matplotlib.rc_context(rc, fname)
  627. @_copy_docstring_and_deprecators(matplotlib.rcdefaults)
  628. def rcdefaults() -> None:
  629. matplotlib.rcdefaults()
  630. if matplotlib.is_interactive():
  631. draw_all()
  632. # getp/get/setp are explicitly reexported so that they show up in pyplot docs.
  633. @_copy_docstring_and_deprecators(matplotlib.artist.getp)
  634. def getp(obj, *args, **kwargs):
  635. return matplotlib.artist.getp(obj, *args, **kwargs)
  636. @_copy_docstring_and_deprecators(matplotlib.artist.get)
  637. def get(obj, *args, **kwargs):
  638. return matplotlib.artist.get(obj, *args, **kwargs)
  639. @_copy_docstring_and_deprecators(matplotlib.artist.setp)
  640. def setp(obj, *args, **kwargs):
  641. return matplotlib.artist.setp(obj, *args, **kwargs)
  642. def xkcd(
  643. scale: float = 1, length: float = 100, randomness: float = 2
  644. ) -> ExitStack:
  645. """
  646. Turn on `xkcd <https://xkcd.com/>`_ sketch-style drawing mode.
  647. This will only have an effect on things drawn after this function is called.
  648. For best results, install the `xkcd script <https://github.com/ipython/xkcd-font/>`_
  649. font; xkcd fonts are not packaged with Matplotlib.
  650. Parameters
  651. ----------
  652. scale : float, optional
  653. The amplitude of the wiggle perpendicular to the source line.
  654. length : float, optional
  655. The length of the wiggle along the line.
  656. randomness : float, optional
  657. The scale factor by which the length is shrunken or expanded.
  658. Notes
  659. -----
  660. This function works by a number of rcParams, so it will probably
  661. override others you have set before.
  662. If you want the effects of this function to be temporary, it can
  663. be used as a context manager, for example::
  664. with plt.xkcd():
  665. # This figure will be in XKCD-style
  666. fig1 = plt.figure()
  667. # ...
  668. # This figure will be in regular style
  669. fig2 = plt.figure()
  670. """
  671. # This cannot be implemented in terms of contextmanager() or rc_context()
  672. # because this needs to work as a non-contextmanager too.
  673. if rcParams['text.usetex']:
  674. raise RuntimeError(
  675. "xkcd mode is not compatible with text.usetex = True")
  676. stack = ExitStack()
  677. stack.callback(rcParams._update_raw, rcParams.copy()) # type: ignore[arg-type]
  678. from matplotlib import patheffects
  679. rcParams.update({
  680. 'font.family': ['xkcd', 'xkcd Script', 'Comic Neue', 'Comic Sans MS'],
  681. 'font.size': 14.0,
  682. 'path.sketch': (scale, length, randomness),
  683. 'path.effects': [
  684. patheffects.withStroke(linewidth=4, foreground="w")],
  685. 'axes.linewidth': 1.5,
  686. 'lines.linewidth': 2.0,
  687. 'figure.facecolor': 'white',
  688. 'grid.linewidth': 0.0,
  689. 'axes.grid': False,
  690. 'axes.unicode_minus': False,
  691. 'axes.edgecolor': 'black',
  692. 'xtick.major.size': 8,
  693. 'xtick.major.width': 3,
  694. 'ytick.major.size': 8,
  695. 'ytick.major.width': 3,
  696. })
  697. return stack
  698. ## Figures ##
  699. def figure(
  700. # autoincrement if None, else integer from 1-N
  701. num: int | str | Figure | SubFigure | None = None,
  702. # defaults to rc figure.figsize
  703. figsize: ArrayLike | None = None,
  704. # defaults to rc figure.dpi
  705. dpi: float | None = None,
  706. *,
  707. # defaults to rc figure.facecolor
  708. facecolor: ColorType | None = None,
  709. # defaults to rc figure.edgecolor
  710. edgecolor: ColorType | None = None,
  711. frameon: bool = True,
  712. FigureClass: type[Figure] = Figure,
  713. clear: bool = False,
  714. **kwargs
  715. ) -> Figure:
  716. """
  717. Create a new figure, or activate an existing figure.
  718. Parameters
  719. ----------
  720. num : int or str or `.Figure` or `.SubFigure`, optional
  721. A unique identifier for the figure.
  722. If a figure with that identifier already exists, this figure is made
  723. active and returned. An integer refers to the ``Figure.number``
  724. attribute, a string refers to the figure label.
  725. If there is no figure with the identifier or *num* is not given, a new
  726. figure is created, made active and returned. If *num* is an int, it
  727. will be used for the ``Figure.number`` attribute, otherwise, an
  728. auto-generated integer value is used (starting at 1 and incremented
  729. for each new figure). If *num* is a string, the figure label and the
  730. window title is set to this value. If num is a ``SubFigure``, its
  731. parent ``Figure`` is activated.
  732. figsize : (float, float), default: :rc:`figure.figsize`
  733. Width, height in inches.
  734. dpi : float, default: :rc:`figure.dpi`
  735. The resolution of the figure in dots-per-inch.
  736. facecolor : :mpltype:`color`, default: :rc:`figure.facecolor`
  737. The background color.
  738. edgecolor : :mpltype:`color`, default: :rc:`figure.edgecolor`
  739. The border color.
  740. frameon : bool, default: True
  741. If False, suppress drawing the figure frame.
  742. FigureClass : subclass of `~matplotlib.figure.Figure`
  743. If set, an instance of this subclass will be created, rather than a
  744. plain `.Figure`.
  745. clear : bool, default: False
  746. If True and the figure already exists, then it is cleared.
  747. layout : {'constrained', 'compressed', 'tight', 'none', `.LayoutEngine`, None}, \
  748. default: None
  749. The layout mechanism for positioning of plot elements to avoid
  750. overlapping Axes decorations (labels, ticks, etc). Note that layout
  751. managers can measurably slow down figure display.
  752. - 'constrained': The constrained layout solver adjusts Axes sizes
  753. to avoid overlapping Axes decorations. Can handle complex plot
  754. layouts and colorbars, and is thus recommended.
  755. See :ref:`constrainedlayout_guide`
  756. for examples.
  757. - 'compressed': uses the same algorithm as 'constrained', but
  758. removes extra space between fixed-aspect-ratio Axes. Best for
  759. simple grids of Axes.
  760. - 'tight': Use the tight layout mechanism. This is a relatively
  761. simple algorithm that adjusts the subplot parameters so that
  762. decorations do not overlap. See `.Figure.set_tight_layout` for
  763. further details.
  764. - 'none': Do not use a layout engine.
  765. - A `.LayoutEngine` instance. Builtin layout classes are
  766. `.ConstrainedLayoutEngine` and `.TightLayoutEngine`, more easily
  767. accessible by 'constrained' and 'tight'. Passing an instance
  768. allows third parties to provide their own layout engine.
  769. If not given, fall back to using the parameters *tight_layout* and
  770. *constrained_layout*, including their config defaults
  771. :rc:`figure.autolayout` and :rc:`figure.constrained_layout.use`.
  772. **kwargs
  773. Additional keyword arguments are passed to the `.Figure` constructor.
  774. Returns
  775. -------
  776. `~matplotlib.figure.Figure`
  777. Notes
  778. -----
  779. A newly created figure is passed to the `~.FigureCanvasBase.new_manager`
  780. method or the `new_figure_manager` function provided by the current
  781. backend, which install a canvas and a manager on the figure.
  782. Once this is done, :rc:`figure.hooks` are called, one at a time, on the
  783. figure; these hooks allow arbitrary customization of the figure (e.g.,
  784. attaching callbacks) or of associated elements (e.g., modifying the
  785. toolbar). See :doc:`/gallery/user_interfaces/mplcvd` for an example of
  786. toolbar customization.
  787. If you are creating many figures, make sure you explicitly call
  788. `.pyplot.close` on the figures you are not using, because this will
  789. enable pyplot to properly clean up the memory.
  790. `~matplotlib.rcParams` defines the default values, which can be modified
  791. in the matplotlibrc file.
  792. """
  793. allnums = get_fignums()
  794. if isinstance(num, FigureBase):
  795. # type narrowed to `Figure | SubFigure` by combination of input and isinstance
  796. root_fig = num.get_figure(root=True)
  797. if root_fig.canvas.manager is None:
  798. raise ValueError("The passed figure is not managed by pyplot")
  799. elif (any(param is not None for param in [figsize, dpi, facecolor, edgecolor])
  800. or not frameon or kwargs) and root_fig.canvas.manager.num in allnums:
  801. _api.warn_external(
  802. "Ignoring specified arguments in this call because figure "
  803. f"with num: {root_fig.canvas.manager.num} already exists")
  804. _pylab_helpers.Gcf.set_active(root_fig.canvas.manager)
  805. return root_fig
  806. next_num = max(allnums) + 1 if allnums else 1
  807. fig_label = ''
  808. if num is None:
  809. num = next_num
  810. else:
  811. if (any(param is not None for param in [figsize, dpi, facecolor, edgecolor])
  812. or not frameon or kwargs) and num in allnums:
  813. _api.warn_external(
  814. "Ignoring specified arguments in this call "
  815. f"because figure with num: {num} already exists")
  816. if isinstance(num, str):
  817. fig_label = num
  818. all_labels = get_figlabels()
  819. if fig_label not in all_labels:
  820. if fig_label == 'all':
  821. _api.warn_external("close('all') closes all existing figures.")
  822. num = next_num
  823. else:
  824. inum = all_labels.index(fig_label)
  825. num = allnums[inum]
  826. else:
  827. num = int(num) # crude validation of num argument
  828. # Type of "num" has narrowed to int, but mypy can't quite see it
  829. manager = _pylab_helpers.Gcf.get_fig_manager(num) # type: ignore[arg-type]
  830. if manager is None:
  831. max_open_warning = rcParams['figure.max_open_warning']
  832. if len(allnums) == max_open_warning >= 1:
  833. _api.warn_external(
  834. f"More than {max_open_warning} figures have been opened. "
  835. f"Figures created through the pyplot interface "
  836. f"(`matplotlib.pyplot.figure`) are retained until explicitly "
  837. f"closed and may consume too much memory. (To control this "
  838. f"warning, see the rcParam `figure.max_open_warning`). "
  839. f"Consider using `matplotlib.pyplot.close()`.",
  840. RuntimeWarning)
  841. manager = new_figure_manager(
  842. num, figsize=figsize, dpi=dpi,
  843. facecolor=facecolor, edgecolor=edgecolor, frameon=frameon,
  844. FigureClass=FigureClass, **kwargs)
  845. fig = manager.canvas.figure
  846. if fig_label:
  847. fig.set_label(fig_label)
  848. for hookspecs in rcParams["figure.hooks"]:
  849. module_name, dotted_name = hookspecs.split(":")
  850. obj: Any = importlib.import_module(module_name)
  851. for part in dotted_name.split("."):
  852. obj = getattr(obj, part)
  853. obj(fig)
  854. _pylab_helpers.Gcf._set_new_active_manager(manager)
  855. # make sure backends (inline) that we don't ship that expect this
  856. # to be called in plotting commands to make the figure call show
  857. # still work. There is probably a better way to do this in the
  858. # FigureManager base class.
  859. draw_if_interactive()
  860. if _REPL_DISPLAYHOOK is _ReplDisplayHook.PLAIN:
  861. fig.stale_callback = _auto_draw_if_interactive
  862. if clear:
  863. manager.canvas.figure.clear()
  864. return manager.canvas.figure
  865. def _auto_draw_if_interactive(fig, val):
  866. """
  867. An internal helper function for making sure that auto-redrawing
  868. works as intended in the plain python repl.
  869. Parameters
  870. ----------
  871. fig : Figure
  872. A figure object which is assumed to be associated with a canvas
  873. """
  874. if (val and matplotlib.is_interactive()
  875. and not fig.canvas.is_saving()
  876. and not fig.canvas._is_idle_drawing):
  877. # Some artists can mark themselves as stale in the middle of drawing
  878. # (e.g. axes position & tick labels being computed at draw time), but
  879. # this shouldn't trigger a redraw because the current redraw will
  880. # already take them into account.
  881. with fig.canvas._idle_draw_cntx():
  882. fig.canvas.draw_idle()
  883. def gcf() -> Figure:
  884. """
  885. Get the current figure.
  886. If there is currently no figure on the pyplot figure stack, a new one is
  887. created using `~.pyplot.figure()`. (To test whether there is currently a
  888. figure on the pyplot figure stack, check whether `~.pyplot.get_fignums()`
  889. is empty.)
  890. """
  891. manager = _pylab_helpers.Gcf.get_active()
  892. if manager is not None:
  893. return manager.canvas.figure
  894. else:
  895. return figure()
  896. def fignum_exists(num: int | str) -> bool:
  897. """
  898. Return whether the figure with the given id exists.
  899. Parameters
  900. ----------
  901. num : int or str
  902. A figure identifier.
  903. Returns
  904. -------
  905. bool
  906. Whether or not a figure with id *num* exists.
  907. """
  908. return (
  909. _pylab_helpers.Gcf.has_fignum(num)
  910. if isinstance(num, int)
  911. else num in get_figlabels()
  912. )
  913. def get_fignums() -> list[int]:
  914. """Return a list of existing figure numbers."""
  915. return sorted(_pylab_helpers.Gcf.figs)
  916. def get_figlabels() -> list[Any]:
  917. """Return a list of existing figure labels."""
  918. managers = _pylab_helpers.Gcf.get_all_fig_managers()
  919. managers.sort(key=lambda m: m.num)
  920. return [m.canvas.figure.get_label() for m in managers]
  921. def get_current_fig_manager() -> FigureManagerBase | None:
  922. """
  923. Return the figure manager of the current figure.
  924. The figure manager is a container for the actual backend-depended window
  925. that displays the figure on screen.
  926. If no current figure exists, a new one is created, and its figure
  927. manager is returned.
  928. Returns
  929. -------
  930. `.FigureManagerBase` or backend-dependent subclass thereof
  931. """
  932. return gcf().canvas.manager
  933. @_copy_docstring_and_deprecators(FigureCanvasBase.mpl_connect)
  934. def connect(s: str, func: Callable[[Event], Any]) -> int:
  935. return gcf().canvas.mpl_connect(s, func)
  936. @_copy_docstring_and_deprecators(FigureCanvasBase.mpl_disconnect)
  937. def disconnect(cid: int) -> None:
  938. gcf().canvas.mpl_disconnect(cid)
  939. def close(fig: None | int | str | Figure | Literal["all"] = None) -> None:
  940. """
  941. Close a figure window, and unregister it from pyplot.
  942. Parameters
  943. ----------
  944. fig : None or int or str or `.Figure`
  945. The figure to close. There are a number of ways to specify this:
  946. - *None*: the current figure
  947. - `.Figure`: the given `.Figure` instance
  948. - ``int``: a figure number
  949. - ``str``: a figure name
  950. - 'all': all figures
  951. Notes
  952. -----
  953. pyplot maintains a reference to figures created with `figure()`. When
  954. work on the figure is completed, it should be closed, i.e. deregistered
  955. from pyplot, to free its memory (see also :rc:figure.max_open_warning).
  956. Closing a figure window created by `show()` automatically deregisters the
  957. figure. For all other use cases, most prominently `savefig()` without
  958. `show()`, the figure must be deregistered explicitly using `close()`.
  959. """
  960. if fig is None:
  961. manager = _pylab_helpers.Gcf.get_active()
  962. if manager is None:
  963. return
  964. else:
  965. _pylab_helpers.Gcf.destroy(manager)
  966. elif fig == 'all':
  967. _pylab_helpers.Gcf.destroy_all()
  968. elif isinstance(fig, int):
  969. _pylab_helpers.Gcf.destroy(fig)
  970. elif hasattr(fig, 'int'):
  971. # if we are dealing with a type UUID, we
  972. # can use its integer representation
  973. _pylab_helpers.Gcf.destroy(fig.int)
  974. elif isinstance(fig, str):
  975. all_labels = get_figlabels()
  976. if fig in all_labels:
  977. num = get_fignums()[all_labels.index(fig)]
  978. _pylab_helpers.Gcf.destroy(num)
  979. elif isinstance(fig, Figure):
  980. _pylab_helpers.Gcf.destroy_fig(fig)
  981. else:
  982. raise TypeError("close() argument must be a Figure, an int, a string, "
  983. "or None, not %s" % type(fig))
  984. def clf() -> None:
  985. """Clear the current figure."""
  986. gcf().clear()
  987. def draw() -> None:
  988. """
  989. Redraw the current figure.
  990. This is used to update a figure that has been altered, but not
  991. automatically re-drawn. If interactive mode is on (via `.ion()`), this
  992. should be only rarely needed, but there may be ways to modify the state of
  993. a figure without marking it as "stale". Please report these cases as bugs.
  994. This is equivalent to calling ``fig.canvas.draw_idle()``, where ``fig`` is
  995. the current figure.
  996. See Also
  997. --------
  998. .FigureCanvasBase.draw_idle
  999. .FigureCanvasBase.draw
  1000. """
  1001. gcf().canvas.draw_idle()
  1002. @_copy_docstring_and_deprecators(Figure.savefig)
  1003. def savefig(*args, **kwargs) -> None:
  1004. fig = gcf()
  1005. # savefig default implementation has no return, so mypy is unhappy
  1006. # presumably this is here because subclasses can return?
  1007. res = fig.savefig(*args, **kwargs) # type: ignore[func-returns-value]
  1008. fig.canvas.draw_idle() # Need this if 'transparent=True', to reset colors.
  1009. return res
  1010. ## Putting things in figures ##
  1011. def figlegend(*args, **kwargs) -> Legend:
  1012. return gcf().legend(*args, **kwargs)
  1013. if Figure.legend.__doc__:
  1014. figlegend.__doc__ = Figure.legend.__doc__ \
  1015. .replace(" legend(", " figlegend(") \
  1016. .replace("fig.legend(", "plt.figlegend(") \
  1017. .replace("ax.plot(", "plt.plot(")
  1018. ## Axes ##
  1019. @_docstring.interpd
  1020. def axes(
  1021. arg: None | tuple[float, float, float, float] = None,
  1022. **kwargs
  1023. ) -> matplotlib.axes.Axes:
  1024. """
  1025. Add an Axes to the current figure and make it the current Axes.
  1026. Call signatures::
  1027. plt.axes()
  1028. plt.axes(rect, projection=None, polar=False, **kwargs)
  1029. plt.axes(ax)
  1030. Parameters
  1031. ----------
  1032. arg : None or 4-tuple
  1033. The exact behavior of this function depends on the type:
  1034. - *None*: A new full window Axes is added using
  1035. ``subplot(**kwargs)``.
  1036. - 4-tuple of floats *rect* = ``(left, bottom, width, height)``.
  1037. A new Axes is added with dimensions *rect* in normalized
  1038. (0, 1) units using `~.Figure.add_axes` on the current figure.
  1039. projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
  1040. 'polar', 'rectilinear', str}, optional
  1041. The projection type of the `~.axes.Axes`. *str* is the name of
  1042. a custom projection, see `~matplotlib.projections`. The default
  1043. None results in a 'rectilinear' projection.
  1044. polar : bool, default: False
  1045. If True, equivalent to projection='polar'.
  1046. sharex, sharey : `~matplotlib.axes.Axes`, optional
  1047. Share the x or y `~matplotlib.axis` with sharex and/or sharey.
  1048. The axis will have the same limits, ticks, and scale as the axis
  1049. of the shared Axes.
  1050. label : str
  1051. A label for the returned Axes.
  1052. Returns
  1053. -------
  1054. `~.axes.Axes`, or a subclass of `~.axes.Axes`
  1055. The returned Axes class depends on the projection used. It is
  1056. `~.axes.Axes` if rectilinear projection is used and
  1057. `.projections.polar.PolarAxes` if polar projection is used.
  1058. Other Parameters
  1059. ----------------
  1060. **kwargs
  1061. This method also takes the keyword arguments for
  1062. the returned Axes class. The keyword arguments for the
  1063. rectilinear Axes class `~.axes.Axes` can be found in
  1064. the following table but there might also be other keyword
  1065. arguments if another projection is used, see the actual Axes
  1066. class.
  1067. %(Axes:kwdoc)s
  1068. See Also
  1069. --------
  1070. .Figure.add_axes
  1071. .pyplot.subplot
  1072. .Figure.add_subplot
  1073. .Figure.subplots
  1074. .pyplot.subplots
  1075. Examples
  1076. --------
  1077. ::
  1078. # Creating a new full window Axes
  1079. plt.axes()
  1080. # Creating a new Axes with specified dimensions and a grey background
  1081. plt.axes((left, bottom, width, height), facecolor='grey')
  1082. """
  1083. fig = gcf()
  1084. pos = kwargs.pop('position', None)
  1085. if arg is None:
  1086. if pos is None:
  1087. return fig.add_subplot(**kwargs)
  1088. else:
  1089. return fig.add_axes(pos, **kwargs)
  1090. else:
  1091. return fig.add_axes(arg, **kwargs)
  1092. def delaxes(ax: matplotlib.axes.Axes | None = None) -> None:
  1093. """
  1094. Remove an `~.axes.Axes` (defaulting to the current Axes) from its figure.
  1095. """
  1096. if ax is None:
  1097. ax = gca()
  1098. ax.remove()
  1099. def sca(ax: Axes) -> None:
  1100. """
  1101. Set the current Axes to *ax* and the current Figure to the parent of *ax*.
  1102. """
  1103. # Mypy sees ax.figure as potentially None,
  1104. # but if you are calling this, it won't be None
  1105. # Additionally the slight difference between `Figure` and `FigureBase` mypy catches
  1106. fig = ax.get_figure(root=False)
  1107. figure(fig) # type: ignore[arg-type]
  1108. fig.sca(ax) # type: ignore[union-attr]
  1109. def cla() -> None:
  1110. """Clear the current Axes."""
  1111. # Not generated via boilerplate.py to allow a different docstring.
  1112. return gca().cla()
  1113. ## More ways of creating Axes ##
  1114. @_docstring.interpd
  1115. def subplot(*args, **kwargs) -> Axes:
  1116. """
  1117. Add an Axes to the current figure or retrieve an existing Axes.
  1118. This is a wrapper of `.Figure.add_subplot` which provides additional
  1119. behavior when working with the implicit API (see the notes section).
  1120. Call signatures::
  1121. subplot(nrows, ncols, index, **kwargs)
  1122. subplot(pos, **kwargs)
  1123. subplot(**kwargs)
  1124. subplot(ax)
  1125. Parameters
  1126. ----------
  1127. *args : int, (int, int, *index*), or `.SubplotSpec`, default: (1, 1, 1)
  1128. The position of the subplot described by one of
  1129. - Three integers (*nrows*, *ncols*, *index*). The subplot will take the
  1130. *index* position on a grid with *nrows* rows and *ncols* columns.
  1131. *index* starts at 1 in the upper left corner and increases to the
  1132. right. *index* can also be a two-tuple specifying the (*first*,
  1133. *last*) indices (1-based, and including *last*) of the subplot, e.g.,
  1134. ``fig.add_subplot(3, 1, (1, 2))`` makes a subplot that spans the
  1135. upper 2/3 of the figure.
  1136. - A 3-digit integer. The digits are interpreted as if given separately
  1137. as three single-digit integers, i.e. ``fig.add_subplot(235)`` is the
  1138. same as ``fig.add_subplot(2, 3, 5)``. Note that this can only be used
  1139. if there are no more than 9 subplots.
  1140. - A `.SubplotSpec`.
  1141. projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
  1142. 'polar', 'rectilinear', str}, optional
  1143. The projection type of the subplot (`~.axes.Axes`). *str* is the name
  1144. of a custom projection, see `~matplotlib.projections`. The default
  1145. None results in a 'rectilinear' projection.
  1146. polar : bool, default: False
  1147. If True, equivalent to projection='polar'.
  1148. sharex, sharey : `~matplotlib.axes.Axes`, optional
  1149. Share the x or y `~matplotlib.axis` with sharex and/or sharey. The
  1150. axis will have the same limits, ticks, and scale as the axis of the
  1151. shared Axes.
  1152. label : str
  1153. A label for the returned Axes.
  1154. Returns
  1155. -------
  1156. `~.axes.Axes`
  1157. The Axes of the subplot. The returned Axes can actually be an instance
  1158. of a subclass, such as `.projections.polar.PolarAxes` for polar
  1159. projections.
  1160. Other Parameters
  1161. ----------------
  1162. **kwargs
  1163. This method also takes the keyword arguments for the returned Axes
  1164. base class; except for the *figure* argument. The keyword arguments
  1165. for the rectilinear base class `~.axes.Axes` can be found in
  1166. the following table but there might also be other keyword
  1167. arguments if another projection is used.
  1168. %(Axes:kwdoc)s
  1169. Notes
  1170. -----
  1171. .. versionchanged:: 3.8
  1172. In versions prior to 3.8, any preexisting Axes that overlap with the new Axes
  1173. beyond sharing a boundary was deleted. Deletion does not happen in more
  1174. recent versions anymore. Use `.Axes.remove` explicitly if needed.
  1175. If you do not want this behavior, use the `.Figure.add_subplot` method
  1176. or the `.pyplot.axes` function instead.
  1177. If no *kwargs* are passed and there exists an Axes in the location
  1178. specified by *args* then that Axes will be returned rather than a new
  1179. Axes being created.
  1180. If *kwargs* are passed and there exists an Axes in the location
  1181. specified by *args*, the projection type is the same, and the
  1182. *kwargs* match with the existing Axes, then the existing Axes is
  1183. returned. Otherwise a new Axes is created with the specified
  1184. parameters. We save a reference to the *kwargs* which we use
  1185. for this comparison. If any of the values in *kwargs* are
  1186. mutable we will not detect the case where they are mutated.
  1187. In these cases we suggest using `.Figure.add_subplot` and the
  1188. explicit Axes API rather than the implicit pyplot API.
  1189. See Also
  1190. --------
  1191. .Figure.add_subplot
  1192. .pyplot.subplots
  1193. .pyplot.axes
  1194. .Figure.subplots
  1195. Examples
  1196. --------
  1197. ::
  1198. plt.subplot(221)
  1199. # equivalent but more general
  1200. ax1 = plt.subplot(2, 2, 1)
  1201. # add a subplot with no frame
  1202. ax2 = plt.subplot(222, frameon=False)
  1203. # add a polar subplot
  1204. plt.subplot(223, projection='polar')
  1205. # add a red subplot that shares the x-axis with ax1
  1206. plt.subplot(224, sharex=ax1, facecolor='red')
  1207. # delete ax2 from the figure
  1208. plt.delaxes(ax2)
  1209. # add ax2 to the figure again
  1210. plt.subplot(ax2)
  1211. # make the first Axes "current" again
  1212. plt.subplot(221)
  1213. """
  1214. # Here we will only normalize `polar=True` vs `projection='polar'` and let
  1215. # downstream code deal with the rest.
  1216. unset = object()
  1217. projection = kwargs.get('projection', unset)
  1218. polar = kwargs.pop('polar', unset)
  1219. if polar is not unset and polar:
  1220. # if we got mixed messages from the user, raise
  1221. if projection is not unset and projection != 'polar':
  1222. raise ValueError(
  1223. f"polar={polar}, yet projection={projection!r}. "
  1224. "Only one of these arguments should be supplied."
  1225. )
  1226. kwargs['projection'] = projection = 'polar'
  1227. # if subplot called without arguments, create subplot(1, 1, 1)
  1228. if len(args) == 0:
  1229. args = (1, 1, 1)
  1230. # This check was added because it is very easy to type subplot(1, 2, False)
  1231. # when subplots(1, 2, False) was intended (sharex=False, that is). In most
  1232. # cases, no error will ever occur, but mysterious behavior can result
  1233. # because what was intended to be the sharex argument is instead treated as
  1234. # a subplot index for subplot()
  1235. if len(args) >= 3 and isinstance(args[2], bool):
  1236. _api.warn_external("The subplot index argument to subplot() appears "
  1237. "to be a boolean. Did you intend to use "
  1238. "subplots()?")
  1239. # Check for nrows and ncols, which are not valid subplot args:
  1240. if 'nrows' in kwargs or 'ncols' in kwargs:
  1241. raise TypeError("subplot() got an unexpected keyword argument 'ncols' "
  1242. "and/or 'nrows'. Did you intend to call subplots()?")
  1243. fig = gcf()
  1244. # First, search for an existing subplot with a matching spec.
  1245. key = SubplotSpec._from_subplot_args(fig, args)
  1246. for ax in fig.axes:
  1247. # If we found an Axes at the position, we can reuse it if the user passed no
  1248. # kwargs or if the Axes class and kwargs are identical.
  1249. if (ax.get_subplotspec() == key
  1250. and (kwargs == {}
  1251. or (ax._projection_init
  1252. == fig._process_projection_requirements(**kwargs)))):
  1253. break
  1254. else:
  1255. # we have exhausted the known Axes and none match, make a new one!
  1256. ax = fig.add_subplot(*args, **kwargs)
  1257. fig.sca(ax)
  1258. return ax
  1259. @overload
  1260. def subplots(
  1261. nrows: Literal[1] = ...,
  1262. ncols: Literal[1] = ...,
  1263. *,
  1264. sharex: bool | Literal["none", "all", "row", "col"] = ...,
  1265. sharey: bool | Literal["none", "all", "row", "col"] = ...,
  1266. squeeze: Literal[True] = ...,
  1267. width_ratios: Sequence[float] | None = ...,
  1268. height_ratios: Sequence[float] | None = ...,
  1269. subplot_kw: dict[str, Any] | None = ...,
  1270. gridspec_kw: dict[str, Any] | None = ...,
  1271. **fig_kw
  1272. ) -> tuple[Figure, Axes]:
  1273. ...
  1274. @overload
  1275. def subplots(
  1276. nrows: int = ...,
  1277. ncols: int = ...,
  1278. *,
  1279. sharex: bool | Literal["none", "all", "row", "col"] = ...,
  1280. sharey: bool | Literal["none", "all", "row", "col"] = ...,
  1281. squeeze: Literal[False],
  1282. width_ratios: Sequence[float] | None = ...,
  1283. height_ratios: Sequence[float] | None = ...,
  1284. subplot_kw: dict[str, Any] | None = ...,
  1285. gridspec_kw: dict[str, Any] | None = ...,
  1286. **fig_kw
  1287. ) -> tuple[Figure, np.ndarray]: # TODO numpy/numpy#24738
  1288. ...
  1289. @overload
  1290. def subplots(
  1291. nrows: int = ...,
  1292. ncols: int = ...,
  1293. *,
  1294. sharex: bool | Literal["none", "all", "row", "col"] = ...,
  1295. sharey: bool | Literal["none", "all", "row", "col"] = ...,
  1296. squeeze: bool = ...,
  1297. width_ratios: Sequence[float] | None = ...,
  1298. height_ratios: Sequence[float] | None = ...,
  1299. subplot_kw: dict[str, Any] | None = ...,
  1300. gridspec_kw: dict[str, Any] | None = ...,
  1301. **fig_kw
  1302. ) -> tuple[Figure, Any]:
  1303. ...
  1304. def subplots(
  1305. nrows: int = 1, ncols: int = 1, *,
  1306. sharex: bool | Literal["none", "all", "row", "col"] = False,
  1307. sharey: bool | Literal["none", "all", "row", "col"] = False,
  1308. squeeze: bool = True,
  1309. width_ratios: Sequence[float] | None = None,
  1310. height_ratios: Sequence[float] | None = None,
  1311. subplot_kw: dict[str, Any] | None = None,
  1312. gridspec_kw: dict[str, Any] | None = None,
  1313. **fig_kw
  1314. ) -> tuple[Figure, Any]:
  1315. """
  1316. Create a figure and a set of subplots.
  1317. This utility wrapper makes it convenient to create common layouts of
  1318. subplots, including the enclosing figure object, in a single call.
  1319. Parameters
  1320. ----------
  1321. nrows, ncols : int, default: 1
  1322. Number of rows/columns of the subplot grid.
  1323. sharex, sharey : bool or {'none', 'all', 'row', 'col'}, default: False
  1324. Controls sharing of properties among x (*sharex*) or y (*sharey*)
  1325. axes:
  1326. - True or 'all': x- or y-axis will be shared among all subplots.
  1327. - False or 'none': each subplot x- or y-axis will be independent.
  1328. - 'row': each subplot row will share an x- or y-axis.
  1329. - 'col': each subplot column will share an x- or y-axis.
  1330. When subplots have a shared x-axis along a column, only the x tick
  1331. labels of the bottom subplot are created. Similarly, when subplots
  1332. have a shared y-axis along a row, only the y tick labels of the first
  1333. column subplot are created. To later turn other subplots' ticklabels
  1334. on, use `~matplotlib.axes.Axes.tick_params`.
  1335. When subplots have a shared axis that has units, calling
  1336. `.Axis.set_units` will update each axis with the new units.
  1337. Note that it is not possible to unshare axes.
  1338. squeeze : bool, default: True
  1339. - If True, extra dimensions are squeezed out from the returned
  1340. array of `~matplotlib.axes.Axes`:
  1341. - if only one subplot is constructed (nrows=ncols=1), the
  1342. resulting single Axes object is returned as a scalar.
  1343. - for Nx1 or 1xM subplots, the returned object is a 1D numpy
  1344. object array of Axes objects.
  1345. - for NxM, subplots with N>1 and M>1 are returned as a 2D array.
  1346. - If False, no squeezing at all is done: the returned Axes object is
  1347. always a 2D array containing Axes instances, even if it ends up
  1348. being 1x1.
  1349. width_ratios : array-like of length *ncols*, optional
  1350. Defines the relative widths of the columns. Each column gets a
  1351. relative width of ``width_ratios[i] / sum(width_ratios)``.
  1352. If not given, all columns will have the same width. Equivalent
  1353. to ``gridspec_kw={'width_ratios': [...]}``.
  1354. height_ratios : array-like of length *nrows*, optional
  1355. Defines the relative heights of the rows. Each row gets a
  1356. relative height of ``height_ratios[i] / sum(height_ratios)``.
  1357. If not given, all rows will have the same height. Convenience
  1358. for ``gridspec_kw={'height_ratios': [...]}``.
  1359. subplot_kw : dict, optional
  1360. Dict with keywords passed to the
  1361. `~matplotlib.figure.Figure.add_subplot` call used to create each
  1362. subplot.
  1363. gridspec_kw : dict, optional
  1364. Dict with keywords passed to the `~matplotlib.gridspec.GridSpec`
  1365. constructor used to create the grid the subplots are placed on.
  1366. **fig_kw
  1367. All additional keyword arguments are passed to the
  1368. `.pyplot.figure` call.
  1369. Returns
  1370. -------
  1371. fig : `.Figure`
  1372. ax : `~matplotlib.axes.Axes` or array of Axes
  1373. *ax* can be either a single `~.axes.Axes` object, or an array of Axes
  1374. objects if more than one subplot was created. The dimensions of the
  1375. resulting array can be controlled with the squeeze keyword, see above.
  1376. Typical idioms for handling the return value are::
  1377. # using the variable ax for single a Axes
  1378. fig, ax = plt.subplots()
  1379. # using the variable axs for multiple Axes
  1380. fig, axs = plt.subplots(2, 2)
  1381. # using tuple unpacking for multiple Axes
  1382. fig, (ax1, ax2) = plt.subplots(1, 2)
  1383. fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
  1384. The names ``ax`` and pluralized ``axs`` are preferred over ``axes``
  1385. because for the latter it's not clear if it refers to a single
  1386. `~.axes.Axes` instance or a collection of these.
  1387. See Also
  1388. --------
  1389. .pyplot.figure
  1390. .pyplot.subplot
  1391. .pyplot.axes
  1392. .Figure.subplots
  1393. .Figure.add_subplot
  1394. Examples
  1395. --------
  1396. ::
  1397. # First create some toy data:
  1398. x = np.linspace(0, 2*np.pi, 400)
  1399. y = np.sin(x**2)
  1400. # Create just a figure and only one subplot
  1401. fig, ax = plt.subplots()
  1402. ax.plot(x, y)
  1403. ax.set_title('Simple plot')
  1404. # Create two subplots and unpack the output array immediately
  1405. f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
  1406. ax1.plot(x, y)
  1407. ax1.set_title('Sharing Y axis')
  1408. ax2.scatter(x, y)
  1409. # Create four polar Axes and access them through the returned array
  1410. fig, axs = plt.subplots(2, 2, subplot_kw=dict(projection="polar"))
  1411. axs[0, 0].plot(x, y)
  1412. axs[1, 1].scatter(x, y)
  1413. # Share a X axis with each column of subplots
  1414. plt.subplots(2, 2, sharex='col')
  1415. # Share a Y axis with each row of subplots
  1416. plt.subplots(2, 2, sharey='row')
  1417. # Share both X and Y axes with all subplots
  1418. plt.subplots(2, 2, sharex='all', sharey='all')
  1419. # Note that this is the same as
  1420. plt.subplots(2, 2, sharex=True, sharey=True)
  1421. # Create figure number 10 with a single subplot
  1422. # and clears it if it already exists.
  1423. fig, ax = plt.subplots(num=10, clear=True)
  1424. """
  1425. fig = figure(**fig_kw)
  1426. axs = fig.subplots(nrows=nrows, ncols=ncols, sharex=sharex, sharey=sharey,
  1427. squeeze=squeeze, subplot_kw=subplot_kw,
  1428. gridspec_kw=gridspec_kw, height_ratios=height_ratios,
  1429. width_ratios=width_ratios)
  1430. return fig, axs
  1431. @overload
  1432. def subplot_mosaic(
  1433. mosaic: str,
  1434. *,
  1435. sharex: bool = ...,
  1436. sharey: bool = ...,
  1437. width_ratios: ArrayLike | None = ...,
  1438. height_ratios: ArrayLike | None = ...,
  1439. empty_sentinel: str = ...,
  1440. subplot_kw: dict[str, Any] | None = ...,
  1441. gridspec_kw: dict[str, Any] | None = ...,
  1442. per_subplot_kw: dict[str | tuple[str, ...], dict[str, Any]] | None = ...,
  1443. **fig_kw: Any
  1444. ) -> tuple[Figure, dict[str, matplotlib.axes.Axes]]: ...
  1445. @overload
  1446. def subplot_mosaic(
  1447. mosaic: list[HashableList[_T]],
  1448. *,
  1449. sharex: bool = ...,
  1450. sharey: bool = ...,
  1451. width_ratios: ArrayLike | None = ...,
  1452. height_ratios: ArrayLike | None = ...,
  1453. empty_sentinel: _T = ...,
  1454. subplot_kw: dict[str, Any] | None = ...,
  1455. gridspec_kw: dict[str, Any] | None = ...,
  1456. per_subplot_kw: dict[_T | tuple[_T, ...], dict[str, Any]] | None = ...,
  1457. **fig_kw: Any
  1458. ) -> tuple[Figure, dict[_T, matplotlib.axes.Axes]]: ...
  1459. @overload
  1460. def subplot_mosaic(
  1461. mosaic: list[HashableList[Hashable]],
  1462. *,
  1463. sharex: bool = ...,
  1464. sharey: bool = ...,
  1465. width_ratios: ArrayLike | None = ...,
  1466. height_ratios: ArrayLike | None = ...,
  1467. empty_sentinel: Any = ...,
  1468. subplot_kw: dict[str, Any] | None = ...,
  1469. gridspec_kw: dict[str, Any] | None = ...,
  1470. per_subplot_kw: dict[Hashable | tuple[Hashable, ...], dict[str, Any]] | None = ...,
  1471. **fig_kw: Any
  1472. ) -> tuple[Figure, dict[Hashable, matplotlib.axes.Axes]]: ...
  1473. def subplot_mosaic(
  1474. mosaic: str | list[HashableList[_T]] | list[HashableList[Hashable]],
  1475. *,
  1476. sharex: bool = False,
  1477. sharey: bool = False,
  1478. width_ratios: ArrayLike | None = None,
  1479. height_ratios: ArrayLike | None = None,
  1480. empty_sentinel: Any = '.',
  1481. subplot_kw: dict[str, Any] | None = None,
  1482. gridspec_kw: dict[str, Any] | None = None,
  1483. per_subplot_kw: dict[str | tuple[str, ...], dict[str, Any]] |
  1484. dict[_T | tuple[_T, ...], dict[str, Any]] |
  1485. dict[Hashable | tuple[Hashable, ...], dict[str, Any]] | None = None,
  1486. **fig_kw: Any
  1487. ) -> tuple[Figure, dict[str, matplotlib.axes.Axes]] | \
  1488. tuple[Figure, dict[_T, matplotlib.axes.Axes]] | \
  1489. tuple[Figure, dict[Hashable, matplotlib.axes.Axes]]:
  1490. """
  1491. Build a layout of Axes based on ASCII art or nested lists.
  1492. This is a helper function to build complex GridSpec layouts visually.
  1493. See :ref:`mosaic`
  1494. for an example and full API documentation
  1495. Parameters
  1496. ----------
  1497. mosaic : list of list of {hashable or nested} or str
  1498. A visual layout of how you want your Axes to be arranged
  1499. labeled as strings. For example ::
  1500. x = [['A panel', 'A panel', 'edge'],
  1501. ['C panel', '.', 'edge']]
  1502. produces 4 Axes:
  1503. - 'A panel' which is 1 row high and spans the first two columns
  1504. - 'edge' which is 2 rows high and is on the right edge
  1505. - 'C panel' which in 1 row and 1 column wide in the bottom left
  1506. - a blank space 1 row and 1 column wide in the bottom center
  1507. Any of the entries in the layout can be a list of lists
  1508. of the same form to create nested layouts.
  1509. If input is a str, then it must be of the form ::
  1510. '''
  1511. AAE
  1512. C.E
  1513. '''
  1514. where each character is a column and each line is a row.
  1515. This only allows only single character Axes labels and does
  1516. not allow nesting but is very terse.
  1517. sharex, sharey : bool, default: False
  1518. If True, the x-axis (*sharex*) or y-axis (*sharey*) will be shared
  1519. among all subplots. In that case, tick label visibility and axis units
  1520. behave as for `subplots`. If False, each subplot's x- or y-axis will
  1521. be independent.
  1522. width_ratios : array-like of length *ncols*, optional
  1523. Defines the relative widths of the columns. Each column gets a
  1524. relative width of ``width_ratios[i] / sum(width_ratios)``.
  1525. If not given, all columns will have the same width. Convenience
  1526. for ``gridspec_kw={'width_ratios': [...]}``.
  1527. height_ratios : array-like of length *nrows*, optional
  1528. Defines the relative heights of the rows. Each row gets a
  1529. relative height of ``height_ratios[i] / sum(height_ratios)``.
  1530. If not given, all rows will have the same height. Convenience
  1531. for ``gridspec_kw={'height_ratios': [...]}``.
  1532. empty_sentinel : object, optional
  1533. Entry in the layout to mean "leave this space empty". Defaults
  1534. to ``'.'``. Note, if *layout* is a string, it is processed via
  1535. `inspect.cleandoc` to remove leading white space, which may
  1536. interfere with using white-space as the empty sentinel.
  1537. subplot_kw : dict, optional
  1538. Dictionary with keywords passed to the `.Figure.add_subplot` call
  1539. used to create each subplot. These values may be overridden by
  1540. values in *per_subplot_kw*.
  1541. per_subplot_kw : dict, optional
  1542. A dictionary mapping the Axes identifiers or tuples of identifiers
  1543. to a dictionary of keyword arguments to be passed to the
  1544. `.Figure.add_subplot` call used to create each subplot. The values
  1545. in these dictionaries have precedence over the values in
  1546. *subplot_kw*.
  1547. If *mosaic* is a string, and thus all keys are single characters,
  1548. it is possible to use a single string instead of a tuple as keys;
  1549. i.e. ``"AB"`` is equivalent to ``("A", "B")``.
  1550. .. versionadded:: 3.7
  1551. gridspec_kw : dict, optional
  1552. Dictionary with keywords passed to the `.GridSpec` constructor used
  1553. to create the grid the subplots are placed on.
  1554. **fig_kw
  1555. All additional keyword arguments are passed to the
  1556. `.pyplot.figure` call.
  1557. Returns
  1558. -------
  1559. fig : `.Figure`
  1560. The new figure
  1561. dict[label, Axes]
  1562. A dictionary mapping the labels to the Axes objects. The order of
  1563. the Axes is left-to-right and top-to-bottom of their position in the
  1564. total layout.
  1565. """
  1566. fig = figure(**fig_kw)
  1567. ax_dict = fig.subplot_mosaic( # type: ignore[misc]
  1568. mosaic, # type: ignore[arg-type]
  1569. sharex=sharex, sharey=sharey,
  1570. height_ratios=height_ratios, width_ratios=width_ratios,
  1571. subplot_kw=subplot_kw, gridspec_kw=gridspec_kw,
  1572. empty_sentinel=empty_sentinel,
  1573. per_subplot_kw=per_subplot_kw, # type: ignore[arg-type]
  1574. )
  1575. return fig, ax_dict
  1576. def subplot2grid(
  1577. shape: tuple[int, int], loc: tuple[int, int],
  1578. rowspan: int = 1, colspan: int = 1,
  1579. fig: Figure | None = None,
  1580. **kwargs
  1581. ) -> matplotlib.axes.Axes:
  1582. """
  1583. Create a subplot at a specific location inside a regular grid.
  1584. Parameters
  1585. ----------
  1586. shape : (int, int)
  1587. Number of rows and of columns of the grid in which to place axis.
  1588. loc : (int, int)
  1589. Row number and column number of the axis location within the grid.
  1590. rowspan : int, default: 1
  1591. Number of rows for the axis to span downwards.
  1592. colspan : int, default: 1
  1593. Number of columns for the axis to span to the right.
  1594. fig : `.Figure`, optional
  1595. Figure to place the subplot in. Defaults to the current figure.
  1596. **kwargs
  1597. Additional keyword arguments are handed to `~.Figure.add_subplot`.
  1598. Returns
  1599. -------
  1600. `~.axes.Axes`
  1601. The Axes of the subplot. The returned Axes can actually be an instance
  1602. of a subclass, such as `.projections.polar.PolarAxes` for polar
  1603. projections.
  1604. Notes
  1605. -----
  1606. The following call ::
  1607. ax = subplot2grid((nrows, ncols), (row, col), rowspan, colspan)
  1608. is identical to ::
  1609. fig = gcf()
  1610. gs = fig.add_gridspec(nrows, ncols)
  1611. ax = fig.add_subplot(gs[row:row+rowspan, col:col+colspan])
  1612. """
  1613. if fig is None:
  1614. fig = gcf()
  1615. rows, cols = shape
  1616. gs = GridSpec._check_gridspec_exists(fig, rows, cols)
  1617. subplotspec = gs.new_subplotspec(loc, rowspan=rowspan, colspan=colspan)
  1618. return fig.add_subplot(subplotspec, **kwargs)
  1619. def twinx(ax: matplotlib.axes.Axes | None = None) -> _AxesBase:
  1620. """
  1621. Make and return a second Axes that shares the *x*-axis. The new Axes will
  1622. overlay *ax* (or the current Axes if *ax* is *None*), and its ticks will be
  1623. on the right.
  1624. Examples
  1625. --------
  1626. :doc:`/gallery/subplots_axes_and_figures/two_scales`
  1627. """
  1628. if ax is None:
  1629. ax = gca()
  1630. ax1 = ax.twinx()
  1631. return ax1
  1632. def twiny(ax: matplotlib.axes.Axes | None = None) -> _AxesBase:
  1633. """
  1634. Make and return a second Axes that shares the *y*-axis. The new Axes will
  1635. overlay *ax* (or the current Axes if *ax* is *None*), and its ticks will be
  1636. on the top.
  1637. Examples
  1638. --------
  1639. :doc:`/gallery/subplots_axes_and_figures/two_scales`
  1640. """
  1641. if ax is None:
  1642. ax = gca()
  1643. ax1 = ax.twiny()
  1644. return ax1
  1645. def subplot_tool(targetfig: Figure | None = None) -> SubplotTool | None:
  1646. """
  1647. Launch a subplot tool window for a figure.
  1648. Returns
  1649. -------
  1650. `matplotlib.widgets.SubplotTool`
  1651. """
  1652. if targetfig is None:
  1653. targetfig = gcf()
  1654. tb = targetfig.canvas.manager.toolbar # type: ignore[union-attr]
  1655. if hasattr(tb, "configure_subplots"): # toolbar2
  1656. from matplotlib.backend_bases import NavigationToolbar2
  1657. return cast(NavigationToolbar2, tb).configure_subplots()
  1658. elif hasattr(tb, "trigger_tool"): # toolmanager
  1659. from matplotlib.backend_bases import ToolContainerBase
  1660. cast(ToolContainerBase, tb).trigger_tool("subplots")
  1661. return None
  1662. else:
  1663. raise ValueError("subplot_tool can only be launched for figures with "
  1664. "an associated toolbar")
  1665. def box(on: bool | None = None) -> None:
  1666. """
  1667. Turn the Axes box on or off on the current Axes.
  1668. Parameters
  1669. ----------
  1670. on : bool or None
  1671. The new `~matplotlib.axes.Axes` box state. If ``None``, toggle
  1672. the state.
  1673. See Also
  1674. --------
  1675. :meth:`matplotlib.axes.Axes.set_frame_on`
  1676. :meth:`matplotlib.axes.Axes.get_frame_on`
  1677. """
  1678. ax = gca()
  1679. if on is None:
  1680. on = not ax.get_frame_on()
  1681. ax.set_frame_on(on)
  1682. ## Axis ##
  1683. def xlim(*args, **kwargs) -> tuple[float, float]:
  1684. """
  1685. Get or set the x limits of the current Axes.
  1686. Call signatures::
  1687. left, right = xlim() # return the current xlim
  1688. xlim((left, right)) # set the xlim to left, right
  1689. xlim(left, right) # set the xlim to left, right
  1690. If you do not specify args, you can pass *left* or *right* as kwargs,
  1691. i.e.::
  1692. xlim(right=3) # adjust the right leaving left unchanged
  1693. xlim(left=1) # adjust the left leaving right unchanged
  1694. Setting limits turns autoscaling off for the x-axis.
  1695. Returns
  1696. -------
  1697. left, right
  1698. A tuple of the new x-axis limits.
  1699. Notes
  1700. -----
  1701. Calling this function with no arguments (e.g. ``xlim()``) is the pyplot
  1702. equivalent of calling `~.Axes.get_xlim` on the current Axes.
  1703. Calling this function with arguments is the pyplot equivalent of calling
  1704. `~.Axes.set_xlim` on the current Axes. All arguments are passed though.
  1705. """
  1706. ax = gca()
  1707. if not args and not kwargs:
  1708. return ax.get_xlim()
  1709. ret = ax.set_xlim(*args, **kwargs)
  1710. return ret
  1711. def ylim(*args, **kwargs) -> tuple[float, float]:
  1712. """
  1713. Get or set the y-limits of the current Axes.
  1714. Call signatures::
  1715. bottom, top = ylim() # return the current ylim
  1716. ylim((bottom, top)) # set the ylim to bottom, top
  1717. ylim(bottom, top) # set the ylim to bottom, top
  1718. If you do not specify args, you can alternatively pass *bottom* or
  1719. *top* as kwargs, i.e.::
  1720. ylim(top=3) # adjust the top leaving bottom unchanged
  1721. ylim(bottom=1) # adjust the bottom leaving top unchanged
  1722. Setting limits turns autoscaling off for the y-axis.
  1723. Returns
  1724. -------
  1725. bottom, top
  1726. A tuple of the new y-axis limits.
  1727. Notes
  1728. -----
  1729. Calling this function with no arguments (e.g. ``ylim()``) is the pyplot
  1730. equivalent of calling `~.Axes.get_ylim` on the current Axes.
  1731. Calling this function with arguments is the pyplot equivalent of calling
  1732. `~.Axes.set_ylim` on the current Axes. All arguments are passed though.
  1733. """
  1734. ax = gca()
  1735. if not args and not kwargs:
  1736. return ax.get_ylim()
  1737. ret = ax.set_ylim(*args, **kwargs)
  1738. return ret
  1739. def xticks(
  1740. ticks: ArrayLike | None = None,
  1741. labels: Sequence[str] | None = None,
  1742. *,
  1743. minor: bool = False,
  1744. **kwargs
  1745. ) -> tuple[list[Tick] | np.ndarray, list[Text]]:
  1746. """
  1747. Get or set the current tick locations and labels of the x-axis.
  1748. Pass no arguments to return the current values without modifying them.
  1749. Parameters
  1750. ----------
  1751. ticks : array-like, optional
  1752. The list of xtick locations. Passing an empty list removes all xticks.
  1753. labels : array-like, optional
  1754. The labels to place at the given *ticks* locations. This argument can
  1755. only be passed if *ticks* is passed as well.
  1756. minor : bool, default: False
  1757. If ``False``, get/set the major ticks/labels; if ``True``, the minor
  1758. ticks/labels.
  1759. **kwargs
  1760. `.Text` properties can be used to control the appearance of the labels.
  1761. .. warning::
  1762. This only sets the properties of the current ticks, which is
  1763. only sufficient if you either pass *ticks*, resulting in a
  1764. fixed list of ticks, or if the plot is static.
  1765. Ticks are not guaranteed to be persistent. Various operations
  1766. can create, delete and modify the Tick instances. There is an
  1767. imminent risk that these settings can get lost if you work on
  1768. the figure further (including also panning/zooming on a
  1769. displayed figure).
  1770. Use `~.pyplot.tick_params` instead if possible.
  1771. Returns
  1772. -------
  1773. locs
  1774. The list of xtick locations.
  1775. labels
  1776. The list of xlabel `.Text` objects.
  1777. Notes
  1778. -----
  1779. Calling this function with no arguments (e.g. ``xticks()``) is the pyplot
  1780. equivalent of calling `~.Axes.get_xticks` and `~.Axes.get_xticklabels` on
  1781. the current Axes.
  1782. Calling this function with arguments is the pyplot equivalent of calling
  1783. `~.Axes.set_xticks` and `~.Axes.set_xticklabels` on the current Axes.
  1784. Examples
  1785. --------
  1786. >>> locs, labels = xticks() # Get the current locations and labels.
  1787. >>> xticks(np.arange(0, 1, step=0.2)) # Set label locations.
  1788. >>> xticks(np.arange(3), ['Tom', 'Dick', 'Sue']) # Set text labels.
  1789. >>> xticks([0, 1, 2], ['January', 'February', 'March'],
  1790. ... rotation=20) # Set text labels and properties.
  1791. >>> xticks([]) # Disable xticks.
  1792. """
  1793. ax = gca()
  1794. locs: list[Tick] | np.ndarray
  1795. if ticks is None:
  1796. locs = ax.get_xticks(minor=minor)
  1797. if labels is not None:
  1798. raise TypeError("xticks(): Parameter 'labels' can't be set "
  1799. "without setting 'ticks'")
  1800. else:
  1801. locs = ax.set_xticks(ticks, minor=minor)
  1802. labels_out: list[Text] = []
  1803. if labels is None:
  1804. labels_out = ax.get_xticklabels(minor=minor)
  1805. for l in labels_out:
  1806. l._internal_update(kwargs)
  1807. else:
  1808. labels_out = ax.set_xticklabels(labels, minor=minor, **kwargs)
  1809. return locs, labels_out
  1810. def yticks(
  1811. ticks: ArrayLike | None = None,
  1812. labels: Sequence[str] | None = None,
  1813. *,
  1814. minor: bool = False,
  1815. **kwargs
  1816. ) -> tuple[list[Tick] | np.ndarray, list[Text]]:
  1817. """
  1818. Get or set the current tick locations and labels of the y-axis.
  1819. Pass no arguments to return the current values without modifying them.
  1820. Parameters
  1821. ----------
  1822. ticks : array-like, optional
  1823. The list of ytick locations. Passing an empty list removes all yticks.
  1824. labels : array-like, optional
  1825. The labels to place at the given *ticks* locations. This argument can
  1826. only be passed if *ticks* is passed as well.
  1827. minor : bool, default: False
  1828. If ``False``, get/set the major ticks/labels; if ``True``, the minor
  1829. ticks/labels.
  1830. **kwargs
  1831. `.Text` properties can be used to control the appearance of the labels.
  1832. .. warning::
  1833. This only sets the properties of the current ticks, which is
  1834. only sufficient if you either pass *ticks*, resulting in a
  1835. fixed list of ticks, or if the plot is static.
  1836. Ticks are not guaranteed to be persistent. Various operations
  1837. can create, delete and modify the Tick instances. There is an
  1838. imminent risk that these settings can get lost if you work on
  1839. the figure further (including also panning/zooming on a
  1840. displayed figure).
  1841. Use `~.pyplot.tick_params` instead if possible.
  1842. Returns
  1843. -------
  1844. locs
  1845. The list of ytick locations.
  1846. labels
  1847. The list of ylabel `.Text` objects.
  1848. Notes
  1849. -----
  1850. Calling this function with no arguments (e.g. ``yticks()``) is the pyplot
  1851. equivalent of calling `~.Axes.get_yticks` and `~.Axes.get_yticklabels` on
  1852. the current Axes.
  1853. Calling this function with arguments is the pyplot equivalent of calling
  1854. `~.Axes.set_yticks` and `~.Axes.set_yticklabels` on the current Axes.
  1855. Examples
  1856. --------
  1857. >>> locs, labels = yticks() # Get the current locations and labels.
  1858. >>> yticks(np.arange(0, 1, step=0.2)) # Set label locations.
  1859. >>> yticks(np.arange(3), ['Tom', 'Dick', 'Sue']) # Set text labels.
  1860. >>> yticks([0, 1, 2], ['January', 'February', 'March'],
  1861. ... rotation=45) # Set text labels and properties.
  1862. >>> yticks([]) # Disable yticks.
  1863. """
  1864. ax = gca()
  1865. locs: list[Tick] | np.ndarray
  1866. if ticks is None:
  1867. locs = ax.get_yticks(minor=minor)
  1868. if labels is not None:
  1869. raise TypeError("yticks(): Parameter 'labels' can't be set "
  1870. "without setting 'ticks'")
  1871. else:
  1872. locs = ax.set_yticks(ticks, minor=minor)
  1873. labels_out: list[Text] = []
  1874. if labels is None:
  1875. labels_out = ax.get_yticklabels(minor=minor)
  1876. for l in labels_out:
  1877. l._internal_update(kwargs)
  1878. else:
  1879. labels_out = ax.set_yticklabels(labels, minor=minor, **kwargs)
  1880. return locs, labels_out
  1881. def rgrids(
  1882. radii: ArrayLike | None = None,
  1883. labels: Sequence[str | Text] | None = None,
  1884. angle: float | None = None,
  1885. fmt: str | None = None,
  1886. **kwargs
  1887. ) -> tuple[list[Line2D], list[Text]]:
  1888. """
  1889. Get or set the radial gridlines on the current polar plot.
  1890. Call signatures::
  1891. lines, labels = rgrids()
  1892. lines, labels = rgrids(radii, labels=None, angle=22.5, fmt=None, **kwargs)
  1893. When called with no arguments, `.rgrids` simply returns the tuple
  1894. (*lines*, *labels*). When called with arguments, the labels will
  1895. appear at the specified radial distances and angle.
  1896. Parameters
  1897. ----------
  1898. radii : tuple with floats
  1899. The radii for the radial gridlines
  1900. labels : tuple with strings or None
  1901. The labels to use at each radial gridline. The
  1902. `matplotlib.ticker.ScalarFormatter` will be used if None.
  1903. angle : float
  1904. The angular position of the radius labels in degrees.
  1905. fmt : str or None
  1906. Format string used in `matplotlib.ticker.FormatStrFormatter`.
  1907. For example '%f'.
  1908. Returns
  1909. -------
  1910. lines : list of `.lines.Line2D`
  1911. The radial gridlines.
  1912. labels : list of `.text.Text`
  1913. The tick labels.
  1914. Other Parameters
  1915. ----------------
  1916. **kwargs
  1917. *kwargs* are optional `.Text` properties for the labels.
  1918. See Also
  1919. --------
  1920. .pyplot.thetagrids
  1921. .projections.polar.PolarAxes.set_rgrids
  1922. .Axis.get_gridlines
  1923. .Axis.get_ticklabels
  1924. Examples
  1925. --------
  1926. ::
  1927. # set the locations of the radial gridlines
  1928. lines, labels = rgrids( (0.25, 0.5, 1.0) )
  1929. # set the locations and labels of the radial gridlines
  1930. lines, labels = rgrids( (0.25, 0.5, 1.0), ('Tom', 'Dick', 'Harry' ))
  1931. """
  1932. ax = gca()
  1933. if not isinstance(ax, PolarAxes):
  1934. raise RuntimeError('rgrids only defined for polar Axes')
  1935. if all(p is None for p in [radii, labels, angle, fmt]) and not kwargs:
  1936. lines_out: list[Line2D] = ax.yaxis.get_gridlines()
  1937. labels_out: list[Text] = ax.yaxis.get_ticklabels()
  1938. elif radii is None:
  1939. raise TypeError("'radii' cannot be None when other parameters are passed")
  1940. else:
  1941. lines_out, labels_out = ax.set_rgrids(
  1942. radii, labels=labels, angle=angle, fmt=fmt, **kwargs)
  1943. return lines_out, labels_out
  1944. def thetagrids(
  1945. angles: ArrayLike | None = None,
  1946. labels: Sequence[str | Text] | None = None,
  1947. fmt: str | None = None,
  1948. **kwargs
  1949. ) -> tuple[list[Line2D], list[Text]]:
  1950. """
  1951. Get or set the theta gridlines on the current polar plot.
  1952. Call signatures::
  1953. lines, labels = thetagrids()
  1954. lines, labels = thetagrids(angles, labels=None, fmt=None, **kwargs)
  1955. When called with no arguments, `.thetagrids` simply returns the tuple
  1956. (*lines*, *labels*). When called with arguments, the labels will
  1957. appear at the specified angles.
  1958. Parameters
  1959. ----------
  1960. angles : tuple with floats, degrees
  1961. The angles of the theta gridlines.
  1962. labels : tuple with strings or None
  1963. The labels to use at each radial gridline. The
  1964. `.projections.polar.ThetaFormatter` will be used if None.
  1965. fmt : str or None
  1966. Format string used in `matplotlib.ticker.FormatStrFormatter`.
  1967. For example '%f'. Note that the angle in radians will be used.
  1968. Returns
  1969. -------
  1970. lines : list of `.lines.Line2D`
  1971. The theta gridlines.
  1972. labels : list of `.text.Text`
  1973. The tick labels.
  1974. Other Parameters
  1975. ----------------
  1976. **kwargs
  1977. *kwargs* are optional `.Text` properties for the labels.
  1978. See Also
  1979. --------
  1980. .pyplot.rgrids
  1981. .projections.polar.PolarAxes.set_thetagrids
  1982. .Axis.get_gridlines
  1983. .Axis.get_ticklabels
  1984. Examples
  1985. --------
  1986. ::
  1987. # set the locations of the angular gridlines
  1988. lines, labels = thetagrids(range(45, 360, 90))
  1989. # set the locations and labels of the angular gridlines
  1990. lines, labels = thetagrids(range(45, 360, 90), ('NE', 'NW', 'SW', 'SE'))
  1991. """
  1992. ax = gca()
  1993. if not isinstance(ax, PolarAxes):
  1994. raise RuntimeError('thetagrids only defined for polar Axes')
  1995. if all(param is None for param in [angles, labels, fmt]) and not kwargs:
  1996. lines_out: list[Line2D] = ax.xaxis.get_ticklines()
  1997. labels_out: list[Text] = ax.xaxis.get_ticklabels()
  1998. elif angles is None:
  1999. raise TypeError("'angles' cannot be None when other parameters are passed")
  2000. else:
  2001. lines_out, labels_out = ax.set_thetagrids(angles,
  2002. labels=labels, fmt=fmt,
  2003. **kwargs)
  2004. return lines_out, labels_out
  2005. @_api.deprecated("3.7", pending=True)
  2006. def get_plot_commands() -> list[str]:
  2007. """
  2008. Get a sorted list of all of the plotting commands.
  2009. """
  2010. NON_PLOT_COMMANDS = {
  2011. 'connect', 'disconnect', 'get_current_fig_manager', 'ginput',
  2012. 'new_figure_manager', 'waitforbuttonpress'}
  2013. return [name for name in _get_pyplot_commands()
  2014. if name not in NON_PLOT_COMMANDS]
  2015. def _get_pyplot_commands() -> list[str]:
  2016. # This works by searching for all functions in this module and removing
  2017. # a few hard-coded exclusions, as well as all of the colormap-setting
  2018. # functions, and anything marked as private with a preceding underscore.
  2019. exclude = {'colormaps', 'colors', 'get_plot_commands', *colormaps}
  2020. this_module = inspect.getmodule(get_plot_commands)
  2021. return sorted(
  2022. name for name, obj in globals().items()
  2023. if not name.startswith('_') and name not in exclude
  2024. and inspect.isfunction(obj)
  2025. and inspect.getmodule(obj) is this_module)
  2026. ## Plotting part 1: manually generated functions and wrappers ##
  2027. @_copy_docstring_and_deprecators(Figure.colorbar)
  2028. def colorbar(
  2029. mappable: ScalarMappable | ColorizingArtist | None = None,
  2030. cax: matplotlib.axes.Axes | None = None,
  2031. ax: matplotlib.axes.Axes | Iterable[matplotlib.axes.Axes] | None = None,
  2032. **kwargs
  2033. ) -> Colorbar:
  2034. if mappable is None:
  2035. mappable = gci()
  2036. if mappable is None:
  2037. raise RuntimeError('No mappable was found to use for colorbar '
  2038. 'creation. First define a mappable such as '
  2039. 'an image (with imshow) or a contour set ('
  2040. 'with contourf).')
  2041. ret = gcf().colorbar(mappable, cax=cax, ax=ax, **kwargs)
  2042. return ret
  2043. def clim(vmin: float | None = None, vmax: float | None = None) -> None:
  2044. """
  2045. Set the color limits of the current image.
  2046. If either *vmin* or *vmax* is None, the image min/max respectively
  2047. will be used for color scaling.
  2048. If you want to set the clim of multiple images, use
  2049. `~.ScalarMappable.set_clim` on every image, for example::
  2050. for im in gca().get_images():
  2051. im.set_clim(0, 0.5)
  2052. """
  2053. im = gci()
  2054. if im is None:
  2055. raise RuntimeError('You must first define an image, e.g., with imshow')
  2056. im.set_clim(vmin, vmax)
  2057. def get_cmap(name: Colormap | str | None = None, lut: int | None = None) -> Colormap:
  2058. """
  2059. Get a colormap instance, defaulting to rc values if *name* is None.
  2060. Parameters
  2061. ----------
  2062. name : `~matplotlib.colors.Colormap` or str or None, default: None
  2063. If a `.Colormap` instance, it will be returned. Otherwise, the name of
  2064. a colormap known to Matplotlib, which will be resampled by *lut*. The
  2065. default, None, means :rc:`image.cmap`.
  2066. lut : int or None, default: None
  2067. If *name* is not already a Colormap instance and *lut* is not None, the
  2068. colormap will be resampled to have *lut* entries in the lookup table.
  2069. Returns
  2070. -------
  2071. Colormap
  2072. """
  2073. if name is None:
  2074. name = rcParams['image.cmap']
  2075. if isinstance(name, Colormap):
  2076. return name
  2077. _api.check_in_list(sorted(_colormaps), name=name)
  2078. if lut is None:
  2079. return _colormaps[name]
  2080. else:
  2081. return _colormaps[name].resampled(lut)
  2082. def set_cmap(cmap: Colormap | str) -> None:
  2083. """
  2084. Set the default colormap, and applies it to the current image if any.
  2085. Parameters
  2086. ----------
  2087. cmap : `~matplotlib.colors.Colormap` or str
  2088. A colormap instance or the name of a registered colormap.
  2089. See Also
  2090. --------
  2091. colormaps
  2092. get_cmap
  2093. """
  2094. cmap = get_cmap(cmap)
  2095. rc('image', cmap=cmap.name)
  2096. im = gci()
  2097. if im is not None:
  2098. im.set_cmap(cmap)
  2099. @_copy_docstring_and_deprecators(matplotlib.image.imread)
  2100. def imread(
  2101. fname: str | pathlib.Path | BinaryIO, format: str | None = None
  2102. ) -> np.ndarray:
  2103. return matplotlib.image.imread(fname, format)
  2104. @_copy_docstring_and_deprecators(matplotlib.image.imsave)
  2105. def imsave(
  2106. fname: str | os.PathLike | BinaryIO, arr: ArrayLike, **kwargs
  2107. ) -> None:
  2108. matplotlib.image.imsave(fname, arr, **kwargs)
  2109. def matshow(A: ArrayLike, fignum: None | int = None, **kwargs) -> AxesImage:
  2110. """
  2111. Display a 2D array as a matrix in a new figure window.
  2112. The origin is set at the upper left hand corner.
  2113. The indexing is ``(row, column)`` so that the first index runs vertically
  2114. and the second index runs horizontally in the figure:
  2115. .. code-block:: none
  2116. A[0, 0] ⋯ A[0, M-1]
  2117. ⋮ ⋮
  2118. A[N-1, 0] ⋯ A[N-1, M-1]
  2119. The aspect ratio of the figure window is that of the array,
  2120. unless this would make an excessively short or narrow figure.
  2121. Tick labels for the xaxis are placed on top.
  2122. Parameters
  2123. ----------
  2124. A : 2D array-like
  2125. The matrix to be displayed.
  2126. fignum : None or int
  2127. If *None*, create a new, appropriately sized figure window.
  2128. If 0, use the current Axes (creating one if there is none, without ever
  2129. adjusting the figure size).
  2130. Otherwise, create a new Axes on the figure with the given number
  2131. (creating it at the appropriate size if it does not exist, but not
  2132. adjusting the figure size otherwise). Note that this will be drawn on
  2133. top of any preexisting Axes on the figure.
  2134. Returns
  2135. -------
  2136. `~matplotlib.image.AxesImage`
  2137. Other Parameters
  2138. ----------------
  2139. **kwargs : `~matplotlib.axes.Axes.imshow` arguments
  2140. """
  2141. A = np.asanyarray(A)
  2142. if fignum == 0:
  2143. ax = gca()
  2144. else:
  2145. if fignum is not None and fignum_exists(fignum):
  2146. # Do not try to set a figure size.
  2147. figsize = None
  2148. else:
  2149. # Extract actual aspect ratio of array and make appropriately sized figure.
  2150. figsize = figaspect(A)
  2151. fig = figure(fignum, figsize=figsize)
  2152. ax = fig.add_axes((0.15, 0.09, 0.775, 0.775))
  2153. im = ax.matshow(A, **kwargs)
  2154. sci(im)
  2155. return im
  2156. def polar(*args, **kwargs) -> list[Line2D]:
  2157. """
  2158. Make a polar plot.
  2159. call signature::
  2160. polar(theta, r, [fmt], **kwargs)
  2161. This is a convenience wrapper around `.pyplot.plot`. It ensures that the
  2162. current Axes is polar (or creates one if needed) and then passes all parameters
  2163. to ``.pyplot.plot``.
  2164. .. note::
  2165. When making polar plots using the :ref:`pyplot API <pyplot_interface>`,
  2166. ``polar()`` should typically be the first command because that makes sure
  2167. a polar Axes is created. Using other commands such as ``plt.title()``
  2168. before this can lead to the implicit creation of a rectangular Axes, in which
  2169. case a subsequent ``polar()`` call will fail.
  2170. """
  2171. # If an axis already exists, check if it has a polar projection
  2172. if gcf().get_axes():
  2173. ax = gca()
  2174. if not isinstance(ax, PolarAxes):
  2175. _api.warn_deprecated(
  2176. "3.10",
  2177. message="There exists a non-polar current Axes. Therefore, the "
  2178. "resulting plot from 'polar()' is non-polar. You likely "
  2179. "should call 'polar()' before any other pyplot plotting "
  2180. "commands. "
  2181. "Support for this scenario is deprecated in %(since)s and "
  2182. "will raise an error in %(removal)s"
  2183. )
  2184. else:
  2185. ax = axes(projection="polar")
  2186. return ax.plot(*args, **kwargs)
  2187. # If rcParams['backend_fallback'] is true, and an interactive backend is
  2188. # requested, ignore rcParams['backend'] and force selection of a backend that
  2189. # is compatible with the current running interactive framework.
  2190. if rcParams["backend_fallback"]:
  2191. requested_backend = rcParams._get_backend_or_none() # type: ignore[attr-defined]
  2192. requested_backend = None if requested_backend is None else requested_backend.lower()
  2193. available_backends = backend_registry.list_builtin(BackendFilter.INTERACTIVE)
  2194. if (
  2195. requested_backend in (set(available_backends) - {'webagg', 'nbagg'})
  2196. and cbook._get_running_interactive_framework()
  2197. ):
  2198. rcParams._set("backend", rcsetup._auto_backend_sentinel)
  2199. # fmt: on
  2200. ################# REMAINING CONTENT GENERATED BY boilerplate.py ##############
  2201. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2202. @_copy_docstring_and_deprecators(Figure.figimage)
  2203. def figimage(
  2204. X: ArrayLike,
  2205. xo: int = 0,
  2206. yo: int = 0,
  2207. alpha: float | None = None,
  2208. norm: str | Normalize | None = None,
  2209. cmap: str | Colormap | None = None,
  2210. vmin: float | None = None,
  2211. vmax: float | None = None,
  2212. origin: Literal["upper", "lower"] | None = None,
  2213. resize: bool = False,
  2214. *,
  2215. colorizer: Colorizer | None = None,
  2216. **kwargs,
  2217. ) -> FigureImage:
  2218. return gcf().figimage(
  2219. X,
  2220. xo=xo,
  2221. yo=yo,
  2222. alpha=alpha,
  2223. norm=norm,
  2224. cmap=cmap,
  2225. vmin=vmin,
  2226. vmax=vmax,
  2227. origin=origin,
  2228. resize=resize,
  2229. colorizer=colorizer,
  2230. **kwargs,
  2231. )
  2232. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2233. @_copy_docstring_and_deprecators(Figure.text)
  2234. def figtext(
  2235. x: float, y: float, s: str, fontdict: dict[str, Any] | None = None, **kwargs
  2236. ) -> Text:
  2237. return gcf().text(x, y, s, fontdict=fontdict, **kwargs)
  2238. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2239. @_copy_docstring_and_deprecators(Figure.gca)
  2240. def gca() -> Axes:
  2241. return gcf().gca()
  2242. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2243. @_copy_docstring_and_deprecators(Figure._gci)
  2244. def gci() -> ColorizingArtist | None:
  2245. return gcf()._gci()
  2246. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2247. @_copy_docstring_and_deprecators(Figure.ginput)
  2248. def ginput(
  2249. n: int = 1,
  2250. timeout: float = 30,
  2251. show_clicks: bool = True,
  2252. mouse_add: MouseButton = MouseButton.LEFT,
  2253. mouse_pop: MouseButton = MouseButton.RIGHT,
  2254. mouse_stop: MouseButton = MouseButton.MIDDLE,
  2255. ) -> list[tuple[int, int]]:
  2256. return gcf().ginput(
  2257. n=n,
  2258. timeout=timeout,
  2259. show_clicks=show_clicks,
  2260. mouse_add=mouse_add,
  2261. mouse_pop=mouse_pop,
  2262. mouse_stop=mouse_stop,
  2263. )
  2264. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2265. @_copy_docstring_and_deprecators(Figure.subplots_adjust)
  2266. def subplots_adjust(
  2267. left: float | None = None,
  2268. bottom: float | None = None,
  2269. right: float | None = None,
  2270. top: float | None = None,
  2271. wspace: float | None = None,
  2272. hspace: float | None = None,
  2273. ) -> None:
  2274. gcf().subplots_adjust(
  2275. left=left, bottom=bottom, right=right, top=top, wspace=wspace, hspace=hspace
  2276. )
  2277. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2278. @_copy_docstring_and_deprecators(Figure.suptitle)
  2279. def suptitle(t: str, **kwargs) -> Text:
  2280. return gcf().suptitle(t, **kwargs)
  2281. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2282. @_copy_docstring_and_deprecators(Figure.tight_layout)
  2283. def tight_layout(
  2284. *,
  2285. pad: float = 1.08,
  2286. h_pad: float | None = None,
  2287. w_pad: float | None = None,
  2288. rect: tuple[float, float, float, float] | None = None,
  2289. ) -> None:
  2290. gcf().tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
  2291. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2292. @_copy_docstring_and_deprecators(Figure.waitforbuttonpress)
  2293. def waitforbuttonpress(timeout: float = -1) -> None | bool:
  2294. return gcf().waitforbuttonpress(timeout=timeout)
  2295. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2296. @_copy_docstring_and_deprecators(Axes.acorr)
  2297. def acorr(
  2298. x: ArrayLike, *, data=None, **kwargs
  2299. ) -> tuple[np.ndarray, np.ndarray, LineCollection | Line2D, Line2D | None]:
  2300. return gca().acorr(x, **({"data": data} if data is not None else {}), **kwargs)
  2301. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2302. @_copy_docstring_and_deprecators(Axes.angle_spectrum)
  2303. def angle_spectrum(
  2304. x: ArrayLike,
  2305. Fs: float | None = None,
  2306. Fc: int | None = None,
  2307. window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = None,
  2308. pad_to: int | None = None,
  2309. sides: Literal["default", "onesided", "twosided"] | None = None,
  2310. *,
  2311. data=None,
  2312. **kwargs,
  2313. ) -> tuple[np.ndarray, np.ndarray, Line2D]:
  2314. return gca().angle_spectrum(
  2315. x,
  2316. Fs=Fs,
  2317. Fc=Fc,
  2318. window=window,
  2319. pad_to=pad_to,
  2320. sides=sides,
  2321. **({"data": data} if data is not None else {}),
  2322. **kwargs,
  2323. )
  2324. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2325. @_copy_docstring_and_deprecators(Axes.annotate)
  2326. def annotate(
  2327. text: str,
  2328. xy: tuple[float, float],
  2329. xytext: tuple[float, float] | None = None,
  2330. xycoords: CoordsType = "data",
  2331. textcoords: CoordsType | None = None,
  2332. arrowprops: dict[str, Any] | None = None,
  2333. annotation_clip: bool | None = None,
  2334. **kwargs,
  2335. ) -> Annotation:
  2336. return gca().annotate(
  2337. text,
  2338. xy,
  2339. xytext=xytext,
  2340. xycoords=xycoords,
  2341. textcoords=textcoords,
  2342. arrowprops=arrowprops,
  2343. annotation_clip=annotation_clip,
  2344. **kwargs,
  2345. )
  2346. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2347. @_copy_docstring_and_deprecators(Axes.arrow)
  2348. def arrow(x: float, y: float, dx: float, dy: float, **kwargs) -> FancyArrow:
  2349. return gca().arrow(x, y, dx, dy, **kwargs)
  2350. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2351. @_copy_docstring_and_deprecators(Axes.autoscale)
  2352. def autoscale(
  2353. enable: bool = True,
  2354. axis: Literal["both", "x", "y"] = "both",
  2355. tight: bool | None = None,
  2356. ) -> None:
  2357. gca().autoscale(enable=enable, axis=axis, tight=tight)
  2358. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2359. @_copy_docstring_and_deprecators(Axes.axhline)
  2360. def axhline(y: float = 0, xmin: float = 0, xmax: float = 1, **kwargs) -> Line2D:
  2361. return gca().axhline(y=y, xmin=xmin, xmax=xmax, **kwargs)
  2362. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2363. @_copy_docstring_and_deprecators(Axes.axhspan)
  2364. def axhspan(
  2365. ymin: float, ymax: float, xmin: float = 0, xmax: float = 1, **kwargs
  2366. ) -> Rectangle:
  2367. return gca().axhspan(ymin, ymax, xmin=xmin, xmax=xmax, **kwargs)
  2368. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2369. @_copy_docstring_and_deprecators(Axes.axis)
  2370. def axis(
  2371. arg: tuple[float, float, float, float] | bool | str | None = None,
  2372. /,
  2373. *,
  2374. emit: bool = True,
  2375. **kwargs,
  2376. ) -> tuple[float, float, float, float]:
  2377. return gca().axis(arg, emit=emit, **kwargs)
  2378. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2379. @_copy_docstring_and_deprecators(Axes.axline)
  2380. def axline(
  2381. xy1: tuple[float, float],
  2382. xy2: tuple[float, float] | None = None,
  2383. *,
  2384. slope: float | None = None,
  2385. **kwargs,
  2386. ) -> AxLine:
  2387. return gca().axline(xy1, xy2=xy2, slope=slope, **kwargs)
  2388. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2389. @_copy_docstring_and_deprecators(Axes.axvline)
  2390. def axvline(x: float = 0, ymin: float = 0, ymax: float = 1, **kwargs) -> Line2D:
  2391. return gca().axvline(x=x, ymin=ymin, ymax=ymax, **kwargs)
  2392. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2393. @_copy_docstring_and_deprecators(Axes.axvspan)
  2394. def axvspan(
  2395. xmin: float, xmax: float, ymin: float = 0, ymax: float = 1, **kwargs
  2396. ) -> Rectangle:
  2397. return gca().axvspan(xmin, xmax, ymin=ymin, ymax=ymax, **kwargs)
  2398. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2399. @_copy_docstring_and_deprecators(Axes.bar)
  2400. def bar(
  2401. x: float | ArrayLike,
  2402. height: float | ArrayLike,
  2403. width: float | ArrayLike = 0.8,
  2404. bottom: float | ArrayLike | None = None,
  2405. *,
  2406. align: Literal["center", "edge"] = "center",
  2407. data=None,
  2408. **kwargs,
  2409. ) -> BarContainer:
  2410. return gca().bar(
  2411. x,
  2412. height,
  2413. width=width,
  2414. bottom=bottom,
  2415. align=align,
  2416. **({"data": data} if data is not None else {}),
  2417. **kwargs,
  2418. )
  2419. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2420. @_copy_docstring_and_deprecators(Axes.barbs)
  2421. def barbs(*args, data=None, **kwargs) -> Barbs:
  2422. return gca().barbs(*args, **({"data": data} if data is not None else {}), **kwargs)
  2423. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2424. @_copy_docstring_and_deprecators(Axes.barh)
  2425. def barh(
  2426. y: float | ArrayLike,
  2427. width: float | ArrayLike,
  2428. height: float | ArrayLike = 0.8,
  2429. left: float | ArrayLike | None = None,
  2430. *,
  2431. align: Literal["center", "edge"] = "center",
  2432. data=None,
  2433. **kwargs,
  2434. ) -> BarContainer:
  2435. return gca().barh(
  2436. y,
  2437. width,
  2438. height=height,
  2439. left=left,
  2440. align=align,
  2441. **({"data": data} if data is not None else {}),
  2442. **kwargs,
  2443. )
  2444. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2445. @_copy_docstring_and_deprecators(Axes.bar_label)
  2446. def bar_label(
  2447. container: BarContainer,
  2448. labels: ArrayLike | None = None,
  2449. *,
  2450. fmt: str | Callable[[float], str] = "%g",
  2451. label_type: Literal["center", "edge"] = "edge",
  2452. padding: float = 0,
  2453. **kwargs,
  2454. ) -> list[Annotation]:
  2455. return gca().bar_label(
  2456. container,
  2457. labels=labels,
  2458. fmt=fmt,
  2459. label_type=label_type,
  2460. padding=padding,
  2461. **kwargs,
  2462. )
  2463. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2464. @_copy_docstring_and_deprecators(Axes.boxplot)
  2465. def boxplot(
  2466. x: ArrayLike | Sequence[ArrayLike],
  2467. notch: bool | None = None,
  2468. sym: str | None = None,
  2469. vert: bool | None = None,
  2470. orientation: Literal["vertical", "horizontal"] = "vertical",
  2471. whis: float | tuple[float, float] | None = None,
  2472. positions: ArrayLike | None = None,
  2473. widths: float | ArrayLike | None = None,
  2474. patch_artist: bool | None = None,
  2475. bootstrap: int | None = None,
  2476. usermedians: ArrayLike | None = None,
  2477. conf_intervals: ArrayLike | None = None,
  2478. meanline: bool | None = None,
  2479. showmeans: bool | None = None,
  2480. showcaps: bool | None = None,
  2481. showbox: bool | None = None,
  2482. showfliers: bool | None = None,
  2483. boxprops: dict[str, Any] | None = None,
  2484. tick_labels: Sequence[str] | None = None,
  2485. flierprops: dict[str, Any] | None = None,
  2486. medianprops: dict[str, Any] | None = None,
  2487. meanprops: dict[str, Any] | None = None,
  2488. capprops: dict[str, Any] | None = None,
  2489. whiskerprops: dict[str, Any] | None = None,
  2490. manage_ticks: bool = True,
  2491. autorange: bool = False,
  2492. zorder: float | None = None,
  2493. capwidths: float | ArrayLike | None = None,
  2494. label: Sequence[str] | None = None,
  2495. *,
  2496. data=None,
  2497. ) -> dict[str, Any]:
  2498. return gca().boxplot(
  2499. x,
  2500. notch=notch,
  2501. sym=sym,
  2502. vert=vert,
  2503. orientation=orientation,
  2504. whis=whis,
  2505. positions=positions,
  2506. widths=widths,
  2507. patch_artist=patch_artist,
  2508. bootstrap=bootstrap,
  2509. usermedians=usermedians,
  2510. conf_intervals=conf_intervals,
  2511. meanline=meanline,
  2512. showmeans=showmeans,
  2513. showcaps=showcaps,
  2514. showbox=showbox,
  2515. showfliers=showfliers,
  2516. boxprops=boxprops,
  2517. tick_labels=tick_labels,
  2518. flierprops=flierprops,
  2519. medianprops=medianprops,
  2520. meanprops=meanprops,
  2521. capprops=capprops,
  2522. whiskerprops=whiskerprops,
  2523. manage_ticks=manage_ticks,
  2524. autorange=autorange,
  2525. zorder=zorder,
  2526. capwidths=capwidths,
  2527. label=label,
  2528. **({"data": data} if data is not None else {}),
  2529. )
  2530. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2531. @_copy_docstring_and_deprecators(Axes.broken_barh)
  2532. def broken_barh(
  2533. xranges: Sequence[tuple[float, float]],
  2534. yrange: tuple[float, float],
  2535. *,
  2536. data=None,
  2537. **kwargs,
  2538. ) -> PolyCollection:
  2539. return gca().broken_barh(
  2540. xranges, yrange, **({"data": data} if data is not None else {}), **kwargs
  2541. )
  2542. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2543. @_copy_docstring_and_deprecators(Axes.clabel)
  2544. def clabel(CS: ContourSet, levels: ArrayLike | None = None, **kwargs) -> list[Text]:
  2545. return gca().clabel(CS, levels=levels, **kwargs)
  2546. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2547. @_copy_docstring_and_deprecators(Axes.cohere)
  2548. def cohere(
  2549. x: ArrayLike,
  2550. y: ArrayLike,
  2551. NFFT: int = 256,
  2552. Fs: float = 2,
  2553. Fc: int = 0,
  2554. detrend: (
  2555. Literal["none", "mean", "linear"] | Callable[[ArrayLike], ArrayLike]
  2556. ) = mlab.detrend_none,
  2557. window: Callable[[ArrayLike], ArrayLike] | ArrayLike = mlab.window_hanning,
  2558. noverlap: int = 0,
  2559. pad_to: int | None = None,
  2560. sides: Literal["default", "onesided", "twosided"] = "default",
  2561. scale_by_freq: bool | None = None,
  2562. *,
  2563. data=None,
  2564. **kwargs,
  2565. ) -> tuple[np.ndarray, np.ndarray]:
  2566. return gca().cohere(
  2567. x,
  2568. y,
  2569. NFFT=NFFT,
  2570. Fs=Fs,
  2571. Fc=Fc,
  2572. detrend=detrend,
  2573. window=window,
  2574. noverlap=noverlap,
  2575. pad_to=pad_to,
  2576. sides=sides,
  2577. scale_by_freq=scale_by_freq,
  2578. **({"data": data} if data is not None else {}),
  2579. **kwargs,
  2580. )
  2581. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2582. @_copy_docstring_and_deprecators(Axes.contour)
  2583. def contour(*args, data=None, **kwargs) -> QuadContourSet:
  2584. __ret = gca().contour(
  2585. *args, **({"data": data} if data is not None else {}), **kwargs
  2586. )
  2587. if __ret._A is not None: # type: ignore[attr-defined]
  2588. sci(__ret)
  2589. return __ret
  2590. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2591. @_copy_docstring_and_deprecators(Axes.contourf)
  2592. def contourf(*args, data=None, **kwargs) -> QuadContourSet:
  2593. __ret = gca().contourf(
  2594. *args, **({"data": data} if data is not None else {}), **kwargs
  2595. )
  2596. if __ret._A is not None: # type: ignore[attr-defined]
  2597. sci(__ret)
  2598. return __ret
  2599. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2600. @_copy_docstring_and_deprecators(Axes.csd)
  2601. def csd(
  2602. x: ArrayLike,
  2603. y: ArrayLike,
  2604. NFFT: int | None = None,
  2605. Fs: float | None = None,
  2606. Fc: int | None = None,
  2607. detrend: (
  2608. Literal["none", "mean", "linear"] | Callable[[ArrayLike], ArrayLike] | None
  2609. ) = None,
  2610. window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = None,
  2611. noverlap: int | None = None,
  2612. pad_to: int | None = None,
  2613. sides: Literal["default", "onesided", "twosided"] | None = None,
  2614. scale_by_freq: bool | None = None,
  2615. return_line: bool | None = None,
  2616. *,
  2617. data=None,
  2618. **kwargs,
  2619. ) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, Line2D]:
  2620. return gca().csd(
  2621. x,
  2622. y,
  2623. NFFT=NFFT,
  2624. Fs=Fs,
  2625. Fc=Fc,
  2626. detrend=detrend,
  2627. window=window,
  2628. noverlap=noverlap,
  2629. pad_to=pad_to,
  2630. sides=sides,
  2631. scale_by_freq=scale_by_freq,
  2632. return_line=return_line,
  2633. **({"data": data} if data is not None else {}),
  2634. **kwargs,
  2635. )
  2636. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2637. @_copy_docstring_and_deprecators(Axes.ecdf)
  2638. def ecdf(
  2639. x: ArrayLike,
  2640. weights: ArrayLike | None = None,
  2641. *,
  2642. complementary: bool = False,
  2643. orientation: Literal["vertical", "horizontal"] = "vertical",
  2644. compress: bool = False,
  2645. data=None,
  2646. **kwargs,
  2647. ) -> Line2D:
  2648. return gca().ecdf(
  2649. x,
  2650. weights=weights,
  2651. complementary=complementary,
  2652. orientation=orientation,
  2653. compress=compress,
  2654. **({"data": data} if data is not None else {}),
  2655. **kwargs,
  2656. )
  2657. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2658. @_copy_docstring_and_deprecators(Axes.errorbar)
  2659. def errorbar(
  2660. x: float | ArrayLike,
  2661. y: float | ArrayLike,
  2662. yerr: float | ArrayLike | None = None,
  2663. xerr: float | ArrayLike | None = None,
  2664. fmt: str = "",
  2665. ecolor: ColorType | None = None,
  2666. elinewidth: float | None = None,
  2667. capsize: float | None = None,
  2668. barsabove: bool = False,
  2669. lolims: bool | ArrayLike = False,
  2670. uplims: bool | ArrayLike = False,
  2671. xlolims: bool | ArrayLike = False,
  2672. xuplims: bool | ArrayLike = False,
  2673. errorevery: int | tuple[int, int] = 1,
  2674. capthick: float | None = None,
  2675. *,
  2676. data=None,
  2677. **kwargs,
  2678. ) -> ErrorbarContainer:
  2679. return gca().errorbar(
  2680. x,
  2681. y,
  2682. yerr=yerr,
  2683. xerr=xerr,
  2684. fmt=fmt,
  2685. ecolor=ecolor,
  2686. elinewidth=elinewidth,
  2687. capsize=capsize,
  2688. barsabove=barsabove,
  2689. lolims=lolims,
  2690. uplims=uplims,
  2691. xlolims=xlolims,
  2692. xuplims=xuplims,
  2693. errorevery=errorevery,
  2694. capthick=capthick,
  2695. **({"data": data} if data is not None else {}),
  2696. **kwargs,
  2697. )
  2698. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2699. @_copy_docstring_and_deprecators(Axes.eventplot)
  2700. def eventplot(
  2701. positions: ArrayLike | Sequence[ArrayLike],
  2702. orientation: Literal["horizontal", "vertical"] = "horizontal",
  2703. lineoffsets: float | Sequence[float] = 1,
  2704. linelengths: float | Sequence[float] = 1,
  2705. linewidths: float | Sequence[float] | None = None,
  2706. colors: ColorType | Sequence[ColorType] | None = None,
  2707. alpha: float | Sequence[float] | None = None,
  2708. linestyles: LineStyleType | Sequence[LineStyleType] = "solid",
  2709. *,
  2710. data=None,
  2711. **kwargs,
  2712. ) -> EventCollection:
  2713. return gca().eventplot(
  2714. positions,
  2715. orientation=orientation,
  2716. lineoffsets=lineoffsets,
  2717. linelengths=linelengths,
  2718. linewidths=linewidths,
  2719. colors=colors,
  2720. alpha=alpha,
  2721. linestyles=linestyles,
  2722. **({"data": data} if data is not None else {}),
  2723. **kwargs,
  2724. )
  2725. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2726. @_copy_docstring_and_deprecators(Axes.fill)
  2727. def fill(*args, data=None, **kwargs) -> list[Polygon]:
  2728. return gca().fill(*args, **({"data": data} if data is not None else {}), **kwargs)
  2729. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2730. @_copy_docstring_and_deprecators(Axes.fill_between)
  2731. def fill_between(
  2732. x: ArrayLike,
  2733. y1: ArrayLike | float,
  2734. y2: ArrayLike | float = 0,
  2735. where: Sequence[bool] | None = None,
  2736. interpolate: bool = False,
  2737. step: Literal["pre", "post", "mid"] | None = None,
  2738. *,
  2739. data=None,
  2740. **kwargs,
  2741. ) -> FillBetweenPolyCollection:
  2742. return gca().fill_between(
  2743. x,
  2744. y1,
  2745. y2=y2,
  2746. where=where,
  2747. interpolate=interpolate,
  2748. step=step,
  2749. **({"data": data} if data is not None else {}),
  2750. **kwargs,
  2751. )
  2752. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2753. @_copy_docstring_and_deprecators(Axes.fill_betweenx)
  2754. def fill_betweenx(
  2755. y: ArrayLike,
  2756. x1: ArrayLike | float,
  2757. x2: ArrayLike | float = 0,
  2758. where: Sequence[bool] | None = None,
  2759. step: Literal["pre", "post", "mid"] | None = None,
  2760. interpolate: bool = False,
  2761. *,
  2762. data=None,
  2763. **kwargs,
  2764. ) -> FillBetweenPolyCollection:
  2765. return gca().fill_betweenx(
  2766. y,
  2767. x1,
  2768. x2=x2,
  2769. where=where,
  2770. step=step,
  2771. interpolate=interpolate,
  2772. **({"data": data} if data is not None else {}),
  2773. **kwargs,
  2774. )
  2775. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2776. @_copy_docstring_and_deprecators(Axes.grid)
  2777. def grid(
  2778. visible: bool | None = None,
  2779. which: Literal["major", "minor", "both"] = "major",
  2780. axis: Literal["both", "x", "y"] = "both",
  2781. **kwargs,
  2782. ) -> None:
  2783. gca().grid(visible=visible, which=which, axis=axis, **kwargs)
  2784. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2785. @_copy_docstring_and_deprecators(Axes.hexbin)
  2786. def hexbin(
  2787. x: ArrayLike,
  2788. y: ArrayLike,
  2789. C: ArrayLike | None = None,
  2790. gridsize: int | tuple[int, int] = 100,
  2791. bins: Literal["log"] | int | Sequence[float] | None = None,
  2792. xscale: Literal["linear", "log"] = "linear",
  2793. yscale: Literal["linear", "log"] = "linear",
  2794. extent: tuple[float, float, float, float] | None = None,
  2795. cmap: str | Colormap | None = None,
  2796. norm: str | Normalize | None = None,
  2797. vmin: float | None = None,
  2798. vmax: float | None = None,
  2799. alpha: float | None = None,
  2800. linewidths: float | None = None,
  2801. edgecolors: Literal["face", "none"] | ColorType = "face",
  2802. reduce_C_function: Callable[[np.ndarray | list[float]], float] = np.mean,
  2803. mincnt: int | None = None,
  2804. marginals: bool = False,
  2805. colorizer: Colorizer | None = None,
  2806. *,
  2807. data=None,
  2808. **kwargs,
  2809. ) -> PolyCollection:
  2810. __ret = gca().hexbin(
  2811. x,
  2812. y,
  2813. C=C,
  2814. gridsize=gridsize,
  2815. bins=bins,
  2816. xscale=xscale,
  2817. yscale=yscale,
  2818. extent=extent,
  2819. cmap=cmap,
  2820. norm=norm,
  2821. vmin=vmin,
  2822. vmax=vmax,
  2823. alpha=alpha,
  2824. linewidths=linewidths,
  2825. edgecolors=edgecolors,
  2826. reduce_C_function=reduce_C_function,
  2827. mincnt=mincnt,
  2828. marginals=marginals,
  2829. colorizer=colorizer,
  2830. **({"data": data} if data is not None else {}),
  2831. **kwargs,
  2832. )
  2833. sci(__ret)
  2834. return __ret
  2835. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2836. @_copy_docstring_and_deprecators(Axes.hist)
  2837. def hist(
  2838. x: ArrayLike | Sequence[ArrayLike],
  2839. bins: int | Sequence[float] | str | None = None,
  2840. range: tuple[float, float] | None = None,
  2841. density: bool = False,
  2842. weights: ArrayLike | None = None,
  2843. cumulative: bool | float = False,
  2844. bottom: ArrayLike | float | None = None,
  2845. histtype: Literal["bar", "barstacked", "step", "stepfilled"] = "bar",
  2846. align: Literal["left", "mid", "right"] = "mid",
  2847. orientation: Literal["vertical", "horizontal"] = "vertical",
  2848. rwidth: float | None = None,
  2849. log: bool = False,
  2850. color: ColorType | Sequence[ColorType] | None = None,
  2851. label: str | Sequence[str] | None = None,
  2852. stacked: bool = False,
  2853. *,
  2854. data=None,
  2855. **kwargs,
  2856. ) -> tuple[
  2857. np.ndarray | list[np.ndarray],
  2858. np.ndarray,
  2859. BarContainer | Polygon | list[BarContainer | Polygon],
  2860. ]:
  2861. return gca().hist(
  2862. x,
  2863. bins=bins,
  2864. range=range,
  2865. density=density,
  2866. weights=weights,
  2867. cumulative=cumulative,
  2868. bottom=bottom,
  2869. histtype=histtype,
  2870. align=align,
  2871. orientation=orientation,
  2872. rwidth=rwidth,
  2873. log=log,
  2874. color=color,
  2875. label=label,
  2876. stacked=stacked,
  2877. **({"data": data} if data is not None else {}),
  2878. **kwargs,
  2879. )
  2880. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2881. @_copy_docstring_and_deprecators(Axes.stairs)
  2882. def stairs(
  2883. values: ArrayLike,
  2884. edges: ArrayLike | None = None,
  2885. *,
  2886. orientation: Literal["vertical", "horizontal"] = "vertical",
  2887. baseline: float | ArrayLike | None = 0,
  2888. fill: bool = False,
  2889. data=None,
  2890. **kwargs,
  2891. ) -> StepPatch:
  2892. return gca().stairs(
  2893. values,
  2894. edges=edges,
  2895. orientation=orientation,
  2896. baseline=baseline,
  2897. fill=fill,
  2898. **({"data": data} if data is not None else {}),
  2899. **kwargs,
  2900. )
  2901. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2902. @_copy_docstring_and_deprecators(Axes.hist2d)
  2903. def hist2d(
  2904. x: ArrayLike,
  2905. y: ArrayLike,
  2906. bins: None | int | tuple[int, int] | ArrayLike | tuple[ArrayLike, ArrayLike] = 10,
  2907. range: ArrayLike | None = None,
  2908. density: bool = False,
  2909. weights: ArrayLike | None = None,
  2910. cmin: float | None = None,
  2911. cmax: float | None = None,
  2912. *,
  2913. data=None,
  2914. **kwargs,
  2915. ) -> tuple[np.ndarray, np.ndarray, np.ndarray, QuadMesh]:
  2916. __ret = gca().hist2d(
  2917. x,
  2918. y,
  2919. bins=bins,
  2920. range=range,
  2921. density=density,
  2922. weights=weights,
  2923. cmin=cmin,
  2924. cmax=cmax,
  2925. **({"data": data} if data is not None else {}),
  2926. **kwargs,
  2927. )
  2928. sci(__ret[-1])
  2929. return __ret
  2930. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2931. @_copy_docstring_and_deprecators(Axes.hlines)
  2932. def hlines(
  2933. y: float | ArrayLike,
  2934. xmin: float | ArrayLike,
  2935. xmax: float | ArrayLike,
  2936. colors: ColorType | Sequence[ColorType] | None = None,
  2937. linestyles: LineStyleType = "solid",
  2938. label: str = "",
  2939. *,
  2940. data=None,
  2941. **kwargs,
  2942. ) -> LineCollection:
  2943. return gca().hlines(
  2944. y,
  2945. xmin,
  2946. xmax,
  2947. colors=colors,
  2948. linestyles=linestyles,
  2949. label=label,
  2950. **({"data": data} if data is not None else {}),
  2951. **kwargs,
  2952. )
  2953. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2954. @_copy_docstring_and_deprecators(Axes.imshow)
  2955. def imshow(
  2956. X: ArrayLike | PIL.Image.Image,
  2957. cmap: str | Colormap | None = None,
  2958. norm: str | Normalize | None = None,
  2959. *,
  2960. aspect: Literal["equal", "auto"] | float | None = None,
  2961. interpolation: str | None = None,
  2962. alpha: float | ArrayLike | None = None,
  2963. vmin: float | None = None,
  2964. vmax: float | None = None,
  2965. colorizer: Colorizer | None = None,
  2966. origin: Literal["upper", "lower"] | None = None,
  2967. extent: tuple[float, float, float, float] | None = None,
  2968. interpolation_stage: Literal["data", "rgba", "auto"] | None = None,
  2969. filternorm: bool = True,
  2970. filterrad: float = 4.0,
  2971. resample: bool | None = None,
  2972. url: str | None = None,
  2973. data=None,
  2974. **kwargs,
  2975. ) -> AxesImage:
  2976. __ret = gca().imshow(
  2977. X,
  2978. cmap=cmap,
  2979. norm=norm,
  2980. aspect=aspect,
  2981. interpolation=interpolation,
  2982. alpha=alpha,
  2983. vmin=vmin,
  2984. vmax=vmax,
  2985. colorizer=colorizer,
  2986. origin=origin,
  2987. extent=extent,
  2988. interpolation_stage=interpolation_stage,
  2989. filternorm=filternorm,
  2990. filterrad=filterrad,
  2991. resample=resample,
  2992. url=url,
  2993. **({"data": data} if data is not None else {}),
  2994. **kwargs,
  2995. )
  2996. sci(__ret)
  2997. return __ret
  2998. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2999. @_copy_docstring_and_deprecators(Axes.legend)
  3000. def legend(*args, **kwargs) -> Legend:
  3001. return gca().legend(*args, **kwargs)
  3002. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3003. @_copy_docstring_and_deprecators(Axes.locator_params)
  3004. def locator_params(
  3005. axis: Literal["both", "x", "y"] = "both", tight: bool | None = None, **kwargs
  3006. ) -> None:
  3007. gca().locator_params(axis=axis, tight=tight, **kwargs)
  3008. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3009. @_copy_docstring_and_deprecators(Axes.loglog)
  3010. def loglog(*args, **kwargs) -> list[Line2D]:
  3011. return gca().loglog(*args, **kwargs)
  3012. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3013. @_copy_docstring_and_deprecators(Axes.magnitude_spectrum)
  3014. def magnitude_spectrum(
  3015. x: ArrayLike,
  3016. Fs: float | None = None,
  3017. Fc: int | None = None,
  3018. window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = None,
  3019. pad_to: int | None = None,
  3020. sides: Literal["default", "onesided", "twosided"] | None = None,
  3021. scale: Literal["default", "linear", "dB"] | None = None,
  3022. *,
  3023. data=None,
  3024. **kwargs,
  3025. ) -> tuple[np.ndarray, np.ndarray, Line2D]:
  3026. return gca().magnitude_spectrum(
  3027. x,
  3028. Fs=Fs,
  3029. Fc=Fc,
  3030. window=window,
  3031. pad_to=pad_to,
  3032. sides=sides,
  3033. scale=scale,
  3034. **({"data": data} if data is not None else {}),
  3035. **kwargs,
  3036. )
  3037. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3038. @_copy_docstring_and_deprecators(Axes.margins)
  3039. def margins(
  3040. *margins: float,
  3041. x: float | None = None,
  3042. y: float | None = None,
  3043. tight: bool | None = True,
  3044. ) -> tuple[float, float] | None:
  3045. return gca().margins(*margins, x=x, y=y, tight=tight)
  3046. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3047. @_copy_docstring_and_deprecators(Axes.minorticks_off)
  3048. def minorticks_off() -> None:
  3049. gca().minorticks_off()
  3050. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3051. @_copy_docstring_and_deprecators(Axes.minorticks_on)
  3052. def minorticks_on() -> None:
  3053. gca().minorticks_on()
  3054. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3055. @_copy_docstring_and_deprecators(Axes.pcolor)
  3056. def pcolor(
  3057. *args: ArrayLike,
  3058. shading: Literal["flat", "nearest", "auto"] | None = None,
  3059. alpha: float | None = None,
  3060. norm: str | Normalize | None = None,
  3061. cmap: str | Colormap | None = None,
  3062. vmin: float | None = None,
  3063. vmax: float | None = None,
  3064. colorizer: Colorizer | None = None,
  3065. data=None,
  3066. **kwargs,
  3067. ) -> Collection:
  3068. __ret = gca().pcolor(
  3069. *args,
  3070. shading=shading,
  3071. alpha=alpha,
  3072. norm=norm,
  3073. cmap=cmap,
  3074. vmin=vmin,
  3075. vmax=vmax,
  3076. colorizer=colorizer,
  3077. **({"data": data} if data is not None else {}),
  3078. **kwargs,
  3079. )
  3080. sci(__ret)
  3081. return __ret
  3082. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3083. @_copy_docstring_and_deprecators(Axes.pcolormesh)
  3084. def pcolormesh(
  3085. *args: ArrayLike,
  3086. alpha: float | None = None,
  3087. norm: str | Normalize | None = None,
  3088. cmap: str | Colormap | None = None,
  3089. vmin: float | None = None,
  3090. vmax: float | None = None,
  3091. colorizer: Colorizer | None = None,
  3092. shading: Literal["flat", "nearest", "gouraud", "auto"] | None = None,
  3093. antialiased: bool = False,
  3094. data=None,
  3095. **kwargs,
  3096. ) -> QuadMesh:
  3097. __ret = gca().pcolormesh(
  3098. *args,
  3099. alpha=alpha,
  3100. norm=norm,
  3101. cmap=cmap,
  3102. vmin=vmin,
  3103. vmax=vmax,
  3104. colorizer=colorizer,
  3105. shading=shading,
  3106. antialiased=antialiased,
  3107. **({"data": data} if data is not None else {}),
  3108. **kwargs,
  3109. )
  3110. sci(__ret)
  3111. return __ret
  3112. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3113. @_copy_docstring_and_deprecators(Axes.phase_spectrum)
  3114. def phase_spectrum(
  3115. x: ArrayLike,
  3116. Fs: float | None = None,
  3117. Fc: int | None = None,
  3118. window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = None,
  3119. pad_to: int | None = None,
  3120. sides: Literal["default", "onesided", "twosided"] | None = None,
  3121. *,
  3122. data=None,
  3123. **kwargs,
  3124. ) -> tuple[np.ndarray, np.ndarray, Line2D]:
  3125. return gca().phase_spectrum(
  3126. x,
  3127. Fs=Fs,
  3128. Fc=Fc,
  3129. window=window,
  3130. pad_to=pad_to,
  3131. sides=sides,
  3132. **({"data": data} if data is not None else {}),
  3133. **kwargs,
  3134. )
  3135. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3136. @_copy_docstring_and_deprecators(Axes.pie)
  3137. def pie(
  3138. x: ArrayLike,
  3139. explode: ArrayLike | None = None,
  3140. labels: Sequence[str] | None = None,
  3141. colors: ColorType | Sequence[ColorType] | None = None,
  3142. autopct: str | Callable[[float], str] | None = None,
  3143. pctdistance: float = 0.6,
  3144. shadow: bool = False,
  3145. labeldistance: float | None = 1.1,
  3146. startangle: float = 0,
  3147. radius: float = 1,
  3148. counterclock: bool = True,
  3149. wedgeprops: dict[str, Any] | None = None,
  3150. textprops: dict[str, Any] | None = None,
  3151. center: tuple[float, float] = (0, 0),
  3152. frame: bool = False,
  3153. rotatelabels: bool = False,
  3154. *,
  3155. normalize: bool = True,
  3156. hatch: str | Sequence[str] | None = None,
  3157. data=None,
  3158. ) -> tuple[list[Wedge], list[Text]] | tuple[list[Wedge], list[Text], list[Text]]:
  3159. return gca().pie(
  3160. x,
  3161. explode=explode,
  3162. labels=labels,
  3163. colors=colors,
  3164. autopct=autopct,
  3165. pctdistance=pctdistance,
  3166. shadow=shadow,
  3167. labeldistance=labeldistance,
  3168. startangle=startangle,
  3169. radius=radius,
  3170. counterclock=counterclock,
  3171. wedgeprops=wedgeprops,
  3172. textprops=textprops,
  3173. center=center,
  3174. frame=frame,
  3175. rotatelabels=rotatelabels,
  3176. normalize=normalize,
  3177. hatch=hatch,
  3178. **({"data": data} if data is not None else {}),
  3179. )
  3180. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3181. @_copy_docstring_and_deprecators(Axes.plot)
  3182. def plot(
  3183. *args: float | ArrayLike | str,
  3184. scalex: bool = True,
  3185. scaley: bool = True,
  3186. data=None,
  3187. **kwargs,
  3188. ) -> list[Line2D]:
  3189. return gca().plot(
  3190. *args,
  3191. scalex=scalex,
  3192. scaley=scaley,
  3193. **({"data": data} if data is not None else {}),
  3194. **kwargs,
  3195. )
  3196. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3197. @_copy_docstring_and_deprecators(Axes.plot_date)
  3198. def plot_date(
  3199. x: ArrayLike,
  3200. y: ArrayLike,
  3201. fmt: str = "o",
  3202. tz: str | datetime.tzinfo | None = None,
  3203. xdate: bool = True,
  3204. ydate: bool = False,
  3205. *,
  3206. data=None,
  3207. **kwargs,
  3208. ) -> list[Line2D]:
  3209. return gca().plot_date(
  3210. x,
  3211. y,
  3212. fmt=fmt,
  3213. tz=tz,
  3214. xdate=xdate,
  3215. ydate=ydate,
  3216. **({"data": data} if data is not None else {}),
  3217. **kwargs,
  3218. )
  3219. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3220. @_copy_docstring_and_deprecators(Axes.psd)
  3221. def psd(
  3222. x: ArrayLike,
  3223. NFFT: int | None = None,
  3224. Fs: float | None = None,
  3225. Fc: int | None = None,
  3226. detrend: (
  3227. Literal["none", "mean", "linear"] | Callable[[ArrayLike], ArrayLike] | None
  3228. ) = None,
  3229. window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = None,
  3230. noverlap: int | None = None,
  3231. pad_to: int | None = None,
  3232. sides: Literal["default", "onesided", "twosided"] | None = None,
  3233. scale_by_freq: bool | None = None,
  3234. return_line: bool | None = None,
  3235. *,
  3236. data=None,
  3237. **kwargs,
  3238. ) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, Line2D]:
  3239. return gca().psd(
  3240. x,
  3241. NFFT=NFFT,
  3242. Fs=Fs,
  3243. Fc=Fc,
  3244. detrend=detrend,
  3245. window=window,
  3246. noverlap=noverlap,
  3247. pad_to=pad_to,
  3248. sides=sides,
  3249. scale_by_freq=scale_by_freq,
  3250. return_line=return_line,
  3251. **({"data": data} if data is not None else {}),
  3252. **kwargs,
  3253. )
  3254. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3255. @_copy_docstring_and_deprecators(Axes.quiver)
  3256. def quiver(*args, data=None, **kwargs) -> Quiver:
  3257. __ret = gca().quiver(
  3258. *args, **({"data": data} if data is not None else {}), **kwargs
  3259. )
  3260. sci(__ret)
  3261. return __ret
  3262. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3263. @_copy_docstring_and_deprecators(Axes.quiverkey)
  3264. def quiverkey(
  3265. Q: Quiver, X: float, Y: float, U: float, label: str, **kwargs
  3266. ) -> QuiverKey:
  3267. return gca().quiverkey(Q, X, Y, U, label, **kwargs)
  3268. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3269. @_copy_docstring_and_deprecators(Axes.scatter)
  3270. def scatter(
  3271. x: float | ArrayLike,
  3272. y: float | ArrayLike,
  3273. s: float | ArrayLike | None = None,
  3274. c: ArrayLike | Sequence[ColorType] | ColorType | None = None,
  3275. marker: MarkerType | None = None,
  3276. cmap: str | Colormap | None = None,
  3277. norm: str | Normalize | None = None,
  3278. vmin: float | None = None,
  3279. vmax: float | None = None,
  3280. alpha: float | None = None,
  3281. linewidths: float | Sequence[float] | None = None,
  3282. *,
  3283. edgecolors: Literal["face", "none"] | ColorType | Sequence[ColorType] | None = None,
  3284. colorizer: Colorizer | None = None,
  3285. plotnonfinite: bool = False,
  3286. data=None,
  3287. **kwargs,
  3288. ) -> PathCollection:
  3289. __ret = gca().scatter(
  3290. x,
  3291. y,
  3292. s=s,
  3293. c=c,
  3294. marker=marker,
  3295. cmap=cmap,
  3296. norm=norm,
  3297. vmin=vmin,
  3298. vmax=vmax,
  3299. alpha=alpha,
  3300. linewidths=linewidths,
  3301. edgecolors=edgecolors,
  3302. colorizer=colorizer,
  3303. plotnonfinite=plotnonfinite,
  3304. **({"data": data} if data is not None else {}),
  3305. **kwargs,
  3306. )
  3307. sci(__ret)
  3308. return __ret
  3309. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3310. @_copy_docstring_and_deprecators(Axes.semilogx)
  3311. def semilogx(*args, **kwargs) -> list[Line2D]:
  3312. return gca().semilogx(*args, **kwargs)
  3313. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3314. @_copy_docstring_and_deprecators(Axes.semilogy)
  3315. def semilogy(*args, **kwargs) -> list[Line2D]:
  3316. return gca().semilogy(*args, **kwargs)
  3317. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3318. @_copy_docstring_and_deprecators(Axes.specgram)
  3319. def specgram(
  3320. x: ArrayLike,
  3321. NFFT: int | None = None,
  3322. Fs: float | None = None,
  3323. Fc: int | None = None,
  3324. detrend: (
  3325. Literal["none", "mean", "linear"] | Callable[[ArrayLike], ArrayLike] | None
  3326. ) = None,
  3327. window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = None,
  3328. noverlap: int | None = None,
  3329. cmap: str | Colormap | None = None,
  3330. xextent: tuple[float, float] | None = None,
  3331. pad_to: int | None = None,
  3332. sides: Literal["default", "onesided", "twosided"] | None = None,
  3333. scale_by_freq: bool | None = None,
  3334. mode: Literal["default", "psd", "magnitude", "angle", "phase"] | None = None,
  3335. scale: Literal["default", "linear", "dB"] | None = None,
  3336. vmin: float | None = None,
  3337. vmax: float | None = None,
  3338. *,
  3339. data=None,
  3340. **kwargs,
  3341. ) -> tuple[np.ndarray, np.ndarray, np.ndarray, AxesImage]:
  3342. __ret = gca().specgram(
  3343. x,
  3344. NFFT=NFFT,
  3345. Fs=Fs,
  3346. Fc=Fc,
  3347. detrend=detrend,
  3348. window=window,
  3349. noverlap=noverlap,
  3350. cmap=cmap,
  3351. xextent=xextent,
  3352. pad_to=pad_to,
  3353. sides=sides,
  3354. scale_by_freq=scale_by_freq,
  3355. mode=mode,
  3356. scale=scale,
  3357. vmin=vmin,
  3358. vmax=vmax,
  3359. **({"data": data} if data is not None else {}),
  3360. **kwargs,
  3361. )
  3362. sci(__ret[-1])
  3363. return __ret
  3364. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3365. @_copy_docstring_and_deprecators(Axes.spy)
  3366. def spy(
  3367. Z: ArrayLike,
  3368. precision: float | Literal["present"] = 0,
  3369. marker: str | None = None,
  3370. markersize: float | None = None,
  3371. aspect: Literal["equal", "auto"] | float | None = "equal",
  3372. origin: Literal["upper", "lower"] = "upper",
  3373. **kwargs,
  3374. ) -> AxesImage:
  3375. __ret = gca().spy(
  3376. Z,
  3377. precision=precision,
  3378. marker=marker,
  3379. markersize=markersize,
  3380. aspect=aspect,
  3381. origin=origin,
  3382. **kwargs,
  3383. )
  3384. if isinstance(__ret, _ColorizerInterface):
  3385. sci(__ret)
  3386. return __ret
  3387. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3388. @_copy_docstring_and_deprecators(Axes.stackplot)
  3389. def stackplot(
  3390. x, *args, labels=(), colors=None, hatch=None, baseline="zero", data=None, **kwargs
  3391. ):
  3392. return gca().stackplot(
  3393. x,
  3394. *args,
  3395. labels=labels,
  3396. colors=colors,
  3397. hatch=hatch,
  3398. baseline=baseline,
  3399. **({"data": data} if data is not None else {}),
  3400. **kwargs,
  3401. )
  3402. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3403. @_copy_docstring_and_deprecators(Axes.stem)
  3404. def stem(
  3405. *args: ArrayLike | str,
  3406. linefmt: str | None = None,
  3407. markerfmt: str | None = None,
  3408. basefmt: str | None = None,
  3409. bottom: float = 0,
  3410. label: str | None = None,
  3411. orientation: Literal["vertical", "horizontal"] = "vertical",
  3412. data=None,
  3413. ) -> StemContainer:
  3414. return gca().stem(
  3415. *args,
  3416. linefmt=linefmt,
  3417. markerfmt=markerfmt,
  3418. basefmt=basefmt,
  3419. bottom=bottom,
  3420. label=label,
  3421. orientation=orientation,
  3422. **({"data": data} if data is not None else {}),
  3423. )
  3424. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3425. @_copy_docstring_and_deprecators(Axes.step)
  3426. def step(
  3427. x: ArrayLike,
  3428. y: ArrayLike,
  3429. *args,
  3430. where: Literal["pre", "post", "mid"] = "pre",
  3431. data=None,
  3432. **kwargs,
  3433. ) -> list[Line2D]:
  3434. return gca().step(
  3435. x,
  3436. y,
  3437. *args,
  3438. where=where,
  3439. **({"data": data} if data is not None else {}),
  3440. **kwargs,
  3441. )
  3442. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3443. @_copy_docstring_and_deprecators(Axes.streamplot)
  3444. def streamplot(
  3445. x,
  3446. y,
  3447. u,
  3448. v,
  3449. density=1,
  3450. linewidth=None,
  3451. color=None,
  3452. cmap=None,
  3453. norm=None,
  3454. arrowsize=1,
  3455. arrowstyle="-|>",
  3456. minlength=0.1,
  3457. transform=None,
  3458. zorder=None,
  3459. start_points=None,
  3460. maxlength=4.0,
  3461. integration_direction="both",
  3462. broken_streamlines=True,
  3463. *,
  3464. data=None,
  3465. ):
  3466. __ret = gca().streamplot(
  3467. x,
  3468. y,
  3469. u,
  3470. v,
  3471. density=density,
  3472. linewidth=linewidth,
  3473. color=color,
  3474. cmap=cmap,
  3475. norm=norm,
  3476. arrowsize=arrowsize,
  3477. arrowstyle=arrowstyle,
  3478. minlength=minlength,
  3479. transform=transform,
  3480. zorder=zorder,
  3481. start_points=start_points,
  3482. maxlength=maxlength,
  3483. integration_direction=integration_direction,
  3484. broken_streamlines=broken_streamlines,
  3485. **({"data": data} if data is not None else {}),
  3486. )
  3487. sci(__ret.lines)
  3488. return __ret
  3489. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3490. @_copy_docstring_and_deprecators(Axes.table)
  3491. def table(
  3492. cellText=None,
  3493. cellColours=None,
  3494. cellLoc="right",
  3495. colWidths=None,
  3496. rowLabels=None,
  3497. rowColours=None,
  3498. rowLoc="left",
  3499. colLabels=None,
  3500. colColours=None,
  3501. colLoc="center",
  3502. loc="bottom",
  3503. bbox=None,
  3504. edges="closed",
  3505. **kwargs,
  3506. ):
  3507. return gca().table(
  3508. cellText=cellText,
  3509. cellColours=cellColours,
  3510. cellLoc=cellLoc,
  3511. colWidths=colWidths,
  3512. rowLabels=rowLabels,
  3513. rowColours=rowColours,
  3514. rowLoc=rowLoc,
  3515. colLabels=colLabels,
  3516. colColours=colColours,
  3517. colLoc=colLoc,
  3518. loc=loc,
  3519. bbox=bbox,
  3520. edges=edges,
  3521. **kwargs,
  3522. )
  3523. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3524. @_copy_docstring_and_deprecators(Axes.text)
  3525. def text(
  3526. x: float, y: float, s: str, fontdict: dict[str, Any] | None = None, **kwargs
  3527. ) -> Text:
  3528. return gca().text(x, y, s, fontdict=fontdict, **kwargs)
  3529. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3530. @_copy_docstring_and_deprecators(Axes.tick_params)
  3531. def tick_params(axis: Literal["both", "x", "y"] = "both", **kwargs) -> None:
  3532. gca().tick_params(axis=axis, **kwargs)
  3533. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3534. @_copy_docstring_and_deprecators(Axes.ticklabel_format)
  3535. def ticklabel_format(
  3536. *,
  3537. axis: Literal["both", "x", "y"] = "both",
  3538. style: Literal["", "sci", "scientific", "plain"] | None = None,
  3539. scilimits: tuple[int, int] | None = None,
  3540. useOffset: bool | float | None = None,
  3541. useLocale: bool | None = None,
  3542. useMathText: bool | None = None,
  3543. ) -> None:
  3544. gca().ticklabel_format(
  3545. axis=axis,
  3546. style=style,
  3547. scilimits=scilimits,
  3548. useOffset=useOffset,
  3549. useLocale=useLocale,
  3550. useMathText=useMathText,
  3551. )
  3552. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3553. @_copy_docstring_and_deprecators(Axes.tricontour)
  3554. def tricontour(*args, **kwargs):
  3555. __ret = gca().tricontour(*args, **kwargs)
  3556. if __ret._A is not None: # type: ignore[attr-defined]
  3557. sci(__ret)
  3558. return __ret
  3559. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3560. @_copy_docstring_and_deprecators(Axes.tricontourf)
  3561. def tricontourf(*args, **kwargs):
  3562. __ret = gca().tricontourf(*args, **kwargs)
  3563. if __ret._A is not None: # type: ignore[attr-defined]
  3564. sci(__ret)
  3565. return __ret
  3566. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3567. @_copy_docstring_and_deprecators(Axes.tripcolor)
  3568. def tripcolor(
  3569. *args,
  3570. alpha=1.0,
  3571. norm=None,
  3572. cmap=None,
  3573. vmin=None,
  3574. vmax=None,
  3575. shading="flat",
  3576. facecolors=None,
  3577. **kwargs,
  3578. ):
  3579. __ret = gca().tripcolor(
  3580. *args,
  3581. alpha=alpha,
  3582. norm=norm,
  3583. cmap=cmap,
  3584. vmin=vmin,
  3585. vmax=vmax,
  3586. shading=shading,
  3587. facecolors=facecolors,
  3588. **kwargs,
  3589. )
  3590. sci(__ret)
  3591. return __ret
  3592. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3593. @_copy_docstring_and_deprecators(Axes.triplot)
  3594. def triplot(*args, **kwargs):
  3595. return gca().triplot(*args, **kwargs)
  3596. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3597. @_copy_docstring_and_deprecators(Axes.violinplot)
  3598. def violinplot(
  3599. dataset: ArrayLike | Sequence[ArrayLike],
  3600. positions: ArrayLike | None = None,
  3601. vert: bool | None = None,
  3602. orientation: Literal["vertical", "horizontal"] = "vertical",
  3603. widths: float | ArrayLike = 0.5,
  3604. showmeans: bool = False,
  3605. showextrema: bool = True,
  3606. showmedians: bool = False,
  3607. quantiles: Sequence[float | Sequence[float]] | None = None,
  3608. points: int = 100,
  3609. bw_method: (
  3610. Literal["scott", "silverman"] | float | Callable[[GaussianKDE], float] | None
  3611. ) = None,
  3612. side: Literal["both", "low", "high"] = "both",
  3613. *,
  3614. data=None,
  3615. ) -> dict[str, Collection]:
  3616. return gca().violinplot(
  3617. dataset,
  3618. positions=positions,
  3619. vert=vert,
  3620. orientation=orientation,
  3621. widths=widths,
  3622. showmeans=showmeans,
  3623. showextrema=showextrema,
  3624. showmedians=showmedians,
  3625. quantiles=quantiles,
  3626. points=points,
  3627. bw_method=bw_method,
  3628. side=side,
  3629. **({"data": data} if data is not None else {}),
  3630. )
  3631. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3632. @_copy_docstring_and_deprecators(Axes.vlines)
  3633. def vlines(
  3634. x: float | ArrayLike,
  3635. ymin: float | ArrayLike,
  3636. ymax: float | ArrayLike,
  3637. colors: ColorType | Sequence[ColorType] | None = None,
  3638. linestyles: LineStyleType = "solid",
  3639. label: str = "",
  3640. *,
  3641. data=None,
  3642. **kwargs,
  3643. ) -> LineCollection:
  3644. return gca().vlines(
  3645. x,
  3646. ymin,
  3647. ymax,
  3648. colors=colors,
  3649. linestyles=linestyles,
  3650. label=label,
  3651. **({"data": data} if data is not None else {}),
  3652. **kwargs,
  3653. )
  3654. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3655. @_copy_docstring_and_deprecators(Axes.xcorr)
  3656. def xcorr(
  3657. x: ArrayLike,
  3658. y: ArrayLike,
  3659. normed: bool = True,
  3660. detrend: Callable[[ArrayLike], ArrayLike] = mlab.detrend_none,
  3661. usevlines: bool = True,
  3662. maxlags: int = 10,
  3663. *,
  3664. data=None,
  3665. **kwargs,
  3666. ) -> tuple[np.ndarray, np.ndarray, LineCollection | Line2D, Line2D | None]:
  3667. return gca().xcorr(
  3668. x,
  3669. y,
  3670. normed=normed,
  3671. detrend=detrend,
  3672. usevlines=usevlines,
  3673. maxlags=maxlags,
  3674. **({"data": data} if data is not None else {}),
  3675. **kwargs,
  3676. )
  3677. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3678. @_copy_docstring_and_deprecators(Axes._sci)
  3679. def sci(im: ColorizingArtist) -> None:
  3680. gca()._sci(im)
  3681. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3682. @_copy_docstring_and_deprecators(Axes.set_title)
  3683. def title(
  3684. label: str,
  3685. fontdict: dict[str, Any] | None = None,
  3686. loc: Literal["left", "center", "right"] | None = None,
  3687. pad: float | None = None,
  3688. *,
  3689. y: float | None = None,
  3690. **kwargs,
  3691. ) -> Text:
  3692. return gca().set_title(label, fontdict=fontdict, loc=loc, pad=pad, y=y, **kwargs)
  3693. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3694. @_copy_docstring_and_deprecators(Axes.set_xlabel)
  3695. def xlabel(
  3696. xlabel: str,
  3697. fontdict: dict[str, Any] | None = None,
  3698. labelpad: float | None = None,
  3699. *,
  3700. loc: Literal["left", "center", "right"] | None = None,
  3701. **kwargs,
  3702. ) -> Text:
  3703. return gca().set_xlabel(
  3704. xlabel, fontdict=fontdict, labelpad=labelpad, loc=loc, **kwargs
  3705. )
  3706. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3707. @_copy_docstring_and_deprecators(Axes.set_ylabel)
  3708. def ylabel(
  3709. ylabel: str,
  3710. fontdict: dict[str, Any] | None = None,
  3711. labelpad: float | None = None,
  3712. *,
  3713. loc: Literal["bottom", "center", "top"] | None = None,
  3714. **kwargs,
  3715. ) -> Text:
  3716. return gca().set_ylabel(
  3717. ylabel, fontdict=fontdict, labelpad=labelpad, loc=loc, **kwargs
  3718. )
  3719. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3720. @_copy_docstring_and_deprecators(Axes.set_xscale)
  3721. def xscale(value: str | ScaleBase, **kwargs) -> None:
  3722. gca().set_xscale(value, **kwargs)
  3723. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3724. @_copy_docstring_and_deprecators(Axes.set_yscale)
  3725. def yscale(value: str | ScaleBase, **kwargs) -> None:
  3726. gca().set_yscale(value, **kwargs)
  3727. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3728. def autumn() -> None:
  3729. """
  3730. Set the colormap to 'autumn'.
  3731. This changes the default colormap as well as the colormap of the current
  3732. image if there is one. See ``help(colormaps)`` for more information.
  3733. """
  3734. set_cmap("autumn")
  3735. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3736. def bone() -> None:
  3737. """
  3738. Set the colormap to 'bone'.
  3739. This changes the default colormap as well as the colormap of the current
  3740. image if there is one. See ``help(colormaps)`` for more information.
  3741. """
  3742. set_cmap("bone")
  3743. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3744. def cool() -> None:
  3745. """
  3746. Set the colormap to 'cool'.
  3747. This changes the default colormap as well as the colormap of the current
  3748. image if there is one. See ``help(colormaps)`` for more information.
  3749. """
  3750. set_cmap("cool")
  3751. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3752. def copper() -> None:
  3753. """
  3754. Set the colormap to 'copper'.
  3755. This changes the default colormap as well as the colormap of the current
  3756. image if there is one. See ``help(colormaps)`` for more information.
  3757. """
  3758. set_cmap("copper")
  3759. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3760. def flag() -> None:
  3761. """
  3762. Set the colormap to 'flag'.
  3763. This changes the default colormap as well as the colormap of the current
  3764. image if there is one. See ``help(colormaps)`` for more information.
  3765. """
  3766. set_cmap("flag")
  3767. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3768. def gray() -> None:
  3769. """
  3770. Set the colormap to 'gray'.
  3771. This changes the default colormap as well as the colormap of the current
  3772. image if there is one. See ``help(colormaps)`` for more information.
  3773. """
  3774. set_cmap("gray")
  3775. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3776. def hot() -> None:
  3777. """
  3778. Set the colormap to 'hot'.
  3779. This changes the default colormap as well as the colormap of the current
  3780. image if there is one. See ``help(colormaps)`` for more information.
  3781. """
  3782. set_cmap("hot")
  3783. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3784. def hsv() -> None:
  3785. """
  3786. Set the colormap to 'hsv'.
  3787. This changes the default colormap as well as the colormap of the current
  3788. image if there is one. See ``help(colormaps)`` for more information.
  3789. """
  3790. set_cmap("hsv")
  3791. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3792. def jet() -> None:
  3793. """
  3794. Set the colormap to 'jet'.
  3795. This changes the default colormap as well as the colormap of the current
  3796. image if there is one. See ``help(colormaps)`` for more information.
  3797. """
  3798. set_cmap("jet")
  3799. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3800. def pink() -> None:
  3801. """
  3802. Set the colormap to 'pink'.
  3803. This changes the default colormap as well as the colormap of the current
  3804. image if there is one. See ``help(colormaps)`` for more information.
  3805. """
  3806. set_cmap("pink")
  3807. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3808. def prism() -> None:
  3809. """
  3810. Set the colormap to 'prism'.
  3811. This changes the default colormap as well as the colormap of the current
  3812. image if there is one. See ``help(colormaps)`` for more information.
  3813. """
  3814. set_cmap("prism")
  3815. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3816. def spring() -> None:
  3817. """
  3818. Set the colormap to 'spring'.
  3819. This changes the default colormap as well as the colormap of the current
  3820. image if there is one. See ``help(colormaps)`` for more information.
  3821. """
  3822. set_cmap("spring")
  3823. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3824. def summer() -> None:
  3825. """
  3826. Set the colormap to 'summer'.
  3827. This changes the default colormap as well as the colormap of the current
  3828. image if there is one. See ``help(colormaps)`` for more information.
  3829. """
  3830. set_cmap("summer")
  3831. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3832. def winter() -> None:
  3833. """
  3834. Set the colormap to 'winter'.
  3835. This changes the default colormap as well as the colormap of the current
  3836. image if there is one. See ``help(colormaps)`` for more information.
  3837. """
  3838. set_cmap("winter")
  3839. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3840. def magma() -> None:
  3841. """
  3842. Set the colormap to 'magma'.
  3843. This changes the default colormap as well as the colormap of the current
  3844. image if there is one. See ``help(colormaps)`` for more information.
  3845. """
  3846. set_cmap("magma")
  3847. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3848. def inferno() -> None:
  3849. """
  3850. Set the colormap to 'inferno'.
  3851. This changes the default colormap as well as the colormap of the current
  3852. image if there is one. See ``help(colormaps)`` for more information.
  3853. """
  3854. set_cmap("inferno")
  3855. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3856. def plasma() -> None:
  3857. """
  3858. Set the colormap to 'plasma'.
  3859. This changes the default colormap as well as the colormap of the current
  3860. image if there is one. See ``help(colormaps)`` for more information.
  3861. """
  3862. set_cmap("plasma")
  3863. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3864. def viridis() -> None:
  3865. """
  3866. Set the colormap to 'viridis'.
  3867. This changes the default colormap as well as the colormap of the current
  3868. image if there is one. See ``help(colormaps)`` for more information.
  3869. """
  3870. set_cmap("viridis")
  3871. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  3872. def nipy_spectral() -> None:
  3873. """
  3874. Set the colormap to 'nipy_spectral'.
  3875. This changes the default colormap as well as the colormap of the current
  3876. image if there is one. See ``help(colormaps)`` for more information.
  3877. """
  3878. set_cmap("nipy_spectral")