_base.py 182 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857
  1. from collections.abc import Iterable, Sequence
  2. from contextlib import ExitStack
  3. import functools
  4. import inspect
  5. import logging
  6. from numbers import Real
  7. from operator import attrgetter
  8. import re
  9. import types
  10. import numpy as np
  11. import matplotlib as mpl
  12. from matplotlib import _api, cbook, _docstring, offsetbox
  13. import matplotlib.artist as martist
  14. import matplotlib.axis as maxis
  15. from matplotlib.cbook import _OrderedSet, _check_1d, index_of
  16. import matplotlib.collections as mcoll
  17. import matplotlib.colors as mcolors
  18. import matplotlib.font_manager as font_manager
  19. from matplotlib.gridspec import SubplotSpec
  20. import matplotlib.image as mimage
  21. import matplotlib.lines as mlines
  22. import matplotlib.patches as mpatches
  23. from matplotlib.rcsetup import cycler, validate_axisbelow
  24. import matplotlib.spines as mspines
  25. import matplotlib.table as mtable
  26. import matplotlib.text as mtext
  27. import matplotlib.ticker as mticker
  28. import matplotlib.transforms as mtransforms
  29. _log = logging.getLogger(__name__)
  30. class _axis_method_wrapper:
  31. """
  32. Helper to generate Axes methods wrapping Axis methods.
  33. After ::
  34. get_foo = _axis_method_wrapper("xaxis", "get_bar")
  35. (in the body of a class) ``get_foo`` is a method that forwards it arguments
  36. to the ``get_bar`` method of the ``xaxis`` attribute, and gets its
  37. signature and docstring from ``Axis.get_bar``.
  38. The docstring of ``get_foo`` is built by replacing "this Axis" by "the
  39. {attr_name}" (i.e., "the xaxis", "the yaxis") in the wrapped method's
  40. dedented docstring; additional replacements can be given in *doc_sub*.
  41. """
  42. def __init__(self, attr_name, method_name, *, doc_sub=None):
  43. self.attr_name = attr_name
  44. self.method_name = method_name
  45. # Immediately put the docstring in ``self.__doc__`` so that docstring
  46. # manipulations within the class body work as expected.
  47. doc = inspect.getdoc(getattr(maxis.Axis, method_name))
  48. self._missing_subs = []
  49. if doc:
  50. doc_sub = {"this Axis": f"the {self.attr_name}", **(doc_sub or {})}
  51. for k, v in doc_sub.items():
  52. if k not in doc: # Delay raising error until we know qualname.
  53. self._missing_subs.append(k)
  54. doc = doc.replace(k, v)
  55. self.__doc__ = doc
  56. def __set_name__(self, owner, name):
  57. # This is called at the end of the class body as
  58. # ``self.__set_name__(cls, name_under_which_self_is_assigned)``; we
  59. # rely on that to give the wrapper the correct __name__/__qualname__.
  60. get_method = attrgetter(f"{self.attr_name}.{self.method_name}")
  61. def wrapper(self, *args, **kwargs):
  62. return get_method(self)(*args, **kwargs)
  63. wrapper.__module__ = owner.__module__
  64. wrapper.__name__ = name
  65. wrapper.__qualname__ = f"{owner.__qualname__}.{name}"
  66. wrapper.__doc__ = self.__doc__
  67. # Manually copy the signature instead of using functools.wraps because
  68. # displaying the Axis method source when asking for the Axes method
  69. # source would be confusing.
  70. wrapper.__signature__ = inspect.signature(
  71. getattr(maxis.Axis, self.method_name))
  72. if self._missing_subs:
  73. raise ValueError(
  74. "The definition of {} expected that the docstring of Axis.{} "
  75. "contains {!r} as substrings".format(
  76. wrapper.__qualname__, self.method_name,
  77. ", ".join(map(repr, self._missing_subs))))
  78. setattr(owner, name, wrapper)
  79. class _TransformedBoundsLocator:
  80. """
  81. Axes locator for `.Axes.inset_axes` and similarly positioned Axes.
  82. The locator is a callable object used in `.Axes.set_aspect` to compute the
  83. Axes location depending on the renderer.
  84. """
  85. def __init__(self, bounds, transform):
  86. """
  87. *bounds* (a ``[l, b, w, h]`` rectangle) and *transform* together
  88. specify the position of the inset Axes.
  89. """
  90. self._bounds = bounds
  91. self._transform = transform
  92. def __call__(self, ax, renderer):
  93. # Subtracting transSubfigure will typically rely on inverted(),
  94. # freezing the transform; thus, this needs to be delayed until draw
  95. # time as transSubfigure may otherwise change after this is evaluated.
  96. return mtransforms.TransformedBbox(
  97. mtransforms.Bbox.from_bounds(*self._bounds),
  98. self._transform - ax.get_figure(root=False).transSubfigure)
  99. def _process_plot_format(fmt, *, ambiguous_fmt_datakey=False):
  100. """
  101. Convert a MATLAB style color/line style format string to a (*linestyle*,
  102. *marker*, *color*) tuple.
  103. Example format strings include:
  104. * 'ko': black circles
  105. * '.b': blue dots
  106. * 'r--': red dashed lines
  107. * 'C2--': the third color in the color cycle, dashed lines
  108. The format is absolute in the sense that if a linestyle or marker is not
  109. defined in *fmt*, there is no line or marker. This is expressed by
  110. returning 'None' for the respective quantity.
  111. See Also
  112. --------
  113. matplotlib.Line2D.lineStyles, matplotlib.colors.cnames
  114. All possible styles and color format strings.
  115. """
  116. linestyle = None
  117. marker = None
  118. color = None
  119. # First check whether fmt is just a colorspec, but specifically exclude the
  120. # grayscale string "1" (not "1.0"), which is interpreted as the tri_down
  121. # marker "1". The grayscale string "0" could be unambiguously understood
  122. # as a color (black) but also excluded for consistency.
  123. if fmt not in ["0", "1"]:
  124. try:
  125. color = mcolors.to_rgba(fmt)
  126. return linestyle, marker, color
  127. except ValueError:
  128. pass
  129. errfmt = ("{!r} is neither a data key nor a valid format string ({})"
  130. if ambiguous_fmt_datakey else
  131. "{!r} is not a valid format string ({})")
  132. i = 0
  133. while i < len(fmt):
  134. c = fmt[i]
  135. if fmt[i:i+2] in mlines.lineStyles: # First, the two-char styles.
  136. if linestyle is not None:
  137. raise ValueError(errfmt.format(fmt, "two linestyle symbols"))
  138. linestyle = fmt[i:i+2]
  139. i += 2
  140. elif c in mlines.lineStyles:
  141. if linestyle is not None:
  142. raise ValueError(errfmt.format(fmt, "two linestyle symbols"))
  143. linestyle = c
  144. i += 1
  145. elif c in mlines.lineMarkers:
  146. if marker is not None:
  147. raise ValueError(errfmt.format(fmt, "two marker symbols"))
  148. marker = c
  149. i += 1
  150. elif c in mcolors.get_named_colors_mapping():
  151. if color is not None:
  152. raise ValueError(errfmt.format(fmt, "two color symbols"))
  153. color = c
  154. i += 1
  155. elif c == "C":
  156. cn_color = re.match(r"C\d+", fmt[i:])
  157. if not cn_color:
  158. raise ValueError(errfmt.format(fmt, "'C' must be followed by a number"))
  159. color = mcolors.to_rgba(cn_color[0])
  160. i += len(cn_color[0])
  161. else:
  162. raise ValueError(errfmt.format(fmt, f"unrecognized character {c!r}"))
  163. if linestyle is None and marker is None:
  164. linestyle = mpl.rcParams['lines.linestyle']
  165. if linestyle is None:
  166. linestyle = 'None'
  167. if marker is None:
  168. marker = 'None'
  169. return linestyle, marker, color
  170. class _process_plot_var_args:
  171. """
  172. Process variable length arguments to `~.Axes.plot`, to support ::
  173. plot(t, s)
  174. plot(t1, s1, t2, s2)
  175. plot(t1, s1, 'ko', t2, s2)
  176. plot(t1, s1, 'ko', t2, s2, 'r--', t3, e3)
  177. an arbitrary number of *x*, *y*, *fmt* are allowed
  178. """
  179. def __init__(self, output='Line2D'):
  180. _api.check_in_list(['Line2D', 'Polygon', 'coordinates'], output=output)
  181. self.output = output
  182. self.set_prop_cycle(None)
  183. def set_prop_cycle(self, cycler):
  184. if cycler is None:
  185. cycler = mpl.rcParams['axes.prop_cycle']
  186. self._idx = 0
  187. self._cycler_items = [*cycler]
  188. def __call__(self, axes, *args, data=None, return_kwargs=False, **kwargs):
  189. axes._process_unit_info(kwargs=kwargs)
  190. for pos_only in "xy":
  191. if pos_only in kwargs:
  192. raise _api.kwarg_error(inspect.stack()[1].function, pos_only)
  193. if not args:
  194. return
  195. if data is None: # Process dict views
  196. args = [cbook.sanitize_sequence(a) for a in args]
  197. else: # Process the 'data' kwarg.
  198. replaced = [mpl._replacer(data, arg) for arg in args]
  199. if len(args) == 1:
  200. label_namer_idx = 0
  201. elif len(args) == 2: # Can be x, y or y, c.
  202. # Figure out what the second argument is.
  203. # 1) If the second argument cannot be a format shorthand, the
  204. # second argument is the label_namer.
  205. # 2) Otherwise (it could have been a format shorthand),
  206. # a) if we did perform a substitution, emit a warning, and
  207. # use it as label_namer.
  208. # b) otherwise, it is indeed a format shorthand; use the
  209. # first argument as label_namer.
  210. try:
  211. _process_plot_format(args[1])
  212. except ValueError: # case 1)
  213. label_namer_idx = 1
  214. else:
  215. if replaced[1] is not args[1]: # case 2a)
  216. _api.warn_external(
  217. f"Second argument {args[1]!r} is ambiguous: could "
  218. f"be a format string but is in 'data'; using as "
  219. f"data. If it was intended as data, set the "
  220. f"format string to an empty string to suppress "
  221. f"this warning. If it was intended as a format "
  222. f"string, explicitly pass the x-values as well. "
  223. f"Alternatively, rename the entry in 'data'.",
  224. RuntimeWarning)
  225. label_namer_idx = 1
  226. else: # case 2b)
  227. label_namer_idx = 0
  228. elif len(args) == 3:
  229. label_namer_idx = 1
  230. else:
  231. raise ValueError(
  232. "Using arbitrary long args with data is not supported due "
  233. "to ambiguity of arguments; use multiple plotting calls "
  234. "instead")
  235. if kwargs.get("label") is None:
  236. kwargs["label"] = mpl._label_from_arg(
  237. replaced[label_namer_idx], args[label_namer_idx])
  238. args = replaced
  239. ambiguous_fmt_datakey = data is not None and len(args) == 2
  240. if len(args) >= 4 and not cbook.is_scalar_or_string(
  241. kwargs.get("label")):
  242. raise ValueError("plot() with multiple groups of data (i.e., "
  243. "pairs of x and y) does not support multiple "
  244. "labels")
  245. # Repeatedly grab (x, y) or (x, y, format) from the front of args and
  246. # massage them into arguments to plot() or fill().
  247. while args:
  248. this, args = args[:2], args[2:]
  249. if args and isinstance(args[0], str):
  250. this += args[0],
  251. args = args[1:]
  252. yield from self._plot_args(
  253. axes, this, kwargs, ambiguous_fmt_datakey=ambiguous_fmt_datakey,
  254. return_kwargs=return_kwargs
  255. )
  256. def get_next_color(self):
  257. """Return the next color in the cycle."""
  258. entry = self._cycler_items[self._idx]
  259. if "color" in entry:
  260. self._idx = (self._idx + 1) % len(self._cycler_items) # Advance cycler.
  261. return entry["color"]
  262. else:
  263. return "k"
  264. def _getdefaults(self, kw, ignore=frozenset()):
  265. """
  266. If some keys in the property cycle (excluding those in the set
  267. *ignore*) are absent or set to None in the dict *kw*, return a copy
  268. of the next entry in the property cycle, excluding keys in *ignore*.
  269. Otherwise, don't advance the property cycle, and return an empty dict.
  270. """
  271. defaults = self._cycler_items[self._idx]
  272. if any(kw.get(k, None) is None for k in {*defaults} - ignore):
  273. self._idx = (self._idx + 1) % len(self._cycler_items) # Advance cycler.
  274. # Return a new dict to avoid exposing _cycler_items entries to mutation.
  275. return {k: v for k, v in defaults.items() if k not in ignore}
  276. else:
  277. return {}
  278. def _setdefaults(self, defaults, kw):
  279. """
  280. Add to the dict *kw* the entries in the dict *default* that are absent
  281. or set to None in *kw*.
  282. """
  283. for k in defaults:
  284. if kw.get(k, None) is None:
  285. kw[k] = defaults[k]
  286. def _make_line(self, axes, x, y, kw, kwargs):
  287. kw = {**kw, **kwargs} # Don't modify the original kw.
  288. self._setdefaults(self._getdefaults(kw), kw)
  289. seg = mlines.Line2D(x, y, **kw)
  290. return seg, kw
  291. def _make_coordinates(self, axes, x, y, kw, kwargs):
  292. kw = {**kw, **kwargs} # Don't modify the original kw.
  293. self._setdefaults(self._getdefaults(kw), kw)
  294. return (x, y), kw
  295. def _make_polygon(self, axes, x, y, kw, kwargs):
  296. # Polygon doesn't directly support unitized inputs.
  297. x = axes.convert_xunits(x)
  298. y = axes.convert_yunits(y)
  299. kw = kw.copy() # Don't modify the original kw.
  300. kwargs = kwargs.copy()
  301. # Ignore 'marker'-related properties as they aren't Polygon
  302. # properties, but they are Line2D properties, and so they are
  303. # likely to appear in the default cycler construction.
  304. # This is done here to the defaults dictionary as opposed to the
  305. # other two dictionaries because we do want to capture when a
  306. # *user* explicitly specifies a marker which should be an error.
  307. # We also want to prevent advancing the cycler if there are no
  308. # defaults needed after ignoring the given properties.
  309. ignores = ({'marker', 'markersize', 'markeredgecolor',
  310. 'markerfacecolor', 'markeredgewidth'}
  311. # Also ignore anything provided by *kwargs*.
  312. | {k for k, v in kwargs.items() if v is not None})
  313. # Only using the first dictionary to use as basis
  314. # for getting defaults for back-compat reasons.
  315. # Doing it with both seems to mess things up in
  316. # various places (probably due to logic bugs elsewhere).
  317. default_dict = self._getdefaults(kw, ignores)
  318. self._setdefaults(default_dict, kw)
  319. # Looks like we don't want "color" to be interpreted to
  320. # mean both facecolor and edgecolor for some reason.
  321. # So the "kw" dictionary is thrown out, and only its
  322. # 'color' value is kept and translated as a 'facecolor'.
  323. # This design should probably be revisited as it increases
  324. # complexity.
  325. facecolor = kw.get('color', None)
  326. # Throw out 'color' as it is now handled as a facecolor
  327. default_dict.pop('color', None)
  328. # To get other properties set from the cycler
  329. # modify the kwargs dictionary.
  330. self._setdefaults(default_dict, kwargs)
  331. seg = mpatches.Polygon(np.column_stack((x, y)),
  332. facecolor=facecolor,
  333. fill=kwargs.get('fill', True),
  334. closed=kw['closed'])
  335. seg.set(**kwargs)
  336. return seg, kwargs
  337. def _plot_args(self, axes, tup, kwargs, *,
  338. return_kwargs=False, ambiguous_fmt_datakey=False):
  339. """
  340. Process the arguments of ``plot([x], y, [fmt], **kwargs)`` calls.
  341. This processes a single set of ([x], y, [fmt]) parameters; i.e. for
  342. ``plot(x, y, x2, y2)`` it will be called twice. Once for (x, y) and
  343. once for (x2, y2).
  344. x and y may be 2D and thus can still represent multiple datasets.
  345. For multiple datasets, if the keyword argument *label* is a list, this
  346. will unpack the list and assign the individual labels to the datasets.
  347. Parameters
  348. ----------
  349. tup : tuple
  350. A tuple of the positional parameters. This can be one of
  351. - (y,)
  352. - (x, y)
  353. - (y, fmt)
  354. - (x, y, fmt)
  355. kwargs : dict
  356. The keyword arguments passed to ``plot()``.
  357. return_kwargs : bool
  358. Whether to also return the effective keyword arguments after label
  359. unpacking as well.
  360. ambiguous_fmt_datakey : bool
  361. Whether the format string in *tup* could also have been a
  362. misspelled data key.
  363. Returns
  364. -------
  365. result
  366. If *return_kwargs* is false, a list of Artists representing the
  367. dataset(s).
  368. If *return_kwargs* is true, a list of (Artist, effective_kwargs)
  369. representing the dataset(s). See *return_kwargs*.
  370. The Artist is either `.Line2D` (if called from ``plot()``) or
  371. `.Polygon` otherwise.
  372. """
  373. if len(tup) > 1 and isinstance(tup[-1], str):
  374. # xy is tup with fmt stripped (could still be (y,) only)
  375. *xy, fmt = tup
  376. linestyle, marker, color = _process_plot_format(
  377. fmt, ambiguous_fmt_datakey=ambiguous_fmt_datakey)
  378. elif len(tup) == 3:
  379. raise ValueError('third arg must be a format string')
  380. else:
  381. xy = tup
  382. linestyle, marker, color = None, None, None
  383. # Don't allow any None value; these would be up-converted to one
  384. # element array of None which causes problems downstream.
  385. if any(v is None for v in tup):
  386. raise ValueError("x, y, and format string must not be None")
  387. kw = {}
  388. for prop_name, val in zip(('linestyle', 'marker', 'color'),
  389. (linestyle, marker, color)):
  390. if val is not None:
  391. # check for conflicts between fmt and kwargs
  392. if (fmt.lower() != 'none'
  393. and prop_name in kwargs
  394. and val != 'None'):
  395. # Technically ``plot(x, y, 'o', ls='--')`` is a conflict
  396. # because 'o' implicitly unsets the linestyle
  397. # (linestyle='None').
  398. # We'll gracefully not warn in this case because an
  399. # explicit set via kwargs can be seen as intention to
  400. # override an implicit unset.
  401. # Note: We don't val.lower() != 'none' because val is not
  402. # necessarily a string (can be a tuple for colors). This
  403. # is safe, because *val* comes from _process_plot_format()
  404. # which only returns 'None'.
  405. _api.warn_external(
  406. f"{prop_name} is redundantly defined by the "
  407. f"'{prop_name}' keyword argument and the fmt string "
  408. f'"{fmt}" (-> {prop_name}={val!r}). The keyword '
  409. f"argument will take precedence.")
  410. kw[prop_name] = val
  411. if len(xy) == 2:
  412. x = _check_1d(xy[0])
  413. y = _check_1d(xy[1])
  414. else:
  415. x, y = index_of(xy[-1])
  416. if axes.xaxis is not None:
  417. axes.xaxis.update_units(x)
  418. if axes.yaxis is not None:
  419. axes.yaxis.update_units(y)
  420. if x.shape[0] != y.shape[0]:
  421. raise ValueError(f"x and y must have same first dimension, but "
  422. f"have shapes {x.shape} and {y.shape}")
  423. if x.ndim > 2 or y.ndim > 2:
  424. raise ValueError(f"x and y can be no greater than 2D, but have "
  425. f"shapes {x.shape} and {y.shape}")
  426. if x.ndim == 1:
  427. x = x[:, np.newaxis]
  428. if y.ndim == 1:
  429. y = y[:, np.newaxis]
  430. if self.output == 'Line2D':
  431. make_artist = self._make_line
  432. elif self.output == 'Polygon':
  433. kw['closed'] = kwargs.get('closed', True)
  434. make_artist = self._make_polygon
  435. elif self.output == 'coordinates':
  436. make_artist = self._make_coordinates
  437. else:
  438. _api.check_in_list(['Line2D', 'Polygon', 'coordinates'], output=self.output)
  439. ncx, ncy = x.shape[1], y.shape[1]
  440. if ncx > 1 and ncy > 1 and ncx != ncy:
  441. raise ValueError(f"x has {ncx} columns but y has {ncy} columns")
  442. if ncx == 0 or ncy == 0:
  443. return []
  444. label = kwargs.get('label')
  445. n_datasets = max(ncx, ncy)
  446. if cbook.is_scalar_or_string(label):
  447. labels = [label] * n_datasets
  448. elif len(label) == n_datasets:
  449. labels = label
  450. elif n_datasets == 1:
  451. msg = (f'Passing label as a length {len(label)} sequence when '
  452. 'plotting a single dataset is deprecated in Matplotlib 3.9 '
  453. 'and will error in 3.11. To keep the current behavior, '
  454. 'cast the sequence to string before passing.')
  455. _api.warn_deprecated('3.9', message=msg)
  456. labels = [label]
  457. else:
  458. raise ValueError(
  459. f"label must be scalar or have the same length as the input "
  460. f"data, but found {len(label)} for {n_datasets} datasets.")
  461. result = (make_artist(axes, x[:, j % ncx], y[:, j % ncy], kw,
  462. {**kwargs, 'label': label})
  463. for j, label in enumerate(labels))
  464. if return_kwargs:
  465. return list(result)
  466. else:
  467. return [l[0] for l in result]
  468. @_api.define_aliases({"facecolor": ["fc"]})
  469. class _AxesBase(martist.Artist):
  470. name = "rectilinear"
  471. # axis names are the prefixes for the attributes that contain the
  472. # respective axis; e.g. 'x' <-> self.xaxis, containing an XAxis.
  473. # Note that PolarAxes uses these attributes as well, so that we have
  474. # 'x' <-> self.xaxis, containing a ThetaAxis. In particular we do not
  475. # have 'theta' in _axis_names.
  476. # In practice, this is ('x', 'y') for all 2D Axes and ('x', 'y', 'z')
  477. # for Axes3D.
  478. _axis_names = ("x", "y")
  479. _shared_axes = {name: cbook.Grouper() for name in _axis_names}
  480. _twinned_axes = cbook.Grouper()
  481. _subclass_uses_cla = False
  482. dataLim: mtransforms.Bbox
  483. """The bounding `.Bbox` enclosing all data displayed in the Axes."""
  484. spines: mspines.Spines
  485. """
  486. The `.Spines` container for the Axes' spines, i.e. the lines denoting the
  487. data area boundaries.
  488. """
  489. xaxis: maxis.XAxis
  490. """
  491. The `.XAxis` instance.
  492. Common axis-related configuration can be achieved through high-level wrapper
  493. methods on Axes; e.g. `ax.set_xticks <.Axes.set_xticks>` is a shortcut for
  494. `ax.xaxis.set_ticks <.Axis.set_ticks>`. The *xaxis* attribute gives direct
  495. direct access to the underlying `~.axis.Axis` if you need more control.
  496. See also
  497. - :ref:`Axis wrapper methods on Axes <axes-api-axis>`
  498. - :doc:`Axis API </api/axis_api>`
  499. """
  500. yaxis: maxis.YAxis
  501. """
  502. The `.YAxis` instance.
  503. Common axis-related configuration can be achieved through high-level wrapper
  504. methods on Axes; e.g. `ax.set_yticks <.Axes.set_yticks>` is a shortcut for
  505. `ax.yaxis.set_ticks <.Axis.set_ticks>`. The *yaxis* attribute gives direct
  506. access to the underlying `~.axis.Axis` if you need more control.
  507. See also
  508. - :ref:`Axis wrapper methods on Axes <axes-api-axis>`
  509. - :doc:`Axis API </api/axis_api>`
  510. """
  511. @property
  512. def _axis_map(self):
  513. """A mapping of axis names, e.g. 'x', to `Axis` instances."""
  514. return {name: getattr(self, f"{name}axis")
  515. for name in self._axis_names}
  516. def __str__(self):
  517. return "{0}({1[0]:g},{1[1]:g};{1[2]:g}x{1[3]:g})".format(
  518. type(self).__name__, self._position.bounds)
  519. def __init__(self, fig,
  520. *args,
  521. facecolor=None, # defaults to rc axes.facecolor
  522. frameon=True,
  523. sharex=None, # use Axes instance's xaxis info
  524. sharey=None, # use Axes instance's yaxis info
  525. label='',
  526. xscale=None,
  527. yscale=None,
  528. box_aspect=None,
  529. forward_navigation_events="auto",
  530. **kwargs
  531. ):
  532. """
  533. Build an Axes in a figure.
  534. Parameters
  535. ----------
  536. fig : `~matplotlib.figure.Figure`
  537. The Axes is built in the `.Figure` *fig*.
  538. *args
  539. ``*args`` can be a single ``(left, bottom, width, height)``
  540. rectangle or a single `.Bbox`. This specifies the rectangle (in
  541. figure coordinates) where the Axes is positioned.
  542. ``*args`` can also consist of three numbers or a single three-digit
  543. number; in the latter case, the digits are considered as
  544. independent numbers. The numbers are interpreted as ``(nrows,
  545. ncols, index)``: ``(nrows, ncols)`` specifies the size of an array
  546. of subplots, and ``index`` is the 1-based index of the subplot
  547. being created. Finally, ``*args`` can also directly be a
  548. `.SubplotSpec` instance.
  549. sharex, sharey : `~matplotlib.axes.Axes`, optional
  550. The x- or y-`~.matplotlib.axis` is shared with the x- or y-axis in
  551. the input `~.axes.Axes`. Note that it is not possible to unshare
  552. axes.
  553. frameon : bool, default: True
  554. Whether the Axes frame is visible.
  555. box_aspect : float, optional
  556. Set a fixed aspect for the Axes box, i.e. the ratio of height to
  557. width. See `~.axes.Axes.set_box_aspect` for details.
  558. forward_navigation_events : bool or "auto", default: "auto"
  559. Control whether pan/zoom events are passed through to Axes below
  560. this one. "auto" is *True* for axes with an invisible patch and
  561. *False* otherwise.
  562. **kwargs
  563. Other optional keyword arguments:
  564. %(Axes:kwdoc)s
  565. Returns
  566. -------
  567. `~.axes.Axes`
  568. The new `~.axes.Axes` object.
  569. """
  570. super().__init__()
  571. if "rect" in kwargs:
  572. if args:
  573. raise TypeError(
  574. "'rect' cannot be used together with positional arguments")
  575. rect = kwargs.pop("rect")
  576. _api.check_isinstance((mtransforms.Bbox, Iterable), rect=rect)
  577. args = (rect,)
  578. subplotspec = None
  579. if len(args) == 1 and isinstance(args[0], mtransforms.Bbox):
  580. self._position = args[0].frozen()
  581. elif len(args) == 1 and np.iterable(args[0]):
  582. self._position = mtransforms.Bbox.from_bounds(*args[0])
  583. else:
  584. self._position = self._originalPosition = mtransforms.Bbox.unit()
  585. subplotspec = SubplotSpec._from_subplot_args(fig, args)
  586. if self._position.width < 0 or self._position.height < 0:
  587. raise ValueError('Width and height specified must be non-negative')
  588. self._originalPosition = self._position.frozen()
  589. self.axes = self
  590. self._aspect = 'auto'
  591. self._adjustable = 'box'
  592. self._anchor = 'C'
  593. self._stale_viewlims = dict.fromkeys(self._axis_names, False)
  594. self._forward_navigation_events = forward_navigation_events
  595. self._sharex = sharex
  596. self._sharey = sharey
  597. self.set_label(label)
  598. self.set_figure(fig)
  599. # The subplotspec needs to be set after the figure (so that
  600. # figure-level subplotpars are taken into account), but the figure
  601. # needs to be set after self._position is initialized.
  602. if subplotspec:
  603. self.set_subplotspec(subplotspec)
  604. else:
  605. self._subplotspec = None
  606. self.set_box_aspect(box_aspect)
  607. self._axes_locator = None # Optionally set via update(kwargs).
  608. self._children = []
  609. # placeholder for any colorbars added that use this Axes.
  610. # (see colorbar.py):
  611. self._colorbars = []
  612. self.spines = mspines.Spines.from_dict(self._gen_axes_spines())
  613. # this call may differ for non-sep axes, e.g., polar
  614. self._init_axis()
  615. if facecolor is None:
  616. facecolor = mpl.rcParams['axes.facecolor']
  617. self._facecolor = facecolor
  618. self._frameon = frameon
  619. self.set_axisbelow(mpl.rcParams['axes.axisbelow'])
  620. self._rasterization_zorder = None
  621. self.clear()
  622. # funcs used to format x and y - fall back on major formatters
  623. self.fmt_xdata = None
  624. self.fmt_ydata = None
  625. self.set_navigate(True)
  626. self.set_navigate_mode(None)
  627. if xscale:
  628. self.set_xscale(xscale)
  629. if yscale:
  630. self.set_yscale(yscale)
  631. self._internal_update(kwargs)
  632. for name, axis in self._axis_map.items():
  633. axis.callbacks._connect_picklable(
  634. 'units', self._unit_change_handler(name))
  635. rcParams = mpl.rcParams
  636. self.tick_params(
  637. top=rcParams['xtick.top'] and rcParams['xtick.minor.top'],
  638. bottom=rcParams['xtick.bottom'] and rcParams['xtick.minor.bottom'],
  639. labeltop=(rcParams['xtick.labeltop'] and
  640. rcParams['xtick.minor.top']),
  641. labelbottom=(rcParams['xtick.labelbottom'] and
  642. rcParams['xtick.minor.bottom']),
  643. left=rcParams['ytick.left'] and rcParams['ytick.minor.left'],
  644. right=rcParams['ytick.right'] and rcParams['ytick.minor.right'],
  645. labelleft=(rcParams['ytick.labelleft'] and
  646. rcParams['ytick.minor.left']),
  647. labelright=(rcParams['ytick.labelright'] and
  648. rcParams['ytick.minor.right']),
  649. which='minor')
  650. self.tick_params(
  651. top=rcParams['xtick.top'] and rcParams['xtick.major.top'],
  652. bottom=rcParams['xtick.bottom'] and rcParams['xtick.major.bottom'],
  653. labeltop=(rcParams['xtick.labeltop'] and
  654. rcParams['xtick.major.top']),
  655. labelbottom=(rcParams['xtick.labelbottom'] and
  656. rcParams['xtick.major.bottom']),
  657. left=rcParams['ytick.left'] and rcParams['ytick.major.left'],
  658. right=rcParams['ytick.right'] and rcParams['ytick.major.right'],
  659. labelleft=(rcParams['ytick.labelleft'] and
  660. rcParams['ytick.major.left']),
  661. labelright=(rcParams['ytick.labelright'] and
  662. rcParams['ytick.major.right']),
  663. which='major')
  664. def __init_subclass__(cls, **kwargs):
  665. parent_uses_cla = super(cls, cls)._subclass_uses_cla
  666. if 'cla' in cls.__dict__:
  667. _api.warn_deprecated(
  668. '3.6',
  669. pending=True,
  670. message=f'Overriding `Axes.cla` in {cls.__qualname__} is '
  671. 'pending deprecation in %(since)s and will be fully '
  672. 'deprecated in favor of `Axes.clear` in the future. '
  673. 'Please report '
  674. f'this to the {cls.__module__!r} author.')
  675. cls._subclass_uses_cla = 'cla' in cls.__dict__ or parent_uses_cla
  676. super().__init_subclass__(**kwargs)
  677. def __getstate__(self):
  678. state = super().__getstate__()
  679. # Prune the sharing & twinning info to only contain the current group.
  680. state["_shared_axes"] = {
  681. name: self._shared_axes[name].get_siblings(self)
  682. for name in self._axis_names if self in self._shared_axes[name]}
  683. state["_twinned_axes"] = (self._twinned_axes.get_siblings(self)
  684. if self in self._twinned_axes else None)
  685. return state
  686. def __setstate__(self, state):
  687. # Merge the grouping info back into the global groupers.
  688. shared_axes = state.pop("_shared_axes")
  689. for name, shared_siblings in shared_axes.items():
  690. self._shared_axes[name].join(*shared_siblings)
  691. twinned_siblings = state.pop("_twinned_axes")
  692. if twinned_siblings:
  693. self._twinned_axes.join(*twinned_siblings)
  694. self.__dict__ = state
  695. self._stale = True
  696. def __repr__(self):
  697. fields = []
  698. if self.get_label():
  699. fields += [f"label={self.get_label()!r}"]
  700. if hasattr(self, "get_title"):
  701. titles = {}
  702. for k in ["left", "center", "right"]:
  703. title = self.get_title(loc=k)
  704. if title:
  705. titles[k] = title
  706. if titles:
  707. fields += [f"title={titles}"]
  708. for name, axis in self._axis_map.items():
  709. if axis.label and axis.label.get_text():
  710. fields += [f"{name}label={axis.label.get_text()!r}"]
  711. return f"<{self.__class__.__name__}: " + ", ".join(fields) + ">"
  712. def get_subplotspec(self):
  713. """Return the `.SubplotSpec` associated with the subplot, or None."""
  714. return self._subplotspec
  715. def set_subplotspec(self, subplotspec):
  716. """Set the `.SubplotSpec`. associated with the subplot."""
  717. self._subplotspec = subplotspec
  718. self._set_position(subplotspec.get_position(self.get_figure(root=False)))
  719. def get_gridspec(self):
  720. """Return the `.GridSpec` associated with the subplot, or None."""
  721. return self._subplotspec.get_gridspec() if self._subplotspec else None
  722. def get_window_extent(self, renderer=None):
  723. """
  724. Return the Axes bounding box in display space.
  725. This bounding box does not include the spines, ticks, ticklabels,
  726. or other labels. For a bounding box including these elements use
  727. `~matplotlib.axes.Axes.get_tightbbox`.
  728. See Also
  729. --------
  730. matplotlib.axes.Axes.get_tightbbox
  731. matplotlib.axis.Axis.get_tightbbox
  732. matplotlib.spines.Spine.get_window_extent
  733. """
  734. return self.bbox
  735. def _init_axis(self):
  736. # This is moved out of __init__ because non-separable axes don't use it
  737. self.xaxis = maxis.XAxis(self, clear=False)
  738. self.spines.bottom.register_axis(self.xaxis)
  739. self.spines.top.register_axis(self.xaxis)
  740. self.yaxis = maxis.YAxis(self, clear=False)
  741. self.spines.left.register_axis(self.yaxis)
  742. self.spines.right.register_axis(self.yaxis)
  743. def set_figure(self, fig):
  744. # docstring inherited
  745. super().set_figure(fig)
  746. self.bbox = mtransforms.TransformedBbox(self._position,
  747. fig.transSubfigure)
  748. # these will be updated later as data is added
  749. self.dataLim = mtransforms.Bbox.null()
  750. self._viewLim = mtransforms.Bbox.unit()
  751. self.transScale = mtransforms.TransformWrapper(
  752. mtransforms.IdentityTransform())
  753. self._set_lim_and_transforms()
  754. def _unstale_viewLim(self):
  755. # We should arrange to store this information once per share-group
  756. # instead of on every axis.
  757. need_scale = {
  758. name: any(ax._stale_viewlims[name]
  759. for ax in self._shared_axes[name].get_siblings(self))
  760. for name in self._axis_names}
  761. if any(need_scale.values()):
  762. for name in need_scale:
  763. for ax in self._shared_axes[name].get_siblings(self):
  764. ax._stale_viewlims[name] = False
  765. self.autoscale_view(**{f"scale{name}": scale
  766. for name, scale in need_scale.items()})
  767. @property
  768. def viewLim(self):
  769. """The view limits as `.Bbox` in data coordinates."""
  770. self._unstale_viewLim()
  771. return self._viewLim
  772. def _request_autoscale_view(self, axis="all", tight=None):
  773. """
  774. Mark a single axis, or all of them, as stale wrt. autoscaling.
  775. No computation is performed until the next autoscaling; thus, separate
  776. calls to control individual axises incur negligible performance cost.
  777. Parameters
  778. ----------
  779. axis : str, default: "all"
  780. Either an element of ``self._axis_names``, or "all".
  781. tight : bool or None, default: None
  782. """
  783. axis_names = _api.check_getitem(
  784. {**{k: [k] for k in self._axis_names}, "all": self._axis_names},
  785. axis=axis)
  786. for name in axis_names:
  787. self._stale_viewlims[name] = True
  788. if tight is not None:
  789. self._tight = tight
  790. def _set_lim_and_transforms(self):
  791. """
  792. Set the *_xaxis_transform*, *_yaxis_transform*, *transScale*,
  793. *transData*, *transLimits* and *transAxes* transformations.
  794. .. note::
  795. This method is primarily used by rectilinear projections of the
  796. `~matplotlib.axes.Axes` class, and is meant to be overridden by
  797. new kinds of projection Axes that need different transformations
  798. and limits. (See `~matplotlib.projections.polar.PolarAxes` for an
  799. example.)
  800. """
  801. self.transAxes = mtransforms.BboxTransformTo(self.bbox)
  802. # Transforms the x and y axis separately by a scale factor.
  803. # It is assumed that this part will have non-linear components
  804. # (e.g., for a log scale).
  805. self.transScale = mtransforms.TransformWrapper(
  806. mtransforms.IdentityTransform())
  807. # An affine transformation on the data, generally to limit the
  808. # range of the axes
  809. self.transLimits = mtransforms.BboxTransformFrom(
  810. mtransforms.TransformedBbox(self._viewLim, self.transScale))
  811. # The parentheses are important for efficiency here -- they
  812. # group the last two (which are usually affines) separately
  813. # from the first (which, with log-scaling can be non-affine).
  814. self.transData = self.transScale + (self.transLimits + self.transAxes)
  815. self._xaxis_transform = mtransforms.blended_transform_factory(
  816. self.transData, self.transAxes)
  817. self._yaxis_transform = mtransforms.blended_transform_factory(
  818. self.transAxes, self.transData)
  819. def get_xaxis_transform(self, which='grid'):
  820. """
  821. Get the transformation used for drawing x-axis labels, ticks
  822. and gridlines. The x-direction is in data coordinates and the
  823. y-direction is in axis coordinates.
  824. .. note::
  825. This transformation is primarily used by the
  826. `~matplotlib.axis.Axis` class, and is meant to be
  827. overridden by new kinds of projections that may need to
  828. place axis elements in different locations.
  829. Parameters
  830. ----------
  831. which : {'grid', 'tick1', 'tick2'}
  832. """
  833. if which == 'grid':
  834. return self._xaxis_transform
  835. elif which == 'tick1':
  836. # for cartesian projection, this is bottom spine
  837. return self.spines.bottom.get_spine_transform()
  838. elif which == 'tick2':
  839. # for cartesian projection, this is top spine
  840. return self.spines.top.get_spine_transform()
  841. else:
  842. raise ValueError(f'unknown value for which: {which!r}')
  843. def get_xaxis_text1_transform(self, pad_points):
  844. """
  845. Returns
  846. -------
  847. transform : Transform
  848. The transform used for drawing x-axis labels, which will add
  849. *pad_points* of padding (in points) between the axis and the label.
  850. The x-direction is in data coordinates and the y-direction is in
  851. axis coordinates
  852. valign : {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
  853. The text vertical alignment.
  854. halign : {'center', 'left', 'right'}
  855. The text horizontal alignment.
  856. Notes
  857. -----
  858. This transformation is primarily used by the `~matplotlib.axis.Axis`
  859. class, and is meant to be overridden by new kinds of projections that
  860. may need to place axis elements in different locations.
  861. """
  862. labels_align = mpl.rcParams["xtick.alignment"]
  863. return (self.get_xaxis_transform(which='tick1') +
  864. mtransforms.ScaledTranslation(
  865. 0, -1 * pad_points / 72,
  866. self.get_figure(root=False).dpi_scale_trans),
  867. "top", labels_align)
  868. def get_xaxis_text2_transform(self, pad_points):
  869. """
  870. Returns
  871. -------
  872. transform : Transform
  873. The transform used for drawing secondary x-axis labels, which will
  874. add *pad_points* of padding (in points) between the axis and the
  875. label. The x-direction is in data coordinates and the y-direction
  876. is in axis coordinates
  877. valign : {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
  878. The text vertical alignment.
  879. halign : {'center', 'left', 'right'}
  880. The text horizontal alignment.
  881. Notes
  882. -----
  883. This transformation is primarily used by the `~matplotlib.axis.Axis`
  884. class, and is meant to be overridden by new kinds of projections that
  885. may need to place axis elements in different locations.
  886. """
  887. labels_align = mpl.rcParams["xtick.alignment"]
  888. return (self.get_xaxis_transform(which='tick2') +
  889. mtransforms.ScaledTranslation(
  890. 0, pad_points / 72,
  891. self.get_figure(root=False).dpi_scale_trans),
  892. "bottom", labels_align)
  893. def get_yaxis_transform(self, which='grid'):
  894. """
  895. Get the transformation used for drawing y-axis labels, ticks
  896. and gridlines. The x-direction is in axis coordinates and the
  897. y-direction is in data coordinates.
  898. .. note::
  899. This transformation is primarily used by the
  900. `~matplotlib.axis.Axis` class, and is meant to be
  901. overridden by new kinds of projections that may need to
  902. place axis elements in different locations.
  903. Parameters
  904. ----------
  905. which : {'grid', 'tick1', 'tick2'}
  906. """
  907. if which == 'grid':
  908. return self._yaxis_transform
  909. elif which == 'tick1':
  910. # for cartesian projection, this is bottom spine
  911. return self.spines.left.get_spine_transform()
  912. elif which == 'tick2':
  913. # for cartesian projection, this is top spine
  914. return self.spines.right.get_spine_transform()
  915. else:
  916. raise ValueError(f'unknown value for which: {which!r}')
  917. def get_yaxis_text1_transform(self, pad_points):
  918. """
  919. Returns
  920. -------
  921. transform : Transform
  922. The transform used for drawing y-axis labels, which will add
  923. *pad_points* of padding (in points) between the axis and the label.
  924. The x-direction is in axis coordinates and the y-direction is in
  925. data coordinates
  926. valign : {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
  927. The text vertical alignment.
  928. halign : {'center', 'left', 'right'}
  929. The text horizontal alignment.
  930. Notes
  931. -----
  932. This transformation is primarily used by the `~matplotlib.axis.Axis`
  933. class, and is meant to be overridden by new kinds of projections that
  934. may need to place axis elements in different locations.
  935. """
  936. labels_align = mpl.rcParams["ytick.alignment"]
  937. return (self.get_yaxis_transform(which='tick1') +
  938. mtransforms.ScaledTranslation(
  939. -1 * pad_points / 72, 0,
  940. self.get_figure(root=False).dpi_scale_trans),
  941. labels_align, "right")
  942. def get_yaxis_text2_transform(self, pad_points):
  943. """
  944. Returns
  945. -------
  946. transform : Transform
  947. The transform used for drawing secondart y-axis labels, which will
  948. add *pad_points* of padding (in points) between the axis and the
  949. label. The x-direction is in axis coordinates and the y-direction
  950. is in data coordinates
  951. valign : {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
  952. The text vertical alignment.
  953. halign : {'center', 'left', 'right'}
  954. The text horizontal alignment.
  955. Notes
  956. -----
  957. This transformation is primarily used by the `~matplotlib.axis.Axis`
  958. class, and is meant to be overridden by new kinds of projections that
  959. may need to place axis elements in different locations.
  960. """
  961. labels_align = mpl.rcParams["ytick.alignment"]
  962. return (self.get_yaxis_transform(which='tick2') +
  963. mtransforms.ScaledTranslation(
  964. pad_points / 72, 0,
  965. self.get_figure(root=False).dpi_scale_trans),
  966. labels_align, "left")
  967. def _update_transScale(self):
  968. self.transScale.set(
  969. mtransforms.blended_transform_factory(
  970. self.xaxis.get_transform(), self.yaxis.get_transform()))
  971. def get_position(self, original=False):
  972. """
  973. Return the position of the Axes within the figure as a `.Bbox`.
  974. Parameters
  975. ----------
  976. original : bool
  977. If ``True``, return the original position. Otherwise, return the
  978. active position. For an explanation of the positions see
  979. `.set_position`.
  980. Returns
  981. -------
  982. `.Bbox`
  983. """
  984. if original:
  985. return self._originalPosition.frozen()
  986. else:
  987. locator = self.get_axes_locator()
  988. if not locator:
  989. self.apply_aspect()
  990. return self._position.frozen()
  991. def set_position(self, pos, which='both'):
  992. """
  993. Set the Axes position.
  994. Axes have two position attributes. The 'original' position is the
  995. position allocated for the Axes. The 'active' position is the
  996. position the Axes is actually drawn at. These positions are usually
  997. the same unless a fixed aspect is set to the Axes. See
  998. `.Axes.set_aspect` for details.
  999. Parameters
  1000. ----------
  1001. pos : [left, bottom, width, height] or `~matplotlib.transforms.Bbox`
  1002. The new position of the Axes in `.Figure` coordinates.
  1003. which : {'both', 'active', 'original'}, default: 'both'
  1004. Determines which position variables to change.
  1005. See Also
  1006. --------
  1007. matplotlib.transforms.Bbox.from_bounds
  1008. matplotlib.transforms.Bbox.from_extents
  1009. """
  1010. self._set_position(pos, which=which)
  1011. # because this is being called externally to the library we
  1012. # don't let it be in the layout.
  1013. self.set_in_layout(False)
  1014. def _set_position(self, pos, which='both'):
  1015. """
  1016. Private version of set_position.
  1017. Call this internally to get the same functionality of `set_position`,
  1018. but not to take the axis out of the constrained_layout hierarchy.
  1019. """
  1020. if not isinstance(pos, mtransforms.BboxBase):
  1021. pos = mtransforms.Bbox.from_bounds(*pos)
  1022. for ax in self._twinned_axes.get_siblings(self):
  1023. if which in ('both', 'active'):
  1024. ax._position.set(pos)
  1025. if which in ('both', 'original'):
  1026. ax._originalPosition.set(pos)
  1027. self.stale = True
  1028. def reset_position(self):
  1029. """
  1030. Reset the active position to the original position.
  1031. This undoes changes to the active position (as defined in
  1032. `.set_position`) which may have been performed to satisfy fixed-aspect
  1033. constraints.
  1034. """
  1035. for ax in self._twinned_axes.get_siblings(self):
  1036. pos = ax.get_position(original=True)
  1037. ax.set_position(pos, which='active')
  1038. def set_axes_locator(self, locator):
  1039. """
  1040. Set the Axes locator.
  1041. Parameters
  1042. ----------
  1043. locator : Callable[[Axes, Renderer], Bbox]
  1044. """
  1045. self._axes_locator = locator
  1046. self.stale = True
  1047. def get_axes_locator(self):
  1048. """
  1049. Return the axes_locator.
  1050. """
  1051. return self._axes_locator
  1052. def _set_artist_props(self, a):
  1053. """Set the boilerplate props for artists added to Axes."""
  1054. a.set_figure(self.get_figure(root=False))
  1055. if not a.is_transform_set():
  1056. a.set_transform(self.transData)
  1057. a.axes = self
  1058. if a.get_mouseover():
  1059. self._mouseover_set.add(a)
  1060. def _gen_axes_patch(self):
  1061. """
  1062. Returns
  1063. -------
  1064. Patch
  1065. The patch used to draw the background of the Axes. It is also used
  1066. as the clipping path for any data elements on the Axes.
  1067. In the standard Axes, this is a rectangle, but in other projections
  1068. it may not be.
  1069. Notes
  1070. -----
  1071. Intended to be overridden by new projection types.
  1072. """
  1073. return mpatches.Rectangle((0.0, 0.0), 1.0, 1.0)
  1074. def _gen_axes_spines(self, locations=None, offset=0.0, units='inches'):
  1075. """
  1076. Returns
  1077. -------
  1078. dict
  1079. Mapping of spine names to `.Line2D` or `.Patch` instances that are
  1080. used to draw Axes spines.
  1081. In the standard Axes, spines are single line segments, but in other
  1082. projections they may not be.
  1083. Notes
  1084. -----
  1085. Intended to be overridden by new projection types.
  1086. """
  1087. return {side: mspines.Spine.linear_spine(self, side)
  1088. for side in ['left', 'right', 'bottom', 'top']}
  1089. def sharex(self, other):
  1090. """
  1091. Share the x-axis with *other*.
  1092. This is equivalent to passing ``sharex=other`` when constructing the
  1093. Axes, and cannot be used if the x-axis is already being shared with
  1094. another Axes. Note that it is not possible to unshare axes.
  1095. """
  1096. _api.check_isinstance(_AxesBase, other=other)
  1097. if self._sharex is not None and other is not self._sharex:
  1098. raise ValueError("x-axis is already shared")
  1099. self._shared_axes["x"].join(self, other)
  1100. self._sharex = other
  1101. self.xaxis.major = other.xaxis.major # Ticker instances holding
  1102. self.xaxis.minor = other.xaxis.minor # locator and formatter.
  1103. x0, x1 = other.get_xlim()
  1104. self.set_xlim(x0, x1, emit=False, auto=other.get_autoscalex_on())
  1105. self.xaxis._scale = other.xaxis._scale
  1106. def sharey(self, other):
  1107. """
  1108. Share the y-axis with *other*.
  1109. This is equivalent to passing ``sharey=other`` when constructing the
  1110. Axes, and cannot be used if the y-axis is already being shared with
  1111. another Axes. Note that it is not possible to unshare axes.
  1112. """
  1113. _api.check_isinstance(_AxesBase, other=other)
  1114. if self._sharey is not None and other is not self._sharey:
  1115. raise ValueError("y-axis is already shared")
  1116. self._shared_axes["y"].join(self, other)
  1117. self._sharey = other
  1118. self.yaxis.major = other.yaxis.major # Ticker instances holding
  1119. self.yaxis.minor = other.yaxis.minor # locator and formatter.
  1120. y0, y1 = other.get_ylim()
  1121. self.set_ylim(y0, y1, emit=False, auto=other.get_autoscaley_on())
  1122. self.yaxis._scale = other.yaxis._scale
  1123. def __clear(self):
  1124. """Clear the Axes."""
  1125. # The actual implementation of clear() as long as clear() has to be
  1126. # an adapter delegating to the correct implementation.
  1127. # The implementation can move back into clear() when the
  1128. # deprecation on cla() subclassing expires.
  1129. # stash the current visibility state
  1130. if hasattr(self, 'patch'):
  1131. patch_visible = self.patch.get_visible()
  1132. else:
  1133. patch_visible = True
  1134. xaxis_visible = self.xaxis.get_visible()
  1135. yaxis_visible = self.yaxis.get_visible()
  1136. for axis in self._axis_map.values():
  1137. axis.clear() # Also resets the scale to linear.
  1138. for spine in self.spines.values():
  1139. spine._clear() # Use _clear to not clear Axis again
  1140. self.ignore_existing_data_limits = True
  1141. self.callbacks = cbook.CallbackRegistry(
  1142. signals=["xlim_changed", "ylim_changed", "zlim_changed"])
  1143. # update the minor locator for x and y axis based on rcParams
  1144. if mpl.rcParams['xtick.minor.visible']:
  1145. self.xaxis.set_minor_locator(mticker.AutoMinorLocator())
  1146. if mpl.rcParams['ytick.minor.visible']:
  1147. self.yaxis.set_minor_locator(mticker.AutoMinorLocator())
  1148. self._xmargin = mpl.rcParams['axes.xmargin']
  1149. self._ymargin = mpl.rcParams['axes.ymargin']
  1150. self._tight = None
  1151. self._use_sticky_edges = True
  1152. self._get_lines = _process_plot_var_args()
  1153. self._get_patches_for_fill = _process_plot_var_args('Polygon')
  1154. self._gridOn = mpl.rcParams['axes.grid']
  1155. # Swap children to minimize time we spend in an invalid state
  1156. old_children, self._children = self._children, []
  1157. for chld in old_children:
  1158. chld._remove_method = None
  1159. chld._parent_figure = None
  1160. chld.axes = None
  1161. # Use list.clear to break the `artist._remove_method` reference cycle
  1162. old_children.clear()
  1163. self._mouseover_set = _OrderedSet()
  1164. self.child_axes = []
  1165. self._current_image = None # strictly for pyplot via _sci, _gci
  1166. self._projection_init = None # strictly for pyplot.subplot
  1167. self.legend_ = None
  1168. self.containers = []
  1169. self.grid(False) # Disable grid on init to use rcParameter
  1170. self.grid(self._gridOn, which=mpl.rcParams['axes.grid.which'],
  1171. axis=mpl.rcParams['axes.grid.axis'])
  1172. props = font_manager.FontProperties(
  1173. size=mpl.rcParams['axes.titlesize'],
  1174. weight=mpl.rcParams['axes.titleweight'])
  1175. y = mpl.rcParams['axes.titley']
  1176. if y is None:
  1177. y = 1.0
  1178. self._autotitlepos = True
  1179. else:
  1180. self._autotitlepos = False
  1181. self.title = mtext.Text(
  1182. x=0.5, y=y, text='',
  1183. fontproperties=props,
  1184. verticalalignment='baseline',
  1185. horizontalalignment='center',
  1186. )
  1187. self._left_title = mtext.Text(
  1188. x=0.0, y=y, text='',
  1189. fontproperties=props.copy(),
  1190. verticalalignment='baseline',
  1191. horizontalalignment='left', )
  1192. self._right_title = mtext.Text(
  1193. x=1.0, y=y, text='',
  1194. fontproperties=props.copy(),
  1195. verticalalignment='baseline',
  1196. horizontalalignment='right',
  1197. )
  1198. title_offset_points = mpl.rcParams['axes.titlepad']
  1199. # refactor this out so it can be called in ax.set_title if
  1200. # pad argument used...
  1201. self._set_title_offset_trans(title_offset_points)
  1202. for _title in (self.title, self._left_title, self._right_title):
  1203. self._set_artist_props(_title)
  1204. # The patch draws the background of the Axes. We want this to be below
  1205. # the other artists. We use the frame to draw the edges so we are
  1206. # setting the edgecolor to None.
  1207. self.patch = self._gen_axes_patch()
  1208. self.patch.set_figure(self.get_figure(root=False))
  1209. self.patch.set_facecolor(self._facecolor)
  1210. self.patch.set_edgecolor('none')
  1211. self.patch.set_linewidth(0)
  1212. self.patch.set_transform(self.transAxes)
  1213. self.set_axis_on()
  1214. self.xaxis.set_clip_path(self.patch)
  1215. self.yaxis.set_clip_path(self.patch)
  1216. if self._sharex is not None:
  1217. self.xaxis.set_visible(xaxis_visible)
  1218. self.patch.set_visible(patch_visible)
  1219. if self._sharey is not None:
  1220. self.yaxis.set_visible(yaxis_visible)
  1221. self.patch.set_visible(patch_visible)
  1222. # This comes last, as the call to _set_lim may trigger an autoscale (in
  1223. # case of shared axes), requiring children to be already set up.
  1224. for name, axis in self._axis_map.items():
  1225. share = getattr(self, f"_share{name}")
  1226. if share is not None:
  1227. getattr(self, f"share{name}")(share)
  1228. else:
  1229. # Although the scale was set to linear as part of clear,
  1230. # polar requires that _set_scale is called again
  1231. if self.name == "polar":
  1232. axis._set_scale("linear")
  1233. axis._set_lim(0, 1, auto=True)
  1234. self._update_transScale()
  1235. self.stale = True
  1236. def clear(self):
  1237. """Clear the Axes."""
  1238. # Act as an alias, or as the superclass implementation depending on the
  1239. # subclass implementation.
  1240. if self._subclass_uses_cla:
  1241. self.cla()
  1242. else:
  1243. self.__clear()
  1244. def cla(self):
  1245. """Clear the Axes."""
  1246. # Act as an alias, or as the superclass implementation depending on the
  1247. # subclass implementation.
  1248. if self._subclass_uses_cla:
  1249. self.__clear()
  1250. else:
  1251. self.clear()
  1252. class ArtistList(Sequence):
  1253. """
  1254. A sublist of Axes children based on their type.
  1255. The type-specific children sublists were made immutable in Matplotlib
  1256. 3.7. In the future these artist lists may be replaced by tuples. Use
  1257. as if this is a tuple already.
  1258. """
  1259. def __init__(self, axes, prop_name,
  1260. valid_types=None, invalid_types=None):
  1261. """
  1262. Parameters
  1263. ----------
  1264. axes : `~matplotlib.axes.Axes`
  1265. The Axes from which this sublist will pull the children
  1266. Artists.
  1267. prop_name : str
  1268. The property name used to access this sublist from the Axes;
  1269. used to generate deprecation warnings.
  1270. valid_types : list of type, optional
  1271. A list of types that determine which children will be returned
  1272. by this sublist. If specified, then the Artists in the sublist
  1273. must be instances of any of these types. If unspecified, then
  1274. any type of Artist is valid (unless limited by
  1275. *invalid_types*.)
  1276. invalid_types : tuple, optional
  1277. A list of types that determine which children will *not* be
  1278. returned by this sublist. If specified, then Artists in the
  1279. sublist will never be an instance of these types. Otherwise, no
  1280. types will be excluded.
  1281. """
  1282. self._axes = axes
  1283. self._prop_name = prop_name
  1284. self._type_check = lambda artist: (
  1285. (not valid_types or isinstance(artist, valid_types)) and
  1286. (not invalid_types or not isinstance(artist, invalid_types))
  1287. )
  1288. def __repr__(self):
  1289. return f'<Axes.ArtistList of {len(self)} {self._prop_name}>'
  1290. def __len__(self):
  1291. return sum(self._type_check(artist)
  1292. for artist in self._axes._children)
  1293. def __iter__(self):
  1294. for artist in list(self._axes._children):
  1295. if self._type_check(artist):
  1296. yield artist
  1297. def __getitem__(self, key):
  1298. return [artist
  1299. for artist in self._axes._children
  1300. if self._type_check(artist)][key]
  1301. def __add__(self, other):
  1302. if isinstance(other, (list, _AxesBase.ArtistList)):
  1303. return [*self, *other]
  1304. if isinstance(other, (tuple, _AxesBase.ArtistList)):
  1305. return (*self, *other)
  1306. return NotImplemented
  1307. def __radd__(self, other):
  1308. if isinstance(other, list):
  1309. return other + list(self)
  1310. if isinstance(other, tuple):
  1311. return other + tuple(self)
  1312. return NotImplemented
  1313. @property
  1314. def artists(self):
  1315. return self.ArtistList(self, 'artists', invalid_types=(
  1316. mcoll.Collection, mimage.AxesImage, mlines.Line2D, mpatches.Patch,
  1317. mtable.Table, mtext.Text))
  1318. @property
  1319. def collections(self):
  1320. return self.ArtistList(self, 'collections',
  1321. valid_types=mcoll.Collection)
  1322. @property
  1323. def images(self):
  1324. return self.ArtistList(self, 'images', valid_types=mimage.AxesImage)
  1325. @property
  1326. def lines(self):
  1327. return self.ArtistList(self, 'lines', valid_types=mlines.Line2D)
  1328. @property
  1329. def patches(self):
  1330. return self.ArtistList(self, 'patches', valid_types=mpatches.Patch)
  1331. @property
  1332. def tables(self):
  1333. return self.ArtistList(self, 'tables', valid_types=mtable.Table)
  1334. @property
  1335. def texts(self):
  1336. return self.ArtistList(self, 'texts', valid_types=mtext.Text)
  1337. def get_facecolor(self):
  1338. """Get the facecolor of the Axes."""
  1339. return self.patch.get_facecolor()
  1340. def set_facecolor(self, color):
  1341. """
  1342. Set the facecolor of the Axes.
  1343. Parameters
  1344. ----------
  1345. color : :mpltype:`color`
  1346. """
  1347. self._facecolor = color
  1348. self.stale = True
  1349. return self.patch.set_facecolor(color)
  1350. def _set_title_offset_trans(self, title_offset_points):
  1351. """
  1352. Set the offset for the title either from :rc:`axes.titlepad`
  1353. or from set_title kwarg ``pad``.
  1354. """
  1355. self.titleOffsetTrans = mtransforms.ScaledTranslation(
  1356. 0.0, title_offset_points / 72,
  1357. self.get_figure(root=False).dpi_scale_trans)
  1358. for _title in (self.title, self._left_title, self._right_title):
  1359. _title.set_transform(self.transAxes + self.titleOffsetTrans)
  1360. _title.set_clip_box(None)
  1361. def set_prop_cycle(self, *args, **kwargs):
  1362. """
  1363. Set the property cycle of the Axes.
  1364. The property cycle controls the style properties such as color,
  1365. marker and linestyle of future plot commands. The style properties
  1366. of data already added to the Axes are not modified.
  1367. Call signatures::
  1368. set_prop_cycle(cycler)
  1369. set_prop_cycle(label=values, label2=values2, ...)
  1370. set_prop_cycle(label, values)
  1371. Form 1 sets given `~cycler.Cycler` object.
  1372. Form 2 creates a `~cycler.Cycler` which cycles over one or more
  1373. properties simultaneously and set it as the property cycle of the
  1374. Axes. If multiple properties are given, their value lists must have
  1375. the same length. This is just a shortcut for explicitly creating a
  1376. cycler and passing it to the function, i.e. it's short for
  1377. ``set_prop_cycle(cycler(label=values, label2=values2, ...))``.
  1378. Form 3 creates a `~cycler.Cycler` for a single property and set it
  1379. as the property cycle of the Axes. This form exists for compatibility
  1380. with the original `cycler.cycler` interface. Its use is discouraged
  1381. in favor of the kwarg form, i.e. ``set_prop_cycle(label=values)``.
  1382. Parameters
  1383. ----------
  1384. cycler : `~cycler.Cycler` or ``None``
  1385. Set the given Cycler. *None* resets to the cycle defined by the
  1386. current style.
  1387. .. ACCEPTS: `~cycler.Cycler`
  1388. label : str
  1389. The property key. Must be a valid `.Artist` property.
  1390. For example, 'color' or 'linestyle'. Aliases are allowed,
  1391. such as 'c' for 'color' and 'lw' for 'linewidth'.
  1392. values : iterable
  1393. Finite-length iterable of the property values. These values
  1394. are validated and will raise a ValueError if invalid.
  1395. See Also
  1396. --------
  1397. matplotlib.rcsetup.cycler
  1398. Convenience function for creating validated cyclers for properties.
  1399. cycler.cycler
  1400. The original function for creating unvalidated cyclers.
  1401. Examples
  1402. --------
  1403. Setting the property cycle for a single property:
  1404. >>> ax.set_prop_cycle(color=['red', 'green', 'blue'])
  1405. Setting the property cycle for simultaneously cycling over multiple
  1406. properties (e.g. red circle, green plus, blue cross):
  1407. >>> ax.set_prop_cycle(color=['red', 'green', 'blue'],
  1408. ... marker=['o', '+', 'x'])
  1409. """
  1410. if args and kwargs:
  1411. raise TypeError("Cannot supply both positional and keyword "
  1412. "arguments to this method.")
  1413. # Can't do `args == (None,)` as that crashes cycler.
  1414. if len(args) == 1 and args[0] is None:
  1415. prop_cycle = None
  1416. else:
  1417. prop_cycle = cycler(*args, **kwargs)
  1418. self._get_lines.set_prop_cycle(prop_cycle)
  1419. self._get_patches_for_fill.set_prop_cycle(prop_cycle)
  1420. def get_aspect(self):
  1421. """
  1422. Return the aspect ratio of the Axes scaling.
  1423. This is either "auto" or a float giving the ratio of y/x-scale.
  1424. """
  1425. return self._aspect
  1426. def set_aspect(self, aspect, adjustable=None, anchor=None, share=False):
  1427. """
  1428. Set the aspect ratio of the Axes scaling, i.e. y/x-scale.
  1429. Parameters
  1430. ----------
  1431. aspect : {'auto', 'equal'} or float
  1432. Possible values:
  1433. - 'auto': fill the position rectangle with data.
  1434. - 'equal': same as ``aspect=1``, i.e. same scaling for x and y.
  1435. - *float*: The displayed size of 1 unit in y-data coordinates will
  1436. be *aspect* times the displayed size of 1 unit in x-data
  1437. coordinates; e.g. for ``aspect=2`` a square in data coordinates
  1438. will be rendered with a height of twice its width.
  1439. adjustable : None or {'box', 'datalim'}, optional
  1440. If not ``None``, this defines which parameter will be adjusted to
  1441. meet the required aspect. See `.set_adjustable` for further
  1442. details.
  1443. anchor : None or str or (float, float), optional
  1444. If not ``None``, this defines where the Axes will be drawn if there
  1445. is extra space due to aspect constraints. The most common way
  1446. to specify the anchor are abbreviations of cardinal directions:
  1447. ===== =====================
  1448. value description
  1449. ===== =====================
  1450. 'C' centered
  1451. 'SW' lower left corner
  1452. 'S' middle of bottom edge
  1453. 'SE' lower right corner
  1454. etc.
  1455. ===== =====================
  1456. See `~.Axes.set_anchor` for further details.
  1457. share : bool, default: False
  1458. If ``True``, apply the settings to all shared Axes.
  1459. See Also
  1460. --------
  1461. matplotlib.axes.Axes.set_adjustable
  1462. Set how the Axes adjusts to achieve the required aspect ratio.
  1463. matplotlib.axes.Axes.set_anchor
  1464. Set the position in case of extra space.
  1465. """
  1466. if cbook._str_equal(aspect, 'equal'):
  1467. aspect = 1
  1468. if not cbook._str_equal(aspect, 'auto'):
  1469. aspect = float(aspect) # raise ValueError if necessary
  1470. if aspect <= 0 or not np.isfinite(aspect):
  1471. raise ValueError("aspect must be finite and positive ")
  1472. if share:
  1473. axes = {sibling for name in self._axis_names
  1474. for sibling in self._shared_axes[name].get_siblings(self)}
  1475. else:
  1476. axes = [self]
  1477. for ax in axes:
  1478. ax._aspect = aspect
  1479. if adjustable is None:
  1480. adjustable = self._adjustable
  1481. self.set_adjustable(adjustable, share=share) # Handle sharing.
  1482. if anchor is not None:
  1483. self.set_anchor(anchor, share=share)
  1484. self.stale = True
  1485. def get_adjustable(self):
  1486. """
  1487. Return whether the Axes will adjust its physical dimension ('box') or
  1488. its data limits ('datalim') to achieve the desired aspect ratio.
  1489. See Also
  1490. --------
  1491. matplotlib.axes.Axes.set_adjustable
  1492. Set how the Axes adjusts to achieve the required aspect ratio.
  1493. matplotlib.axes.Axes.set_aspect
  1494. For a description of aspect handling.
  1495. """
  1496. return self._adjustable
  1497. def set_adjustable(self, adjustable, share=False):
  1498. """
  1499. Set how the Axes adjusts to achieve the required aspect ratio.
  1500. Parameters
  1501. ----------
  1502. adjustable : {'box', 'datalim'}
  1503. If 'box', change the physical dimensions of the Axes.
  1504. If 'datalim', change the ``x`` or ``y`` data limits. This
  1505. may ignore explicitly defined axis limits.
  1506. share : bool, default: False
  1507. If ``True``, apply the settings to all shared Axes.
  1508. See Also
  1509. --------
  1510. matplotlib.axes.Axes.set_aspect
  1511. For a description of aspect handling.
  1512. Notes
  1513. -----
  1514. Shared Axes (of which twinned Axes are a special case)
  1515. impose restrictions on how aspect ratios can be imposed.
  1516. For twinned Axes, use 'datalim'. For Axes that share both
  1517. x and y, use 'box'. Otherwise, either 'datalim' or 'box'
  1518. may be used. These limitations are partly a requirement
  1519. to avoid over-specification, and partly a result of the
  1520. particular implementation we are currently using, in
  1521. which the adjustments for aspect ratios are done sequentially
  1522. and independently on each Axes as it is drawn.
  1523. """
  1524. _api.check_in_list(["box", "datalim"], adjustable=adjustable)
  1525. if share:
  1526. axs = {sibling for name in self._axis_names
  1527. for sibling in self._shared_axes[name].get_siblings(self)}
  1528. else:
  1529. axs = [self]
  1530. if (adjustable == "datalim"
  1531. and any(getattr(ax.get_data_ratio, "__func__", None)
  1532. != _AxesBase.get_data_ratio
  1533. for ax in axs)):
  1534. # Limits adjustment by apply_aspect assumes that the axes' aspect
  1535. # ratio can be computed from the data limits and scales.
  1536. raise ValueError("Cannot set Axes adjustable to 'datalim' for "
  1537. "Axes which override 'get_data_ratio'")
  1538. for ax in axs:
  1539. ax._adjustable = adjustable
  1540. self.stale = True
  1541. def get_box_aspect(self):
  1542. """
  1543. Return the Axes box aspect, i.e. the ratio of height to width.
  1544. The box aspect is ``None`` (i.e. chosen depending on the available
  1545. figure space) unless explicitly specified.
  1546. See Also
  1547. --------
  1548. matplotlib.axes.Axes.set_box_aspect
  1549. for a description of box aspect.
  1550. matplotlib.axes.Axes.set_aspect
  1551. for a description of aspect handling.
  1552. """
  1553. return self._box_aspect
  1554. def set_box_aspect(self, aspect=None):
  1555. """
  1556. Set the Axes box aspect, i.e. the ratio of height to width.
  1557. This defines the aspect of the Axes in figure space and is not to be
  1558. confused with the data aspect (see `~.Axes.set_aspect`).
  1559. Parameters
  1560. ----------
  1561. aspect : float or None
  1562. Changes the physical dimensions of the Axes, such that the ratio
  1563. of the Axes height to the Axes width in physical units is equal to
  1564. *aspect*. Defining a box aspect will change the *adjustable*
  1565. property to 'datalim' (see `~.Axes.set_adjustable`).
  1566. *None* will disable a fixed box aspect so that height and width
  1567. of the Axes are chosen independently.
  1568. See Also
  1569. --------
  1570. matplotlib.axes.Axes.set_aspect
  1571. for a description of aspect handling.
  1572. """
  1573. axs = {*self._twinned_axes.get_siblings(self),
  1574. *self._twinned_axes.get_siblings(self)}
  1575. if aspect is not None:
  1576. aspect = float(aspect)
  1577. # when box_aspect is set to other than ´None`,
  1578. # adjustable must be "datalim"
  1579. for ax in axs:
  1580. ax.set_adjustable("datalim")
  1581. for ax in axs:
  1582. ax._box_aspect = aspect
  1583. ax.stale = True
  1584. def get_anchor(self):
  1585. """
  1586. Get the anchor location.
  1587. See Also
  1588. --------
  1589. matplotlib.axes.Axes.set_anchor
  1590. for a description of the anchor.
  1591. matplotlib.axes.Axes.set_aspect
  1592. for a description of aspect handling.
  1593. """
  1594. return self._anchor
  1595. def set_anchor(self, anchor, share=False):
  1596. """
  1597. Define the anchor location.
  1598. The actual drawing area (active position) of the Axes may be smaller
  1599. than the Bbox (original position) when a fixed aspect is required. The
  1600. anchor defines where the drawing area will be located within the
  1601. available space.
  1602. Parameters
  1603. ----------
  1604. anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}
  1605. Either an (*x*, *y*) pair of relative coordinates (0 is left or
  1606. bottom, 1 is right or top), 'C' (center), or a cardinal direction
  1607. ('SW', southwest, is bottom left, etc.). str inputs are shorthands
  1608. for (*x*, *y*) coordinates, as shown in the following diagram::
  1609. ┌─────────────────┬─────────────────┬─────────────────┐
  1610. │ 'NW' (0.0, 1.0) │ 'N' (0.5, 1.0) │ 'NE' (1.0, 1.0) │
  1611. ├─────────────────┼─────────────────┼─────────────────┤
  1612. │ 'W' (0.0, 0.5) │ 'C' (0.5, 0.5) │ 'E' (1.0, 0.5) │
  1613. ├─────────────────┼─────────────────┼─────────────────┤
  1614. │ 'SW' (0.0, 0.0) │ 'S' (0.5, 0.0) │ 'SE' (1.0, 0.0) │
  1615. └─────────────────┴─────────────────┴─────────────────┘
  1616. share : bool, default: False
  1617. If ``True``, apply the settings to all shared Axes.
  1618. See Also
  1619. --------
  1620. matplotlib.axes.Axes.set_aspect
  1621. for a description of aspect handling.
  1622. """
  1623. if not (anchor in mtransforms.Bbox.coefs or len(anchor) == 2):
  1624. raise ValueError('argument must be among %s' %
  1625. ', '.join(mtransforms.Bbox.coefs))
  1626. if share:
  1627. axes = {sibling for name in self._axis_names
  1628. for sibling in self._shared_axes[name].get_siblings(self)}
  1629. else:
  1630. axes = [self]
  1631. for ax in axes:
  1632. ax._anchor = anchor
  1633. self.stale = True
  1634. def get_data_ratio(self):
  1635. """
  1636. Return the aspect ratio of the scaled data.
  1637. Notes
  1638. -----
  1639. This method is intended to be overridden by new projection types.
  1640. """
  1641. txmin, txmax = self.xaxis.get_transform().transform(self.get_xbound())
  1642. tymin, tymax = self.yaxis.get_transform().transform(self.get_ybound())
  1643. xsize = max(abs(txmax - txmin), 1e-30)
  1644. ysize = max(abs(tymax - tymin), 1e-30)
  1645. return ysize / xsize
  1646. def apply_aspect(self, position=None):
  1647. """
  1648. Adjust the Axes for a specified data aspect ratio.
  1649. Depending on `.get_adjustable` this will modify either the
  1650. Axes box (position) or the view limits. In the former case,
  1651. `~matplotlib.axes.Axes.get_anchor` will affect the position.
  1652. Parameters
  1653. ----------
  1654. position : None or .Bbox
  1655. .. note::
  1656. This parameter exists for historic reasons and is considered
  1657. internal. End users should not use it.
  1658. If not ``None``, this defines the position of the
  1659. Axes within the figure as a Bbox. See `~.Axes.get_position`
  1660. for further details.
  1661. Notes
  1662. -----
  1663. This is called automatically when each Axes is drawn. You may need
  1664. to call it yourself if you need to update the Axes position and/or
  1665. view limits before the Figure is drawn.
  1666. An alternative with a broader scope is `.Figure.draw_without_rendering`,
  1667. which updates all stale components of a figure, not only the positioning /
  1668. view limits of a single Axes.
  1669. See Also
  1670. --------
  1671. matplotlib.axes.Axes.set_aspect
  1672. For a description of aspect ratio handling.
  1673. matplotlib.axes.Axes.set_adjustable
  1674. Set how the Axes adjusts to achieve the required aspect ratio.
  1675. matplotlib.axes.Axes.set_anchor
  1676. Set the position in case of extra space.
  1677. matplotlib.figure.Figure.draw_without_rendering
  1678. Update all stale components of a figure.
  1679. Examples
  1680. --------
  1681. A typical usage example would be the following. `~.Axes.imshow` sets the
  1682. aspect to 1, but adapting the Axes position and extent to reflect this is
  1683. deferred until rendering for performance reasons. If you want to know the
  1684. Axes size before, you need to call `.apply_aspect` to get the correct
  1685. values.
  1686. >>> fig, ax = plt.subplots()
  1687. >>> ax.imshow(np.zeros((3, 3)))
  1688. >>> ax.bbox.width, ax.bbox.height
  1689. (496.0, 369.59999999999997)
  1690. >>> ax.apply_aspect()
  1691. >>> ax.bbox.width, ax.bbox.height
  1692. (369.59999999999997, 369.59999999999997)
  1693. """
  1694. if position is None:
  1695. position = self.get_position(original=True)
  1696. aspect = self.get_aspect()
  1697. if aspect == 'auto' and self._box_aspect is None:
  1698. self._set_position(position, which='active')
  1699. return
  1700. trans = self.get_figure(root=False).transSubfigure
  1701. bb = mtransforms.Bbox.unit().transformed(trans)
  1702. # this is the physical aspect of the panel (or figure):
  1703. fig_aspect = bb.height / bb.width
  1704. if self._adjustable == 'box':
  1705. if self in self._twinned_axes:
  1706. raise RuntimeError("Adjustable 'box' is not allowed in a "
  1707. "twinned Axes; use 'datalim' instead")
  1708. box_aspect = aspect * self.get_data_ratio()
  1709. pb = position.frozen()
  1710. pb1 = pb.shrunk_to_aspect(box_aspect, pb, fig_aspect)
  1711. self._set_position(pb1.anchored(self.get_anchor(), pb), 'active')
  1712. return
  1713. # The following is only seen if self._adjustable == 'datalim'
  1714. if self._box_aspect is not None:
  1715. pb = position.frozen()
  1716. pb1 = pb.shrunk_to_aspect(self._box_aspect, pb, fig_aspect)
  1717. self._set_position(pb1.anchored(self.get_anchor(), pb), 'active')
  1718. if aspect == "auto":
  1719. return
  1720. # reset active to original in case it had been changed by prior use
  1721. # of 'box'
  1722. if self._box_aspect is None:
  1723. self._set_position(position, which='active')
  1724. else:
  1725. position = pb1.anchored(self.get_anchor(), pb)
  1726. x_trf = self.xaxis.get_transform()
  1727. y_trf = self.yaxis.get_transform()
  1728. xmin, xmax = x_trf.transform(self.get_xbound())
  1729. ymin, ymax = y_trf.transform(self.get_ybound())
  1730. xsize = max(abs(xmax - xmin), 1e-30)
  1731. ysize = max(abs(ymax - ymin), 1e-30)
  1732. box_aspect = fig_aspect * (position.height / position.width)
  1733. data_ratio = box_aspect / aspect
  1734. y_expander = data_ratio * xsize / ysize - 1
  1735. # If y_expander > 0, the dy/dx viewLim ratio needs to increase
  1736. if abs(y_expander) < 0.005:
  1737. return
  1738. dL = self.dataLim
  1739. x0, x1 = x_trf.transform(dL.intervalx)
  1740. y0, y1 = y_trf.transform(dL.intervaly)
  1741. xr = 1.05 * (x1 - x0)
  1742. yr = 1.05 * (y1 - y0)
  1743. xmarg = xsize - xr
  1744. ymarg = ysize - yr
  1745. Ysize = data_ratio * xsize
  1746. Xsize = ysize / data_ratio
  1747. Xmarg = Xsize - xr
  1748. Ymarg = Ysize - yr
  1749. # Setting these targets to, e.g., 0.05*xr does not seem to help.
  1750. xm = 0
  1751. ym = 0
  1752. shared_x = self in self._shared_axes["x"]
  1753. shared_y = self in self._shared_axes["y"]
  1754. if shared_x and shared_y:
  1755. raise RuntimeError("set_aspect(..., adjustable='datalim') or "
  1756. "axis('equal') are not allowed when both axes "
  1757. "are shared. Try set_aspect(..., "
  1758. "adjustable='box').")
  1759. # If y is shared, then we are only allowed to change x, etc.
  1760. if shared_y:
  1761. adjust_y = False
  1762. else:
  1763. if xmarg > xm and ymarg > ym:
  1764. adjy = ((Ymarg > 0 and y_expander < 0) or
  1765. (Xmarg < 0 and y_expander > 0))
  1766. else:
  1767. adjy = y_expander > 0
  1768. adjust_y = shared_x or adjy # (Ymarg > xmarg)
  1769. if adjust_y:
  1770. yc = 0.5 * (ymin + ymax)
  1771. y0 = yc - Ysize / 2.0
  1772. y1 = yc + Ysize / 2.0
  1773. if not self.get_autoscaley_on():
  1774. _log.warning("Ignoring fixed y limits to fulfill fixed data aspect "
  1775. "with adjustable data limits.")
  1776. self.set_ybound(y_trf.inverted().transform([y0, y1]))
  1777. else:
  1778. xc = 0.5 * (xmin + xmax)
  1779. x0 = xc - Xsize / 2.0
  1780. x1 = xc + Xsize / 2.0
  1781. if not self.get_autoscalex_on():
  1782. _log.warning("Ignoring fixed x limits to fulfill fixed data aspect "
  1783. "with adjustable data limits.")
  1784. self.set_xbound(x_trf.inverted().transform([x0, x1]))
  1785. def axis(self, arg=None, /, *, emit=True, **kwargs):
  1786. """
  1787. Convenience method to get or set some axis properties.
  1788. Call signatures::
  1789. xmin, xmax, ymin, ymax = axis()
  1790. xmin, xmax, ymin, ymax = axis([xmin, xmax, ymin, ymax])
  1791. xmin, xmax, ymin, ymax = axis(option)
  1792. xmin, xmax, ymin, ymax = axis(**kwargs)
  1793. Parameters
  1794. ----------
  1795. xmin, xmax, ymin, ymax : float, optional
  1796. The axis limits to be set. This can also be achieved using ::
  1797. ax.set(xlim=(xmin, xmax), ylim=(ymin, ymax))
  1798. option : bool or str
  1799. If a bool, turns axis lines and labels on or off. If a string,
  1800. possible values are:
  1801. ================ ===========================================================
  1802. Value Description
  1803. ================ ===========================================================
  1804. 'off' or `False` Hide all axis decorations, i.e. axis labels, spines,
  1805. tick marks, tick labels, and grid lines.
  1806. This is the same as `~.Axes.set_axis_off()`.
  1807. 'on' or `True` Do not hide all axis decorations, i.e. axis labels, spines,
  1808. tick marks, tick labels, and grid lines.
  1809. This is the same as `~.Axes.set_axis_on()`.
  1810. 'equal' Set equal scaling (i.e., make circles circular) by
  1811. changing the axis limits. This is the same as
  1812. ``ax.set_aspect('equal', adjustable='datalim')``.
  1813. Explicit data limits may not be respected in this case.
  1814. 'scaled' Set equal scaling (i.e., make circles circular) by
  1815. changing dimensions of the plot box. This is the same as
  1816. ``ax.set_aspect('equal', adjustable='box', anchor='C')``.
  1817. Additionally, further autoscaling will be disabled.
  1818. 'tight' Set limits just large enough to show all data, then
  1819. disable further autoscaling.
  1820. 'auto' Automatic scaling (fill plot box with data).
  1821. 'image' 'scaled' with axis limits equal to data limits.
  1822. 'square' Square plot; similar to 'scaled', but initially forcing
  1823. ``xmax-xmin == ymax-ymin``.
  1824. ================ ===========================================================
  1825. emit : bool, default: True
  1826. Whether observers are notified of the axis limit change.
  1827. This option is passed on to `~.Axes.set_xlim` and
  1828. `~.Axes.set_ylim`.
  1829. Returns
  1830. -------
  1831. xmin, xmax, ymin, ymax : float
  1832. The axis limits.
  1833. See Also
  1834. --------
  1835. matplotlib.axes.Axes.set_xlim
  1836. matplotlib.axes.Axes.set_ylim
  1837. Notes
  1838. -----
  1839. For 3D Axes, this method additionally takes *zmin*, *zmax* as
  1840. parameters and likewise returns them.
  1841. """
  1842. if isinstance(arg, (str, bool)):
  1843. if arg is True:
  1844. arg = 'on'
  1845. if arg is False:
  1846. arg = 'off'
  1847. arg = arg.lower()
  1848. if arg == 'on':
  1849. self.set_axis_on()
  1850. elif arg == 'off':
  1851. self.set_axis_off()
  1852. elif arg in [
  1853. 'equal', 'tight', 'scaled', 'auto', 'image', 'square']:
  1854. self.set_autoscale_on(True)
  1855. self.set_aspect('auto')
  1856. self.autoscale_view(tight=False)
  1857. if arg == 'equal':
  1858. self.set_aspect('equal', adjustable='datalim')
  1859. elif arg == 'scaled':
  1860. self.set_aspect('equal', adjustable='box', anchor='C')
  1861. self.set_autoscale_on(False) # Req. by Mark Bakker
  1862. elif arg == 'tight':
  1863. self.autoscale_view(tight=True)
  1864. self.set_autoscale_on(False)
  1865. elif arg == 'image':
  1866. self.autoscale_view(tight=True)
  1867. self.set_autoscale_on(False)
  1868. self.set_aspect('equal', adjustable='box', anchor='C')
  1869. elif arg == 'square':
  1870. self.set_aspect('equal', adjustable='box', anchor='C')
  1871. self.set_autoscale_on(False)
  1872. xlim = self.get_xlim()
  1873. ylim = self.get_ylim()
  1874. edge_size = max(np.diff(xlim), np.diff(ylim))[0]
  1875. self.set_xlim([xlim[0], xlim[0] + edge_size],
  1876. emit=emit, auto=False)
  1877. self.set_ylim([ylim[0], ylim[0] + edge_size],
  1878. emit=emit, auto=False)
  1879. else:
  1880. raise ValueError(f"Unrecognized string {arg!r} to axis; "
  1881. "try 'on' or 'off'")
  1882. else:
  1883. if arg is not None:
  1884. if len(arg) != 2*len(self._axis_names):
  1885. raise TypeError(
  1886. "The first argument to axis() must be an iterable of the form "
  1887. "[{}]".format(", ".join(
  1888. f"{name}min, {name}max" for name in self._axis_names)))
  1889. limits = {
  1890. name: arg[2*i:2*(i+1)]
  1891. for i, name in enumerate(self._axis_names)
  1892. }
  1893. else:
  1894. limits = {}
  1895. for name in self._axis_names:
  1896. ax_min = kwargs.pop(f'{name}min', None)
  1897. ax_max = kwargs.pop(f'{name}max', None)
  1898. limits[name] = (ax_min, ax_max)
  1899. for name, (ax_min, ax_max) in limits.items():
  1900. ax_auto = (None # Keep autoscale state as is.
  1901. if ax_min is None and ax_max is None
  1902. else False) # Turn off autoscale.
  1903. set_ax_lim = getattr(self, f'set_{name}lim')
  1904. set_ax_lim(ax_min, ax_max, emit=emit, auto=ax_auto)
  1905. if kwargs:
  1906. raise _api.kwarg_error("axis", kwargs)
  1907. lims = ()
  1908. for name in self._axis_names:
  1909. get_ax_lim = getattr(self, f'get_{name}lim')
  1910. lims += get_ax_lim()
  1911. return lims
  1912. def get_legend(self):
  1913. """Return the `.Legend` instance, or None if no legend is defined."""
  1914. return self.legend_
  1915. def get_images(self):
  1916. r"""Return a list of `.AxesImage`\s contained by the Axes."""
  1917. return cbook.silent_list('AxesImage', self.images)
  1918. def get_lines(self):
  1919. """Return a list of lines contained by the Axes."""
  1920. return cbook.silent_list('Line2D', self.lines)
  1921. def get_xaxis(self):
  1922. """
  1923. [*Discouraged*] Return the XAxis instance.
  1924. .. admonition:: Discouraged
  1925. The use of this function is discouraged. You should instead
  1926. directly access the attribute `~.Axes.xaxis`.
  1927. """
  1928. return self.xaxis
  1929. def get_yaxis(self):
  1930. """
  1931. [*Discouraged*] Return the YAxis instance.
  1932. .. admonition:: Discouraged
  1933. The use of this function is discouraged. You should instead
  1934. directly access the attribute `~.Axes.yaxis`.
  1935. """
  1936. return self.yaxis
  1937. get_xgridlines = _axis_method_wrapper("xaxis", "get_gridlines")
  1938. get_xticklines = _axis_method_wrapper("xaxis", "get_ticklines")
  1939. get_ygridlines = _axis_method_wrapper("yaxis", "get_gridlines")
  1940. get_yticklines = _axis_method_wrapper("yaxis", "get_ticklines")
  1941. # Adding and tracking artists
  1942. def _sci(self, im):
  1943. """
  1944. Set the current image.
  1945. This image will be the target of colormap functions like
  1946. ``pyplot.viridis``, and other functions such as `~.pyplot.clim`. The
  1947. current image is an attribute of the current Axes.
  1948. """
  1949. _api.check_isinstance((mcoll.Collection, mimage.AxesImage), im=im)
  1950. if im not in self._children:
  1951. raise ValueError("Argument must be an image or collection in this Axes")
  1952. self._current_image = im
  1953. def _gci(self):
  1954. """Helper for `~matplotlib.pyplot.gci`; do not use elsewhere."""
  1955. return self._current_image
  1956. def has_data(self):
  1957. """
  1958. Return whether any artists have been added to the Axes.
  1959. This should not be used to determine whether the *dataLim*
  1960. need to be updated, and may not actually be useful for
  1961. anything.
  1962. """
  1963. return any(isinstance(a, (mcoll.Collection, mimage.AxesImage,
  1964. mlines.Line2D, mpatches.Patch))
  1965. for a in self._children)
  1966. def add_artist(self, a):
  1967. """
  1968. Add an `.Artist` to the Axes; return the artist.
  1969. Use `add_artist` only for artists for which there is no dedicated
  1970. "add" method; and if necessary, use a method such as `update_datalim`
  1971. to manually update the `~.Axes.dataLim` if the artist is to be included
  1972. in autoscaling.
  1973. If no ``transform`` has been specified when creating the artist (e.g.
  1974. ``artist.get_transform() == None``) then the transform is set to
  1975. ``ax.transData``.
  1976. """
  1977. a.axes = self
  1978. self._children.append(a)
  1979. a._remove_method = self._children.remove
  1980. self._set_artist_props(a)
  1981. if a.get_clip_path() is None:
  1982. a.set_clip_path(self.patch)
  1983. self.stale = True
  1984. return a
  1985. def add_child_axes(self, ax):
  1986. """
  1987. Add an `.Axes` to the Axes' children; return the child Axes.
  1988. This is the lowlevel version. See `.axes.Axes.inset_axes`.
  1989. """
  1990. # normally Axes have themselves as the Axes, but these need to have
  1991. # their parent...
  1992. # Need to bypass the getter...
  1993. ax._axes = self
  1994. ax.stale_callback = martist._stale_axes_callback
  1995. self.child_axes.append(ax)
  1996. ax._remove_method = functools.partial(
  1997. self.get_figure(root=False)._remove_axes, owners=[self.child_axes])
  1998. self.stale = True
  1999. return ax
  2000. def add_collection(self, collection, autolim=True):
  2001. """
  2002. Add a `.Collection` to the Axes; return the collection.
  2003. """
  2004. _api.check_isinstance(mcoll.Collection, collection=collection)
  2005. if not collection.get_label():
  2006. collection.set_label(f'_child{len(self._children)}')
  2007. self._children.append(collection)
  2008. collection._remove_method = self._children.remove
  2009. self._set_artist_props(collection)
  2010. if collection.get_clip_path() is None:
  2011. collection.set_clip_path(self.patch)
  2012. if autolim:
  2013. # Make sure viewLim is not stale (mostly to match
  2014. # pre-lazy-autoscale behavior, which is not really better).
  2015. self._unstale_viewLim()
  2016. datalim = collection.get_datalim(self.transData)
  2017. points = datalim.get_points()
  2018. if not np.isinf(datalim.minpos).all():
  2019. # By definition, if minpos (minimum positive value) is set
  2020. # (i.e., non-inf), then min(points) <= minpos <= max(points),
  2021. # and minpos would be superfluous. However, we add minpos to
  2022. # the call so that self.dataLim will update its own minpos.
  2023. # This ensures that log scales see the correct minimum.
  2024. points = np.concatenate([points, [datalim.minpos]])
  2025. # only update the dataLim for x/y if the collection uses transData
  2026. # in this direction.
  2027. x_is_data, y_is_data = (collection.get_transform()
  2028. .contains_branch_seperately(self.transData))
  2029. ox_is_data, oy_is_data = (collection.get_offset_transform()
  2030. .contains_branch_seperately(self.transData))
  2031. self.update_datalim(
  2032. points,
  2033. updatex=x_is_data or ox_is_data,
  2034. updatey=y_is_data or oy_is_data,
  2035. )
  2036. self.stale = True
  2037. return collection
  2038. def add_image(self, image):
  2039. """
  2040. Add an `.AxesImage` to the Axes; return the image.
  2041. """
  2042. _api.check_isinstance(mimage.AxesImage, image=image)
  2043. self._set_artist_props(image)
  2044. if not image.get_label():
  2045. image.set_label(f'_child{len(self._children)}')
  2046. self._children.append(image)
  2047. image._remove_method = self._children.remove
  2048. self.stale = True
  2049. return image
  2050. def _update_image_limits(self, image):
  2051. xmin, xmax, ymin, ymax = image.get_extent()
  2052. self.axes.update_datalim(((xmin, ymin), (xmax, ymax)))
  2053. def add_line(self, line):
  2054. """
  2055. Add a `.Line2D` to the Axes; return the line.
  2056. """
  2057. _api.check_isinstance(mlines.Line2D, line=line)
  2058. self._set_artist_props(line)
  2059. if line.get_clip_path() is None:
  2060. line.set_clip_path(self.patch)
  2061. self._update_line_limits(line)
  2062. if not line.get_label():
  2063. line.set_label(f'_child{len(self._children)}')
  2064. self._children.append(line)
  2065. line._remove_method = self._children.remove
  2066. self.stale = True
  2067. return line
  2068. def _add_text(self, txt):
  2069. """
  2070. Add a `.Text` to the Axes; return the text.
  2071. """
  2072. _api.check_isinstance(mtext.Text, txt=txt)
  2073. self._set_artist_props(txt)
  2074. self._children.append(txt)
  2075. txt._remove_method = self._children.remove
  2076. self.stale = True
  2077. return txt
  2078. def _update_line_limits(self, line):
  2079. """
  2080. Figures out the data limit of the given line, updating `.Axes.dataLim`.
  2081. """
  2082. path = line.get_path()
  2083. if path.vertices.size == 0:
  2084. return
  2085. line_trf = line.get_transform()
  2086. if line_trf == self.transData:
  2087. data_path = path
  2088. elif any(line_trf.contains_branch_seperately(self.transData)):
  2089. # Compute the transform from line coordinates to data coordinates.
  2090. trf_to_data = line_trf - self.transData
  2091. # If transData is affine we can use the cached non-affine component
  2092. # of line's path (since the non-affine part of line_trf is
  2093. # entirely encapsulated in trf_to_data).
  2094. if self.transData.is_affine:
  2095. line_trans_path = line._get_transformed_path()
  2096. na_path, _ = line_trans_path.get_transformed_path_and_affine()
  2097. data_path = trf_to_data.transform_path_affine(na_path)
  2098. else:
  2099. data_path = trf_to_data.transform_path(path)
  2100. else:
  2101. # For backwards compatibility we update the dataLim with the
  2102. # coordinate range of the given path, even though the coordinate
  2103. # systems are completely different. This may occur in situations
  2104. # such as when ax.transAxes is passed through for absolute
  2105. # positioning.
  2106. data_path = path
  2107. if not data_path.vertices.size:
  2108. return
  2109. updatex, updatey = line_trf.contains_branch_seperately(self.transData)
  2110. if self.name != "rectilinear":
  2111. # This block is mostly intended to handle axvline in polar plots,
  2112. # for which updatey would otherwise be True.
  2113. if updatex and line_trf == self.get_yaxis_transform():
  2114. updatex = False
  2115. if updatey and line_trf == self.get_xaxis_transform():
  2116. updatey = False
  2117. self.dataLim.update_from_path(data_path,
  2118. self.ignore_existing_data_limits,
  2119. updatex=updatex, updatey=updatey)
  2120. self.ignore_existing_data_limits = False
  2121. def add_patch(self, p):
  2122. """
  2123. Add a `.Patch` to the Axes; return the patch.
  2124. """
  2125. _api.check_isinstance(mpatches.Patch, p=p)
  2126. self._set_artist_props(p)
  2127. if p.get_clip_path() is None:
  2128. p.set_clip_path(self.patch)
  2129. self._update_patch_limits(p)
  2130. self._children.append(p)
  2131. p._remove_method = self._children.remove
  2132. return p
  2133. def _update_patch_limits(self, patch):
  2134. """Update the data limits for the given patch."""
  2135. # hist can add zero height Rectangles, which is useful to keep
  2136. # the bins, counts and patches lined up, but it throws off log
  2137. # scaling. We'll ignore rects with zero height or width in
  2138. # the auto-scaling
  2139. # cannot check for '==0' since unitized data may not compare to zero
  2140. # issue #2150 - we update the limits if patch has non zero width
  2141. # or height.
  2142. if (isinstance(patch, mpatches.Rectangle) and
  2143. ((not patch.get_width()) and (not patch.get_height()))):
  2144. return
  2145. p = patch.get_path()
  2146. # Get all vertices on the path
  2147. # Loop through each segment to get extrema for Bezier curve sections
  2148. vertices = []
  2149. for curve, code in p.iter_bezier(simplify=False):
  2150. # Get distance along the curve of any extrema
  2151. _, dzeros = curve.axis_aligned_extrema()
  2152. # Calculate vertices of start, end and any extrema in between
  2153. vertices.append(curve([0, *dzeros, 1]))
  2154. if len(vertices):
  2155. vertices = np.vstack(vertices)
  2156. patch_trf = patch.get_transform()
  2157. updatex, updatey = patch_trf.contains_branch_seperately(self.transData)
  2158. if not (updatex or updatey):
  2159. return
  2160. if self.name != "rectilinear":
  2161. # As in _update_line_limits, but for axvspan.
  2162. if updatex and patch_trf == self.get_yaxis_transform():
  2163. updatex = False
  2164. if updatey and patch_trf == self.get_xaxis_transform():
  2165. updatey = False
  2166. trf_to_data = patch_trf - self.transData
  2167. xys = trf_to_data.transform(vertices)
  2168. self.update_datalim(xys, updatex=updatex, updatey=updatey)
  2169. def add_table(self, tab):
  2170. """
  2171. Add a `.Table` to the Axes; return the table.
  2172. """
  2173. _api.check_isinstance(mtable.Table, tab=tab)
  2174. self._set_artist_props(tab)
  2175. self._children.append(tab)
  2176. if tab.get_clip_path() is None:
  2177. tab.set_clip_path(self.patch)
  2178. tab._remove_method = self._children.remove
  2179. return tab
  2180. def add_container(self, container):
  2181. """
  2182. Add a `.Container` to the Axes' containers; return the container.
  2183. """
  2184. label = container.get_label()
  2185. if not label:
  2186. container.set_label('_container%d' % len(self.containers))
  2187. self.containers.append(container)
  2188. container._remove_method = self.containers.remove
  2189. return container
  2190. def _unit_change_handler(self, axis_name, event=None):
  2191. """
  2192. Process axis units changes: requests updates to data and view limits.
  2193. """
  2194. if event is None: # Allow connecting `self._unit_change_handler(name)`
  2195. return functools.partial(
  2196. self._unit_change_handler, axis_name, event=object())
  2197. _api.check_in_list(self._axis_map, axis_name=axis_name)
  2198. for line in self.lines:
  2199. line.recache_always()
  2200. self.relim()
  2201. self._request_autoscale_view(axis_name)
  2202. def relim(self, visible_only=False):
  2203. """
  2204. Recompute the data limits based on current artists.
  2205. At present, `.Collection` instances are not supported.
  2206. Parameters
  2207. ----------
  2208. visible_only : bool, default: False
  2209. Whether to exclude invisible artists.
  2210. """
  2211. # Collections are deliberately not supported (yet); see
  2212. # the TODO note in artists.py.
  2213. self.dataLim.ignore(True)
  2214. self.dataLim.set_points(mtransforms.Bbox.null().get_points())
  2215. self.ignore_existing_data_limits = True
  2216. for artist in self._children:
  2217. if not visible_only or artist.get_visible():
  2218. if isinstance(artist, mlines.Line2D):
  2219. self._update_line_limits(artist)
  2220. elif isinstance(artist, mpatches.Patch):
  2221. self._update_patch_limits(artist)
  2222. elif isinstance(artist, mimage.AxesImage):
  2223. self._update_image_limits(artist)
  2224. def update_datalim(self, xys, updatex=True, updatey=True):
  2225. """
  2226. Extend the `~.Axes.dataLim` Bbox to include the given points.
  2227. If no data is set currently, the Bbox will ignore its limits and set
  2228. the bound to be the bounds of the xydata (*xys*). Otherwise, it will
  2229. compute the bounds of the union of its current data and the data in
  2230. *xys*.
  2231. Parameters
  2232. ----------
  2233. xys : 2D array-like
  2234. The points to include in the data limits Bbox. This can be either
  2235. a list of (x, y) tuples or a (N, 2) array.
  2236. updatex, updatey : bool, default: True
  2237. Whether to update the x/y limits.
  2238. """
  2239. xys = np.asarray(xys)
  2240. if not np.any(np.isfinite(xys)):
  2241. return
  2242. self.dataLim.update_from_data_xy(xys, self.ignore_existing_data_limits,
  2243. updatex=updatex, updatey=updatey)
  2244. self.ignore_existing_data_limits = False
  2245. def _process_unit_info(self, datasets=None, kwargs=None, *, convert=True):
  2246. """
  2247. Set axis units based on *datasets* and *kwargs*, and optionally apply
  2248. unit conversions to *datasets*.
  2249. Parameters
  2250. ----------
  2251. datasets : list
  2252. List of (axis_name, dataset) pairs (where the axis name is defined
  2253. as in `._axis_map`). Individual datasets can also be None
  2254. (which gets passed through).
  2255. kwargs : dict
  2256. Other parameters from which unit info (i.e., the *xunits*,
  2257. *yunits*, *zunits* (for 3D Axes), *runits* and *thetaunits* (for
  2258. polar) entries) is popped, if present. Note that this dict is
  2259. mutated in-place!
  2260. convert : bool, default: True
  2261. Whether to return the original datasets or the converted ones.
  2262. Returns
  2263. -------
  2264. list
  2265. Either the original datasets if *convert* is False, or the
  2266. converted ones if *convert* is True (the default).
  2267. """
  2268. # The API makes datasets a list of pairs rather than an axis_name to
  2269. # dataset mapping because it is sometimes necessary to process multiple
  2270. # datasets for a single axis, and concatenating them may be tricky
  2271. # (e.g. if some are scalars, etc.).
  2272. datasets = datasets or []
  2273. kwargs = kwargs or {}
  2274. axis_map = self._axis_map
  2275. for axis_name, data in datasets:
  2276. try:
  2277. axis = axis_map[axis_name]
  2278. except KeyError:
  2279. raise ValueError(f"Invalid axis name: {axis_name!r}") from None
  2280. # Update from data if axis is already set but no unit is set yet.
  2281. if axis is not None and data is not None and not axis.have_units():
  2282. axis.update_units(data)
  2283. for axis_name, axis in axis_map.items():
  2284. # Return if no axis is set.
  2285. if axis is None:
  2286. continue
  2287. # Check for units in the kwargs, and if present update axis.
  2288. units = kwargs.pop(f"{axis_name}units", axis.units)
  2289. if self.name == "polar":
  2290. # Special case: polar supports "thetaunits"/"runits".
  2291. polar_units = {"x": "thetaunits", "y": "runits"}
  2292. units = kwargs.pop(polar_units[axis_name], units)
  2293. if units != axis.units and units is not None:
  2294. axis.set_units(units)
  2295. # If the units being set imply a different converter,
  2296. # we need to update again.
  2297. for dataset_axis_name, data in datasets:
  2298. if dataset_axis_name == axis_name and data is not None:
  2299. axis.update_units(data)
  2300. return [axis_map[axis_name].convert_units(data)
  2301. if convert and data is not None else data
  2302. for axis_name, data in datasets]
  2303. def in_axes(self, mouseevent):
  2304. """
  2305. Return whether the given event (in display coords) is in the Axes.
  2306. """
  2307. return self.patch.contains(mouseevent)[0]
  2308. get_autoscalex_on = _axis_method_wrapper("xaxis", "_get_autoscale_on")
  2309. get_autoscaley_on = _axis_method_wrapper("yaxis", "_get_autoscale_on")
  2310. set_autoscalex_on = _axis_method_wrapper("xaxis", "_set_autoscale_on")
  2311. set_autoscaley_on = _axis_method_wrapper("yaxis", "_set_autoscale_on")
  2312. def get_autoscale_on(self):
  2313. """Return True if each axis is autoscaled, False otherwise."""
  2314. return all(axis._get_autoscale_on()
  2315. for axis in self._axis_map.values())
  2316. def set_autoscale_on(self, b):
  2317. """
  2318. Set whether autoscaling is applied to each axis on the next draw or
  2319. call to `.Axes.autoscale_view`.
  2320. Parameters
  2321. ----------
  2322. b : bool
  2323. """
  2324. for axis in self._axis_map.values():
  2325. axis._set_autoscale_on(b)
  2326. @property
  2327. def use_sticky_edges(self):
  2328. """
  2329. When autoscaling, whether to obey all `.Artist.sticky_edges`.
  2330. Default is ``True``.
  2331. Setting this to ``False`` ensures that the specified margins
  2332. will be applied, even if the plot includes an image, for
  2333. example, which would otherwise force a view limit to coincide
  2334. with its data limit.
  2335. The changing this property does not change the plot until
  2336. `autoscale` or `autoscale_view` is called.
  2337. """
  2338. return self._use_sticky_edges
  2339. @use_sticky_edges.setter
  2340. def use_sticky_edges(self, b):
  2341. self._use_sticky_edges = bool(b)
  2342. # No effect until next autoscaling, which will mark the Axes as stale.
  2343. def get_xmargin(self):
  2344. """
  2345. Retrieve autoscaling margin of the x-axis.
  2346. .. versionadded:: 3.9
  2347. Returns
  2348. -------
  2349. xmargin : float
  2350. See Also
  2351. --------
  2352. matplotlib.axes.Axes.set_xmargin
  2353. """
  2354. return self._xmargin
  2355. def get_ymargin(self):
  2356. """
  2357. Retrieve autoscaling margin of the y-axis.
  2358. .. versionadded:: 3.9
  2359. Returns
  2360. -------
  2361. ymargin : float
  2362. See Also
  2363. --------
  2364. matplotlib.axes.Axes.set_ymargin
  2365. """
  2366. return self._ymargin
  2367. def set_xmargin(self, m):
  2368. """
  2369. Set padding of X data limits prior to autoscaling.
  2370. *m* times the data interval will be added to each end of that interval
  2371. before it is used in autoscaling. If *m* is negative, this will clip
  2372. the data range instead of expanding it.
  2373. For example, if your data is in the range [0, 2], a margin of 0.1 will
  2374. result in a range [-0.2, 2.2]; a margin of -0.1 will result in a range
  2375. of [0.2, 1.8].
  2376. Parameters
  2377. ----------
  2378. m : float greater than -0.5
  2379. """
  2380. if m <= -0.5:
  2381. raise ValueError("margin must be greater than -0.5")
  2382. self._xmargin = m
  2383. self._request_autoscale_view("x")
  2384. self.stale = True
  2385. def set_ymargin(self, m):
  2386. """
  2387. Set padding of Y data limits prior to autoscaling.
  2388. *m* times the data interval will be added to each end of that interval
  2389. before it is used in autoscaling. If *m* is negative, this will clip
  2390. the data range instead of expanding it.
  2391. For example, if your data is in the range [0, 2], a margin of 0.1 will
  2392. result in a range [-0.2, 2.2]; a margin of -0.1 will result in a range
  2393. of [0.2, 1.8].
  2394. Parameters
  2395. ----------
  2396. m : float greater than -0.5
  2397. """
  2398. if m <= -0.5:
  2399. raise ValueError("margin must be greater than -0.5")
  2400. self._ymargin = m
  2401. self._request_autoscale_view("y")
  2402. self.stale = True
  2403. def margins(self, *margins, x=None, y=None, tight=True):
  2404. """
  2405. Set or retrieve margins around the data for autoscaling axis limits.
  2406. This allows to configure the padding around the data without having to
  2407. set explicit limits using `~.Axes.set_xlim` / `~.Axes.set_ylim`.
  2408. Autoscaling determines the axis limits by adding *margin* times the
  2409. data interval as padding around the data. See the following illustration:
  2410. .. plot:: _embedded_plots/axes_margins.py
  2411. All input parameters must be floats greater than -0.5. Passing both
  2412. positional and keyword arguments is invalid and will raise a TypeError.
  2413. If no arguments (positional or otherwise) are provided, the current
  2414. margins will remain unchanged and simply be returned.
  2415. The default margins are :rc:`axes.xmargin` and :rc:`axes.ymargin`.
  2416. Parameters
  2417. ----------
  2418. *margins : float, optional
  2419. If a single positional argument is provided, it specifies
  2420. both margins of the x-axis and y-axis limits. If two
  2421. positional arguments are provided, they will be interpreted
  2422. as *xmargin*, *ymargin*. If setting the margin on a single
  2423. axis is desired, use the keyword arguments described below.
  2424. x, y : float, optional
  2425. Specific margin values for the x-axis and y-axis,
  2426. respectively. These cannot be used with positional
  2427. arguments, but can be used individually to alter on e.g.,
  2428. only the y-axis.
  2429. tight : bool or None, default: True
  2430. The *tight* parameter is passed to `~.axes.Axes.autoscale_view`,
  2431. which is executed after a margin is changed; the default
  2432. here is *True*, on the assumption that when margins are
  2433. specified, no additional padding to match tick marks is
  2434. usually desired. Setting *tight* to *None* preserves
  2435. the previous setting.
  2436. Returns
  2437. -------
  2438. xmargin, ymargin : float
  2439. Notes
  2440. -----
  2441. If a previously used Axes method such as :meth:`pcolor` has set
  2442. `~.Axes.use_sticky_edges` to `True`, only the limits not set by
  2443. the "sticky artists" will be modified. To force all
  2444. margins to be set, set `~.Axes.use_sticky_edges` to `False`
  2445. before calling :meth:`margins`.
  2446. See Also
  2447. --------
  2448. .Axes.set_xmargin, .Axes.set_ymargin
  2449. """
  2450. if margins and (x is not None or y is not None):
  2451. raise TypeError('Cannot pass both positional and keyword '
  2452. 'arguments for x and/or y.')
  2453. elif len(margins) == 1:
  2454. x = y = margins[0]
  2455. elif len(margins) == 2:
  2456. x, y = margins
  2457. elif margins:
  2458. raise TypeError('Must pass a single positional argument for all '
  2459. 'margins, or one for each margin (x, y).')
  2460. if x is None and y is None:
  2461. if tight is not True:
  2462. _api.warn_external(f'ignoring tight={tight!r} in get mode')
  2463. return self._xmargin, self._ymargin
  2464. if tight is not None:
  2465. self._tight = tight
  2466. if x is not None:
  2467. self.set_xmargin(x)
  2468. if y is not None:
  2469. self.set_ymargin(y)
  2470. def set_rasterization_zorder(self, z):
  2471. """
  2472. Set the zorder threshold for rasterization for vector graphics output.
  2473. All artists with a zorder below the given value will be rasterized if
  2474. they support rasterization.
  2475. This setting is ignored for pixel-based output.
  2476. See also :doc:`/gallery/misc/rasterization_demo`.
  2477. Parameters
  2478. ----------
  2479. z : float or None
  2480. The zorder below which artists are rasterized.
  2481. If ``None`` rasterization based on zorder is deactivated.
  2482. """
  2483. self._rasterization_zorder = z
  2484. self.stale = True
  2485. def get_rasterization_zorder(self):
  2486. """Return the zorder value below which artists will be rasterized."""
  2487. return self._rasterization_zorder
  2488. def autoscale(self, enable=True, axis='both', tight=None):
  2489. """
  2490. Autoscale the axis view to the data (toggle).
  2491. Convenience method for simple axis view autoscaling.
  2492. It turns autoscaling on or off, and then,
  2493. if autoscaling for either axis is on, it performs
  2494. the autoscaling on the specified axis or Axes.
  2495. Parameters
  2496. ----------
  2497. enable : bool or None, default: True
  2498. True turns autoscaling on, False turns it off.
  2499. None leaves the autoscaling state unchanged.
  2500. axis : {'both', 'x', 'y'}, default: 'both'
  2501. The axis on which to operate. (For 3D Axes, *axis* can also be set
  2502. to 'z', and 'both' refers to all three Axes.)
  2503. tight : bool or None, default: None
  2504. If True, first set the margins to zero. Then, this argument is
  2505. forwarded to `~.axes.Axes.autoscale_view` (regardless of
  2506. its value); see the description of its behavior there.
  2507. """
  2508. if enable is None:
  2509. scalex = True
  2510. scaley = True
  2511. else:
  2512. if axis in ['x', 'both']:
  2513. self.set_autoscalex_on(bool(enable))
  2514. scalex = self.get_autoscalex_on()
  2515. else:
  2516. scalex = False
  2517. if axis in ['y', 'both']:
  2518. self.set_autoscaley_on(bool(enable))
  2519. scaley = self.get_autoscaley_on()
  2520. else:
  2521. scaley = False
  2522. if tight and scalex:
  2523. self._xmargin = 0
  2524. if tight and scaley:
  2525. self._ymargin = 0
  2526. if scalex:
  2527. self._request_autoscale_view("x", tight=tight)
  2528. if scaley:
  2529. self._request_autoscale_view("y", tight=tight)
  2530. def autoscale_view(self, tight=None, scalex=True, scaley=True):
  2531. """
  2532. Autoscale the view limits using the data limits.
  2533. Parameters
  2534. ----------
  2535. tight : bool or None
  2536. If *True*, only expand the axis limits using the margins. Note
  2537. that unlike for `autoscale`, ``tight=True`` does *not* set the
  2538. margins to zero.
  2539. If *False* and :rc:`axes.autolimit_mode` is 'round_numbers', then
  2540. after expansion by the margins, further expand the axis limits
  2541. using the axis major locator.
  2542. If None (the default), reuse the value set in the previous call to
  2543. `autoscale_view` (the initial value is False, but the default style
  2544. sets :rc:`axes.autolimit_mode` to 'data', in which case this
  2545. behaves like True).
  2546. scalex : bool, default: True
  2547. Whether to autoscale the x-axis.
  2548. scaley : bool, default: True
  2549. Whether to autoscale the y-axis.
  2550. Notes
  2551. -----
  2552. The autoscaling preserves any preexisting axis direction reversal.
  2553. The data limits are not updated automatically when artist data are
  2554. changed after the artist has been added to an Axes instance. In that
  2555. case, use :meth:`matplotlib.axes.Axes.relim` prior to calling
  2556. autoscale_view.
  2557. If the views of the Axes are fixed, e.g. via `set_xlim`, they will
  2558. not be changed by autoscale_view().
  2559. See :meth:`matplotlib.axes.Axes.autoscale` for an alternative.
  2560. """
  2561. if tight is not None:
  2562. self._tight = bool(tight)
  2563. x_stickies = y_stickies = np.array([])
  2564. if self.use_sticky_edges:
  2565. if self._xmargin and scalex and self.get_autoscalex_on():
  2566. x_stickies = np.sort(np.concatenate([
  2567. artist.sticky_edges.x
  2568. for ax in self._shared_axes["x"].get_siblings(self)
  2569. for artist in ax.get_children()]))
  2570. if self._ymargin and scaley and self.get_autoscaley_on():
  2571. y_stickies = np.sort(np.concatenate([
  2572. artist.sticky_edges.y
  2573. for ax in self._shared_axes["y"].get_siblings(self)
  2574. for artist in ax.get_children()]))
  2575. if self.get_xscale() == 'log':
  2576. x_stickies = x_stickies[x_stickies > 0]
  2577. if self.get_yscale() == 'log':
  2578. y_stickies = y_stickies[y_stickies > 0]
  2579. def handle_single_axis(
  2580. scale, shared_axes, name, axis, margin, stickies, set_bound):
  2581. if not (scale and axis._get_autoscale_on()):
  2582. return # nothing to do...
  2583. shared = shared_axes.get_siblings(self)
  2584. # Base autoscaling on finite data limits when there is at least one
  2585. # finite data limit among all the shared_axes and intervals.
  2586. values = [val for ax in shared
  2587. for val in getattr(ax.dataLim, f"interval{name}")
  2588. if np.isfinite(val)]
  2589. if values:
  2590. x0, x1 = (min(values), max(values))
  2591. elif getattr(self._viewLim, f"mutated{name}")():
  2592. # No data, but explicit viewLims already set:
  2593. # in mutatedx or mutatedy.
  2594. return
  2595. else:
  2596. x0, x1 = (-np.inf, np.inf)
  2597. # If x0 and x1 are nonfinite, get default limits from the locator.
  2598. locator = axis.get_major_locator()
  2599. x0, x1 = locator.nonsingular(x0, x1)
  2600. # Find the minimum minpos for use in the margin calculation.
  2601. minimum_minpos = min(
  2602. getattr(ax.dataLim, f"minpos{name}") for ax in shared)
  2603. # Prevent margin addition from crossing a sticky value. A small
  2604. # tolerance must be added due to floating point issues with
  2605. # streamplot; it is defined relative to x1-x0 but has
  2606. # no absolute term (e.g. "+1e-8") to avoid issues when working with
  2607. # datasets where all values are tiny (less than 1e-8).
  2608. tol = 1e-5 * abs(x1 - x0)
  2609. # Index of largest element < x0 + tol, if any.
  2610. i0 = stickies.searchsorted(x0 + tol) - 1
  2611. x0bound = stickies[i0] if i0 != -1 else None
  2612. # Index of smallest element > x1 - tol, if any.
  2613. i1 = stickies.searchsorted(x1 - tol)
  2614. x1bound = stickies[i1] if i1 != len(stickies) else None
  2615. # Add the margin in figure space and then transform back, to handle
  2616. # non-linear scales.
  2617. transform = axis.get_transform()
  2618. inverse_trans = transform.inverted()
  2619. x0, x1 = axis._scale.limit_range_for_scale(x0, x1, minimum_minpos)
  2620. x0t, x1t = transform.transform([x0, x1])
  2621. delta = (x1t - x0t) * margin
  2622. if not np.isfinite(delta):
  2623. delta = 0 # If a bound isn't finite, set margin to zero.
  2624. x0, x1 = inverse_trans.transform([x0t - delta, x1t + delta])
  2625. # Apply sticky bounds.
  2626. if x0bound is not None:
  2627. x0 = max(x0, x0bound)
  2628. if x1bound is not None:
  2629. x1 = min(x1, x1bound)
  2630. if not self._tight:
  2631. x0, x1 = locator.view_limits(x0, x1)
  2632. set_bound(x0, x1)
  2633. # End of definition of internal function 'handle_single_axis'.
  2634. handle_single_axis(
  2635. scalex, self._shared_axes["x"], 'x', self.xaxis, self._xmargin,
  2636. x_stickies, self.set_xbound)
  2637. handle_single_axis(
  2638. scaley, self._shared_axes["y"], 'y', self.yaxis, self._ymargin,
  2639. y_stickies, self.set_ybound)
  2640. def _update_title_position(self, renderer):
  2641. """
  2642. Update the title position based on the bounding box enclosing
  2643. all the ticklabels and x-axis spine and xlabel...
  2644. """
  2645. if self._autotitlepos is not None and not self._autotitlepos:
  2646. _log.debug('title position was updated manually, not adjusting')
  2647. return
  2648. titles = (self.title, self._left_title, self._right_title)
  2649. if not any(title.get_text() for title in titles):
  2650. # If the titles are all empty, there is no need to update their positions.
  2651. return
  2652. # Need to check all our twins too, aligned axes, and all the children
  2653. # as well.
  2654. axs = set()
  2655. axs.update(self.child_axes)
  2656. axs.update(self._twinned_axes.get_siblings(self))
  2657. axs.update(
  2658. self.get_figure(root=False)._align_label_groups['title'].get_siblings(self))
  2659. for ax in self.child_axes: # Child positions must be updated first.
  2660. locator = ax.get_axes_locator()
  2661. ax.apply_aspect(locator(self, renderer) if locator else None)
  2662. top = -np.inf
  2663. for ax in axs:
  2664. bb = None
  2665. if (ax.xaxis.get_ticks_position() in ['top', 'unknown'] or
  2666. ax.xaxis.get_label_position() == 'top'):
  2667. bb = ax.xaxis.get_tightbbox(renderer)
  2668. if bb is None:
  2669. # Extent of the outline for colorbars, of the axes otherwise.
  2670. bb = ax.spines.get("outline", ax).get_window_extent()
  2671. top = max(top, bb.ymax)
  2672. for title in titles:
  2673. x, _ = title.get_position()
  2674. # need to start again in case of window resizing
  2675. title.set_position((x, 1.0))
  2676. if title.get_text():
  2677. for ax in axs:
  2678. ax.yaxis.get_tightbbox(renderer) # update offsetText
  2679. if ax.yaxis.offsetText.get_text():
  2680. bb = ax.yaxis.offsetText.get_tightbbox(renderer)
  2681. if bb.intersection(title.get_tightbbox(renderer), bb):
  2682. top = bb.ymax
  2683. if top < 0:
  2684. # the top of Axes is not even on the figure, so don't try and
  2685. # automatically place it.
  2686. _log.debug('top of Axes not in the figure, so title not moved')
  2687. return
  2688. if title.get_window_extent(renderer).ymin < top:
  2689. _, y = self.transAxes.inverted().transform((0, top))
  2690. title.set_position((x, y))
  2691. # empirically, this doesn't always get the min to top,
  2692. # so we need to adjust again.
  2693. if title.get_window_extent(renderer).ymin < top:
  2694. _, y = self.transAxes.inverted().transform(
  2695. (0., 2 * top - title.get_window_extent(renderer).ymin))
  2696. title.set_position((x, y))
  2697. ymax = max(title.get_position()[1] for title in titles)
  2698. for title in titles:
  2699. # now line up all the titles at the highest baseline.
  2700. x, _ = title.get_position()
  2701. title.set_position((x, ymax))
  2702. # Drawing
  2703. @martist.allow_rasterization
  2704. def draw(self, renderer):
  2705. # docstring inherited
  2706. if renderer is None:
  2707. raise RuntimeError('No renderer defined')
  2708. if not self.get_visible():
  2709. return
  2710. self._unstale_viewLim()
  2711. renderer.open_group('axes', gid=self.get_gid())
  2712. # prevent triggering call backs during the draw process
  2713. self._stale = True
  2714. # loop over self and child Axes...
  2715. locator = self.get_axes_locator()
  2716. self.apply_aspect(locator(self, renderer) if locator else None)
  2717. artists = self.get_children()
  2718. artists.remove(self.patch)
  2719. # the frame draws the edges around the Axes patch -- we
  2720. # decouple these so the patch can be in the background and the
  2721. # frame in the foreground. Do this before drawing the axis
  2722. # objects so that the spine has the opportunity to update them.
  2723. if not (self.axison and self._frameon):
  2724. for spine in self.spines.values():
  2725. artists.remove(spine)
  2726. self._update_title_position(renderer)
  2727. if not self.axison:
  2728. for _axis in self._axis_map.values():
  2729. artists.remove(_axis)
  2730. if not self.get_figure(root=True).canvas.is_saving():
  2731. artists = [
  2732. a for a in artists
  2733. if not a.get_animated() or isinstance(a, mimage.AxesImage)]
  2734. artists = sorted(artists, key=attrgetter('zorder'))
  2735. # rasterize artists with negative zorder
  2736. # if the minimum zorder is negative, start rasterization
  2737. rasterization_zorder = self._rasterization_zorder
  2738. if (rasterization_zorder is not None and
  2739. artists and artists[0].zorder < rasterization_zorder):
  2740. split_index = np.searchsorted(
  2741. [art.zorder for art in artists],
  2742. rasterization_zorder, side='right'
  2743. )
  2744. artists_rasterized = artists[:split_index]
  2745. artists = artists[split_index:]
  2746. else:
  2747. artists_rasterized = []
  2748. if self.axison and self._frameon:
  2749. if artists_rasterized:
  2750. artists_rasterized = [self.patch] + artists_rasterized
  2751. else:
  2752. artists = [self.patch] + artists
  2753. if artists_rasterized:
  2754. _draw_rasterized(self.get_figure(root=True), artists_rasterized, renderer)
  2755. mimage._draw_list_compositing_images(
  2756. renderer, self, artists, self.get_figure(root=True).suppressComposite)
  2757. renderer.close_group('axes')
  2758. self.stale = False
  2759. def draw_artist(self, a):
  2760. """
  2761. Efficiently redraw a single artist.
  2762. """
  2763. a.draw(self.get_figure(root=True).canvas.get_renderer())
  2764. def redraw_in_frame(self):
  2765. """
  2766. Efficiently redraw Axes data, but not axis ticks, labels, etc.
  2767. """
  2768. with ExitStack() as stack:
  2769. for artist in [*self._axis_map.values(),
  2770. self.title, self._left_title, self._right_title]:
  2771. stack.enter_context(artist._cm_set(visible=False))
  2772. self.draw(self.get_figure(root=True).canvas.get_renderer())
  2773. # Axes rectangle characteristics
  2774. def get_frame_on(self):
  2775. """Get whether the Axes rectangle patch is drawn."""
  2776. return self._frameon
  2777. def set_frame_on(self, b):
  2778. """
  2779. Set whether the Axes rectangle patch is drawn.
  2780. Parameters
  2781. ----------
  2782. b : bool
  2783. """
  2784. self._frameon = b
  2785. self.stale = True
  2786. def get_axisbelow(self):
  2787. """
  2788. Get whether axis ticks and gridlines are above or below most artists.
  2789. Returns
  2790. -------
  2791. bool or 'line'
  2792. See Also
  2793. --------
  2794. set_axisbelow
  2795. """
  2796. return self._axisbelow
  2797. def set_axisbelow(self, b):
  2798. """
  2799. Set whether axis ticks and gridlines are above or below most artists.
  2800. This controls the zorder of the ticks and gridlines. For more
  2801. information on the zorder see :doc:`/gallery/misc/zorder_demo`.
  2802. Parameters
  2803. ----------
  2804. b : bool or 'line'
  2805. Possible values:
  2806. - *True* (zorder = 0.5): Ticks and gridlines are below patches and
  2807. lines, though still above images.
  2808. - 'line' (zorder = 1.5): Ticks and gridlines are above patches
  2809. (e.g. rectangles, with default zorder = 1) but still below lines
  2810. and markers (with their default zorder = 2).
  2811. - *False* (zorder = 2.5): Ticks and gridlines are above patches
  2812. and lines / markers.
  2813. Notes
  2814. -----
  2815. For more control, call the `~.Artist.set_zorder` method of each axis.
  2816. See Also
  2817. --------
  2818. get_axisbelow
  2819. """
  2820. # Check that b is True, False or 'line'
  2821. self._axisbelow = axisbelow = validate_axisbelow(b)
  2822. zorder = {
  2823. True: 0.5,
  2824. 'line': 1.5,
  2825. False: 2.5,
  2826. }[axisbelow]
  2827. for axis in self._axis_map.values():
  2828. axis.set_zorder(zorder)
  2829. self.stale = True
  2830. @_docstring.interpd
  2831. def grid(self, visible=None, which='major', axis='both', **kwargs):
  2832. """
  2833. Configure the grid lines.
  2834. Parameters
  2835. ----------
  2836. visible : bool or None, optional
  2837. Whether to show the grid lines. If any *kwargs* are supplied, it
  2838. is assumed you want the grid on and *visible* will be set to True.
  2839. If *visible* is *None* and there are no *kwargs*, this toggles the
  2840. visibility of the lines.
  2841. which : {'major', 'minor', 'both'}, optional
  2842. The grid lines to apply the changes on.
  2843. axis : {'both', 'x', 'y'}, optional
  2844. The axis to apply the changes on.
  2845. **kwargs : `~matplotlib.lines.Line2D` properties
  2846. Define the line properties of the grid, e.g.::
  2847. grid(color='r', linestyle='-', linewidth=2)
  2848. Valid keyword arguments are:
  2849. %(Line2D:kwdoc)s
  2850. Notes
  2851. -----
  2852. The axis is drawn as a unit, so the effective zorder for drawing the
  2853. grid is determined by the zorder of each axis, not by the zorder of the
  2854. `.Line2D` objects comprising the grid. Therefore, to set grid zorder,
  2855. use `.set_axisbelow` or, for more control, call the
  2856. `~.Artist.set_zorder` method of each axis.
  2857. """
  2858. _api.check_in_list(['x', 'y', 'both'], axis=axis)
  2859. if axis in ['x', 'both']:
  2860. self.xaxis.grid(visible, which=which, **kwargs)
  2861. if axis in ['y', 'both']:
  2862. self.yaxis.grid(visible, which=which, **kwargs)
  2863. def ticklabel_format(self, *, axis='both', style=None, scilimits=None,
  2864. useOffset=None, useLocale=None, useMathText=None):
  2865. r"""
  2866. Configure the `.ScalarFormatter` used by default for linear Axes.
  2867. If a parameter is not set, the corresponding property of the formatter
  2868. is left unchanged.
  2869. Parameters
  2870. ----------
  2871. axis : {'x', 'y', 'both'}, default: 'both'
  2872. The axis to configure. Only major ticks are affected.
  2873. style : {'sci', 'scientific', 'plain'}
  2874. Whether to use scientific notation.
  2875. The formatter default is to use scientific notation.
  2876. 'sci' is equivalent to 'scientific'.
  2877. scilimits : pair of ints (m, n)
  2878. Scientific notation is used only for numbers outside the range
  2879. 10\ :sup:`m` to 10\ :sup:`n` (and only if the formatter is
  2880. configured to use scientific notation at all). Use (0, 0) to
  2881. include all numbers. Use (m, m) where m != 0 to fix the order of
  2882. magnitude to 10\ :sup:`m`.
  2883. The formatter default is :rc:`axes.formatter.limits`.
  2884. useOffset : bool or float
  2885. If True, the offset is calculated as needed.
  2886. If False, no offset is used.
  2887. If a numeric value, it sets the offset.
  2888. The formatter default is :rc:`axes.formatter.useoffset`.
  2889. useLocale : bool
  2890. Whether to format the number using the current locale or using the
  2891. C (English) locale. This affects e.g. the decimal separator. The
  2892. formatter default is :rc:`axes.formatter.use_locale`.
  2893. useMathText : bool
  2894. Render the offset and scientific notation in mathtext.
  2895. The formatter default is :rc:`axes.formatter.use_mathtext`.
  2896. Raises
  2897. ------
  2898. AttributeError
  2899. If the current formatter is not a `.ScalarFormatter`.
  2900. """
  2901. if isinstance(style, str):
  2902. style = style.lower()
  2903. axis = axis.lower()
  2904. if scilimits is not None:
  2905. try:
  2906. m, n = scilimits
  2907. m + n + 1 # check that both are numbers
  2908. except (ValueError, TypeError) as err:
  2909. raise ValueError("scilimits must be a sequence of 2 integers"
  2910. ) from err
  2911. STYLES = {'sci': True, 'scientific': True, 'plain': False, '': None, None: None}
  2912. # The '' option is included for backwards-compatibility.
  2913. is_sci_style = _api.check_getitem(STYLES, style=style)
  2914. axis_map = {**{k: [v] for k, v in self._axis_map.items()},
  2915. 'both': list(self._axis_map.values())}
  2916. axises = _api.check_getitem(axis_map, axis=axis)
  2917. try:
  2918. for axis in axises:
  2919. if is_sci_style is not None:
  2920. axis.major.formatter.set_scientific(is_sci_style)
  2921. if scilimits is not None:
  2922. axis.major.formatter.set_powerlimits(scilimits)
  2923. if useOffset is not None:
  2924. axis.major.formatter.set_useOffset(useOffset)
  2925. if useLocale is not None:
  2926. axis.major.formatter.set_useLocale(useLocale)
  2927. if useMathText is not None:
  2928. axis.major.formatter.set_useMathText(useMathText)
  2929. except AttributeError as err:
  2930. raise AttributeError(
  2931. "This method only works with the ScalarFormatter") from err
  2932. def locator_params(self, axis='both', tight=None, **kwargs):
  2933. """
  2934. Control behavior of major tick locators.
  2935. Because the locator is involved in autoscaling, `~.Axes.autoscale_view`
  2936. is called automatically after the parameters are changed.
  2937. Parameters
  2938. ----------
  2939. axis : {'both', 'x', 'y'}, default: 'both'
  2940. The axis on which to operate. (For 3D Axes, *axis* can also be
  2941. set to 'z', and 'both' refers to all three axes.)
  2942. tight : bool or None, optional
  2943. Parameter passed to `~.Axes.autoscale_view`.
  2944. Default is None, for no change.
  2945. Other Parameters
  2946. ----------------
  2947. **kwargs
  2948. Remaining keyword arguments are passed to directly to the
  2949. ``set_params()`` method of the locator. Supported keywords depend
  2950. on the type of the locator. See for example
  2951. `~.ticker.MaxNLocator.set_params` for the `.ticker.MaxNLocator`
  2952. used by default for linear.
  2953. Examples
  2954. --------
  2955. When plotting small subplots, one might want to reduce the maximum
  2956. number of ticks and use tight bounds, for example::
  2957. ax.locator_params(tight=True, nbins=4)
  2958. """
  2959. _api.check_in_list([*self._axis_names, "both"], axis=axis)
  2960. for name in self._axis_names:
  2961. if axis in [name, "both"]:
  2962. loc = self._axis_map[name].get_major_locator()
  2963. loc.set_params(**kwargs)
  2964. self._request_autoscale_view(name, tight=tight)
  2965. self.stale = True
  2966. def tick_params(self, axis='both', **kwargs):
  2967. """
  2968. Change the appearance of ticks, tick labels, and gridlines.
  2969. Tick properties that are not explicitly set using the keyword
  2970. arguments remain unchanged unless *reset* is True. For the current
  2971. style settings, see `.Axis.get_tick_params`.
  2972. Parameters
  2973. ----------
  2974. axis : {'x', 'y', 'both'}, default: 'both'
  2975. The axis to which the parameters are applied.
  2976. which : {'major', 'minor', 'both'}, default: 'major'
  2977. The group of ticks to which the parameters are applied.
  2978. reset : bool, default: False
  2979. Whether to reset the ticks to defaults before updating them.
  2980. Other Parameters
  2981. ----------------
  2982. direction : {'in', 'out', 'inout'}
  2983. Puts ticks inside the Axes, outside the Axes, or both.
  2984. length : float
  2985. Tick length in points.
  2986. width : float
  2987. Tick width in points.
  2988. color : :mpltype:`color`
  2989. Tick color.
  2990. pad : float
  2991. Distance in points between tick and label.
  2992. labelsize : float or str
  2993. Tick label font size in points or as a string (e.g., 'large').
  2994. labelcolor : :mpltype:`color`
  2995. Tick label color.
  2996. labelfontfamily : str
  2997. Tick label font.
  2998. colors : :mpltype:`color`
  2999. Tick color and label color.
  3000. zorder : float
  3001. Tick and label zorder.
  3002. bottom, top, left, right : bool
  3003. Whether to draw the respective ticks.
  3004. labelbottom, labeltop, labelleft, labelright : bool
  3005. Whether to draw the respective tick labels.
  3006. labelrotation : float
  3007. Tick label rotation
  3008. grid_color : :mpltype:`color`
  3009. Gridline color.
  3010. grid_alpha : float
  3011. Transparency of gridlines: 0 (transparent) to 1 (opaque).
  3012. grid_linewidth : float
  3013. Width of gridlines in points.
  3014. grid_linestyle : str
  3015. Any valid `.Line2D` line style spec.
  3016. Examples
  3017. --------
  3018. ::
  3019. ax.tick_params(direction='out', length=6, width=2, colors='r',
  3020. grid_color='r', grid_alpha=0.5)
  3021. This will make all major ticks be red, pointing out of the box,
  3022. and with dimensions 6 points by 2 points. Tick labels will
  3023. also be red. Gridlines will be red and translucent.
  3024. """
  3025. _api.check_in_list(['x', 'y', 'both'], axis=axis)
  3026. if axis in ['x', 'both']:
  3027. xkw = dict(kwargs)
  3028. xkw.pop('left', None)
  3029. xkw.pop('right', None)
  3030. xkw.pop('labelleft', None)
  3031. xkw.pop('labelright', None)
  3032. self.xaxis.set_tick_params(**xkw)
  3033. if axis in ['y', 'both']:
  3034. ykw = dict(kwargs)
  3035. ykw.pop('top', None)
  3036. ykw.pop('bottom', None)
  3037. ykw.pop('labeltop', None)
  3038. ykw.pop('labelbottom', None)
  3039. self.yaxis.set_tick_params(**ykw)
  3040. def set_axis_off(self):
  3041. """
  3042. Hide all visual components of the x- and y-axis.
  3043. This sets a flag to suppress drawing of all axis decorations, i.e.
  3044. axis labels, axis spines, and the axis tick component (tick markers,
  3045. tick labels, and grid lines). Individual visibility settings of these
  3046. components are ignored as long as `set_axis_off()` is in effect.
  3047. """
  3048. self.axison = False
  3049. self.stale = True
  3050. def set_axis_on(self):
  3051. """
  3052. Do not hide all visual components of the x- and y-axis.
  3053. This reverts the effect of a prior `.set_axis_off()` call. Whether the
  3054. individual axis decorations are drawn is controlled by their respective
  3055. visibility settings.
  3056. This is on by default.
  3057. """
  3058. self.axison = True
  3059. self.stale = True
  3060. # data limits, ticks, tick labels, and formatting
  3061. def get_xlabel(self):
  3062. """
  3063. Get the xlabel text string.
  3064. """
  3065. label = self.xaxis.label
  3066. return label.get_text()
  3067. def set_xlabel(self, xlabel, fontdict=None, labelpad=None, *,
  3068. loc=None, **kwargs):
  3069. """
  3070. Set the label for the x-axis.
  3071. Parameters
  3072. ----------
  3073. xlabel : str
  3074. The label text.
  3075. labelpad : float, default: :rc:`axes.labelpad`
  3076. Spacing in points from the Axes bounding box including ticks
  3077. and tick labels. If None, the previous value is left as is.
  3078. loc : {'left', 'center', 'right'}, default: :rc:`xaxis.labellocation`
  3079. The label position. This is a high-level alternative for passing
  3080. parameters *x* and *horizontalalignment*.
  3081. Other Parameters
  3082. ----------------
  3083. **kwargs : `~matplotlib.text.Text` properties
  3084. `.Text` properties control the appearance of the label.
  3085. See Also
  3086. --------
  3087. text : Documents the properties supported by `.Text`.
  3088. """
  3089. if labelpad is not None:
  3090. self.xaxis.labelpad = labelpad
  3091. protected_kw = ['x', 'horizontalalignment', 'ha']
  3092. if {*kwargs} & {*protected_kw}:
  3093. if loc is not None:
  3094. raise TypeError(f"Specifying 'loc' is disallowed when any of "
  3095. f"its corresponding low level keyword "
  3096. f"arguments ({protected_kw}) are also "
  3097. f"supplied")
  3098. else:
  3099. loc = (loc if loc is not None
  3100. else mpl.rcParams['xaxis.labellocation'])
  3101. _api.check_in_list(('left', 'center', 'right'), loc=loc)
  3102. x = {
  3103. 'left': 0,
  3104. 'center': 0.5,
  3105. 'right': 1,
  3106. }[loc]
  3107. kwargs.update(x=x, horizontalalignment=loc)
  3108. return self.xaxis.set_label_text(xlabel, fontdict, **kwargs)
  3109. def invert_xaxis(self):
  3110. """
  3111. Invert the x-axis.
  3112. See Also
  3113. --------
  3114. xaxis_inverted
  3115. get_xlim, set_xlim
  3116. get_xbound, set_xbound
  3117. """
  3118. self.xaxis.set_inverted(not self.xaxis.get_inverted())
  3119. xaxis_inverted = _axis_method_wrapper("xaxis", "get_inverted")
  3120. def get_xbound(self):
  3121. """
  3122. Return the lower and upper x-axis bounds, in increasing order.
  3123. See Also
  3124. --------
  3125. set_xbound
  3126. get_xlim, set_xlim
  3127. invert_xaxis, xaxis_inverted
  3128. """
  3129. left, right = self.get_xlim()
  3130. if left < right:
  3131. return left, right
  3132. else:
  3133. return right, left
  3134. def set_xbound(self, lower=None, upper=None):
  3135. """
  3136. Set the lower and upper numerical bounds of the x-axis.
  3137. This method will honor axis inversion regardless of parameter order.
  3138. It will not change the autoscaling setting (`.get_autoscalex_on()`).
  3139. Parameters
  3140. ----------
  3141. lower, upper : float or None
  3142. The lower and upper bounds. If *None*, the respective axis bound
  3143. is not modified.
  3144. .. ACCEPTS: (lower: float, upper: float)
  3145. See Also
  3146. --------
  3147. get_xbound
  3148. get_xlim, set_xlim
  3149. invert_xaxis, xaxis_inverted
  3150. """
  3151. if upper is None and np.iterable(lower):
  3152. lower, upper = lower
  3153. old_lower, old_upper = self.get_xbound()
  3154. if lower is None:
  3155. lower = old_lower
  3156. if upper is None:
  3157. upper = old_upper
  3158. self.set_xlim(sorted((lower, upper),
  3159. reverse=bool(self.xaxis_inverted())),
  3160. auto=None)
  3161. def get_xlim(self):
  3162. """
  3163. Return the x-axis view limits.
  3164. Returns
  3165. -------
  3166. left, right : (float, float)
  3167. The current x-axis limits in data coordinates.
  3168. See Also
  3169. --------
  3170. .Axes.set_xlim
  3171. .Axes.set_xbound, .Axes.get_xbound
  3172. .Axes.invert_xaxis, .Axes.xaxis_inverted
  3173. Notes
  3174. -----
  3175. The x-axis may be inverted, in which case the *left* value will
  3176. be greater than the *right* value.
  3177. """
  3178. return tuple(self.viewLim.intervalx)
  3179. def _validate_converted_limits(self, limit, convert):
  3180. """
  3181. Raise ValueError if converted limits are non-finite.
  3182. Note that this function also accepts None as a limit argument.
  3183. Returns
  3184. -------
  3185. The limit value after call to convert(), or None if limit is None.
  3186. """
  3187. if limit is not None:
  3188. converted_limit = convert(limit)
  3189. if isinstance(converted_limit, np.ndarray):
  3190. converted_limit = converted_limit.squeeze()
  3191. if (isinstance(converted_limit, Real)
  3192. and not np.isfinite(converted_limit)):
  3193. raise ValueError("Axis limits cannot be NaN or Inf")
  3194. return converted_limit
  3195. def set_xlim(self, left=None, right=None, *, emit=True, auto=False,
  3196. xmin=None, xmax=None):
  3197. """
  3198. Set the x-axis view limits.
  3199. Parameters
  3200. ----------
  3201. left : float, optional
  3202. The left xlim in data coordinates. Passing *None* leaves the
  3203. limit unchanged.
  3204. The left and right xlims may also be passed as the tuple
  3205. (*left*, *right*) as the first positional argument (or as
  3206. the *left* keyword argument).
  3207. .. ACCEPTS: (left: float, right: float)
  3208. right : float, optional
  3209. The right xlim in data coordinates. Passing *None* leaves the
  3210. limit unchanged.
  3211. emit : bool, default: True
  3212. Whether to notify observers of limit change.
  3213. auto : bool or None, default: False
  3214. Whether to turn on autoscaling of the x-axis. True turns on,
  3215. False turns off, None leaves unchanged.
  3216. xmin, xmax : float, optional
  3217. They are equivalent to left and right respectively, and it is an
  3218. error to pass both *xmin* and *left* or *xmax* and *right*.
  3219. Returns
  3220. -------
  3221. left, right : (float, float)
  3222. The new x-axis limits in data coordinates.
  3223. See Also
  3224. --------
  3225. get_xlim
  3226. set_xbound, get_xbound
  3227. invert_xaxis, xaxis_inverted
  3228. Notes
  3229. -----
  3230. The *left* value may be greater than the *right* value, in which
  3231. case the x-axis values will decrease from left to right.
  3232. Examples
  3233. --------
  3234. >>> set_xlim(left, right)
  3235. >>> set_xlim((left, right))
  3236. >>> left, right = set_xlim(left, right)
  3237. One limit may be left unchanged.
  3238. >>> set_xlim(right=right_lim)
  3239. Limits may be passed in reverse order to flip the direction of
  3240. the x-axis. For example, suppose *x* represents the number of
  3241. years before present. The x-axis limits might be set like the
  3242. following so 5000 years ago is on the left of the plot and the
  3243. present is on the right.
  3244. >>> set_xlim(5000, 0)
  3245. """
  3246. if right is None and np.iterable(left):
  3247. left, right = left
  3248. if xmin is not None:
  3249. if left is not None:
  3250. raise TypeError("Cannot pass both 'left' and 'xmin'")
  3251. left = xmin
  3252. if xmax is not None:
  3253. if right is not None:
  3254. raise TypeError("Cannot pass both 'right' and 'xmax'")
  3255. right = xmax
  3256. return self.xaxis._set_lim(left, right, emit=emit, auto=auto)
  3257. get_xscale = _axis_method_wrapper("xaxis", "get_scale")
  3258. set_xscale = _axis_method_wrapper("xaxis", "_set_axes_scale")
  3259. get_xticks = _axis_method_wrapper("xaxis", "get_ticklocs")
  3260. set_xticks = _axis_method_wrapper("xaxis", "set_ticks",
  3261. doc_sub={'set_ticks': 'set_xticks'})
  3262. get_xmajorticklabels = _axis_method_wrapper("xaxis", "get_majorticklabels")
  3263. get_xminorticklabels = _axis_method_wrapper("xaxis", "get_minorticklabels")
  3264. get_xticklabels = _axis_method_wrapper("xaxis", "get_ticklabels")
  3265. set_xticklabels = _axis_method_wrapper(
  3266. "xaxis", "set_ticklabels",
  3267. doc_sub={"Axis.set_ticks": "Axes.set_xticks"})
  3268. def get_ylabel(self):
  3269. """
  3270. Get the ylabel text string.
  3271. """
  3272. label = self.yaxis.label
  3273. return label.get_text()
  3274. def set_ylabel(self, ylabel, fontdict=None, labelpad=None, *,
  3275. loc=None, **kwargs):
  3276. """
  3277. Set the label for the y-axis.
  3278. Parameters
  3279. ----------
  3280. ylabel : str
  3281. The label text.
  3282. labelpad : float, default: :rc:`axes.labelpad`
  3283. Spacing in points from the Axes bounding box including ticks
  3284. and tick labels. If None, the previous value is left as is.
  3285. loc : {'bottom', 'center', 'top'}, default: :rc:`yaxis.labellocation`
  3286. The label position. This is a high-level alternative for passing
  3287. parameters *y* and *horizontalalignment*.
  3288. Other Parameters
  3289. ----------------
  3290. **kwargs : `~matplotlib.text.Text` properties
  3291. `.Text` properties control the appearance of the label.
  3292. See Also
  3293. --------
  3294. text : Documents the properties supported by `.Text`.
  3295. """
  3296. if labelpad is not None:
  3297. self.yaxis.labelpad = labelpad
  3298. protected_kw = ['y', 'horizontalalignment', 'ha']
  3299. if {*kwargs} & {*protected_kw}:
  3300. if loc is not None:
  3301. raise TypeError(f"Specifying 'loc' is disallowed when any of "
  3302. f"its corresponding low level keyword "
  3303. f"arguments ({protected_kw}) are also "
  3304. f"supplied")
  3305. else:
  3306. loc = (loc if loc is not None
  3307. else mpl.rcParams['yaxis.labellocation'])
  3308. _api.check_in_list(('bottom', 'center', 'top'), loc=loc)
  3309. y, ha = {
  3310. 'bottom': (0, 'left'),
  3311. 'center': (0.5, 'center'),
  3312. 'top': (1, 'right')
  3313. }[loc]
  3314. kwargs.update(y=y, horizontalalignment=ha)
  3315. return self.yaxis.set_label_text(ylabel, fontdict, **kwargs)
  3316. def invert_yaxis(self):
  3317. """
  3318. Invert the y-axis.
  3319. See Also
  3320. --------
  3321. yaxis_inverted
  3322. get_ylim, set_ylim
  3323. get_ybound, set_ybound
  3324. """
  3325. self.yaxis.set_inverted(not self.yaxis.get_inverted())
  3326. yaxis_inverted = _axis_method_wrapper("yaxis", "get_inverted")
  3327. def get_ybound(self):
  3328. """
  3329. Return the lower and upper y-axis bounds, in increasing order.
  3330. See Also
  3331. --------
  3332. set_ybound
  3333. get_ylim, set_ylim
  3334. invert_yaxis, yaxis_inverted
  3335. """
  3336. bottom, top = self.get_ylim()
  3337. if bottom < top:
  3338. return bottom, top
  3339. else:
  3340. return top, bottom
  3341. def set_ybound(self, lower=None, upper=None):
  3342. """
  3343. Set the lower and upper numerical bounds of the y-axis.
  3344. This method will honor axis inversion regardless of parameter order.
  3345. It will not change the autoscaling setting (`.get_autoscaley_on()`).
  3346. Parameters
  3347. ----------
  3348. lower, upper : float or None
  3349. The lower and upper bounds. If *None*, the respective axis bound
  3350. is not modified.
  3351. .. ACCEPTS: (lower: float, upper: float)
  3352. See Also
  3353. --------
  3354. get_ybound
  3355. get_ylim, set_ylim
  3356. invert_yaxis, yaxis_inverted
  3357. """
  3358. if upper is None and np.iterable(lower):
  3359. lower, upper = lower
  3360. old_lower, old_upper = self.get_ybound()
  3361. if lower is None:
  3362. lower = old_lower
  3363. if upper is None:
  3364. upper = old_upper
  3365. self.set_ylim(sorted((lower, upper),
  3366. reverse=bool(self.yaxis_inverted())),
  3367. auto=None)
  3368. def get_ylim(self):
  3369. """
  3370. Return the y-axis view limits.
  3371. Returns
  3372. -------
  3373. bottom, top : (float, float)
  3374. The current y-axis limits in data coordinates.
  3375. See Also
  3376. --------
  3377. .Axes.set_ylim
  3378. .Axes.set_ybound, .Axes.get_ybound
  3379. .Axes.invert_yaxis, .Axes.yaxis_inverted
  3380. Notes
  3381. -----
  3382. The y-axis may be inverted, in which case the *bottom* value
  3383. will be greater than the *top* value.
  3384. """
  3385. return tuple(self.viewLim.intervaly)
  3386. def set_ylim(self, bottom=None, top=None, *, emit=True, auto=False,
  3387. ymin=None, ymax=None):
  3388. """
  3389. Set the y-axis view limits.
  3390. Parameters
  3391. ----------
  3392. bottom : float, optional
  3393. The bottom ylim in data coordinates. Passing *None* leaves the
  3394. limit unchanged.
  3395. The bottom and top ylims may also be passed as the tuple
  3396. (*bottom*, *top*) as the first positional argument (or as
  3397. the *bottom* keyword argument).
  3398. .. ACCEPTS: (bottom: float, top: float)
  3399. top : float, optional
  3400. The top ylim in data coordinates. Passing *None* leaves the
  3401. limit unchanged.
  3402. emit : bool, default: True
  3403. Whether to notify observers of limit change.
  3404. auto : bool or None, default: False
  3405. Whether to turn on autoscaling of the y-axis. *True* turns on,
  3406. *False* turns off, *None* leaves unchanged.
  3407. ymin, ymax : float, optional
  3408. They are equivalent to bottom and top respectively, and it is an
  3409. error to pass both *ymin* and *bottom* or *ymax* and *top*.
  3410. Returns
  3411. -------
  3412. bottom, top : (float, float)
  3413. The new y-axis limits in data coordinates.
  3414. See Also
  3415. --------
  3416. get_ylim
  3417. set_ybound, get_ybound
  3418. invert_yaxis, yaxis_inverted
  3419. Notes
  3420. -----
  3421. The *bottom* value may be greater than the *top* value, in which
  3422. case the y-axis values will decrease from *bottom* to *top*.
  3423. Examples
  3424. --------
  3425. >>> set_ylim(bottom, top)
  3426. >>> set_ylim((bottom, top))
  3427. >>> bottom, top = set_ylim(bottom, top)
  3428. One limit may be left unchanged.
  3429. >>> set_ylim(top=top_lim)
  3430. Limits may be passed in reverse order to flip the direction of
  3431. the y-axis. For example, suppose ``y`` represents depth of the
  3432. ocean in m. The y-axis limits might be set like the following
  3433. so 5000 m depth is at the bottom of the plot and the surface,
  3434. 0 m, is at the top.
  3435. >>> set_ylim(5000, 0)
  3436. """
  3437. if top is None and np.iterable(bottom):
  3438. bottom, top = bottom
  3439. if ymin is not None:
  3440. if bottom is not None:
  3441. raise TypeError("Cannot pass both 'bottom' and 'ymin'")
  3442. bottom = ymin
  3443. if ymax is not None:
  3444. if top is not None:
  3445. raise TypeError("Cannot pass both 'top' and 'ymax'")
  3446. top = ymax
  3447. return self.yaxis._set_lim(bottom, top, emit=emit, auto=auto)
  3448. get_yscale = _axis_method_wrapper("yaxis", "get_scale")
  3449. set_yscale = _axis_method_wrapper("yaxis", "_set_axes_scale")
  3450. get_yticks = _axis_method_wrapper("yaxis", "get_ticklocs")
  3451. set_yticks = _axis_method_wrapper("yaxis", "set_ticks",
  3452. doc_sub={'set_ticks': 'set_yticks'})
  3453. get_ymajorticklabels = _axis_method_wrapper("yaxis", "get_majorticklabels")
  3454. get_yminorticklabels = _axis_method_wrapper("yaxis", "get_minorticklabels")
  3455. get_yticklabels = _axis_method_wrapper("yaxis", "get_ticklabels")
  3456. set_yticklabels = _axis_method_wrapper(
  3457. "yaxis", "set_ticklabels",
  3458. doc_sub={"Axis.set_ticks": "Axes.set_yticks"})
  3459. xaxis_date = _axis_method_wrapper("xaxis", "axis_date")
  3460. yaxis_date = _axis_method_wrapper("yaxis", "axis_date")
  3461. def format_xdata(self, x):
  3462. """
  3463. Return *x* formatted as an x-value.
  3464. This function will use the `.fmt_xdata` attribute if it is not None,
  3465. else will fall back on the xaxis major formatter.
  3466. """
  3467. return (self.fmt_xdata if self.fmt_xdata is not None
  3468. else self.xaxis.get_major_formatter().format_data_short)(x)
  3469. def format_ydata(self, y):
  3470. """
  3471. Return *y* formatted as a y-value.
  3472. This function will use the `.fmt_ydata` attribute if it is not None,
  3473. else will fall back on the yaxis major formatter.
  3474. """
  3475. return (self.fmt_ydata if self.fmt_ydata is not None
  3476. else self.yaxis.get_major_formatter().format_data_short)(y)
  3477. def format_coord(self, x, y):
  3478. """Return a format string formatting the *x*, *y* coordinates."""
  3479. twins = self._twinned_axes.get_siblings(self)
  3480. if len(twins) == 1:
  3481. return "(x, y) = ({}, {})".format(
  3482. "???" if x is None else self.format_xdata(x),
  3483. "???" if y is None else self.format_ydata(y))
  3484. screen_xy = self.transData.transform((x, y))
  3485. xy_strs = []
  3486. # Retrieve twins in the order of self.figure.axes to sort tied zorders (which is
  3487. # the common case) by the order in which they are added to the figure.
  3488. for ax in sorted(twins, key=attrgetter("zorder")):
  3489. data_x, data_y = ax.transData.inverted().transform(screen_xy)
  3490. xy_strs.append(
  3491. "({}, {})".format(ax.format_xdata(data_x), ax.format_ydata(data_y)))
  3492. return "(x, y) = {}".format(" | ".join(xy_strs))
  3493. def minorticks_on(self):
  3494. """
  3495. Display minor ticks on the Axes.
  3496. Displaying minor ticks may reduce performance; you may turn them off
  3497. using `minorticks_off()` if drawing speed is a problem.
  3498. """
  3499. self.xaxis.minorticks_on()
  3500. self.yaxis.minorticks_on()
  3501. def minorticks_off(self):
  3502. """Remove minor ticks from the Axes."""
  3503. self.xaxis.minorticks_off()
  3504. self.yaxis.minorticks_off()
  3505. # Interactive manipulation
  3506. def can_zoom(self):
  3507. """
  3508. Return whether this Axes supports the zoom box button functionality.
  3509. """
  3510. return True
  3511. def can_pan(self):
  3512. """
  3513. Return whether this Axes supports any pan/zoom button functionality.
  3514. """
  3515. return True
  3516. def get_navigate(self):
  3517. """
  3518. Get whether the Axes responds to navigation commands.
  3519. """
  3520. return self._navigate
  3521. def set_navigate(self, b):
  3522. """
  3523. Set whether the Axes responds to navigation toolbar commands.
  3524. Parameters
  3525. ----------
  3526. b : bool
  3527. See Also
  3528. --------
  3529. matplotlib.axes.Axes.set_forward_navigation_events
  3530. """
  3531. self._navigate = b
  3532. def get_navigate_mode(self):
  3533. """
  3534. Get the navigation toolbar button status: 'PAN', 'ZOOM', or None.
  3535. """
  3536. return self._navigate_mode
  3537. def set_navigate_mode(self, b):
  3538. """
  3539. Set the navigation toolbar button status.
  3540. .. warning::
  3541. This is not a user-API function.
  3542. """
  3543. self._navigate_mode = b
  3544. def _get_view(self):
  3545. """
  3546. Save information required to reproduce the current view.
  3547. This method is called before a view is changed, such as during a pan or zoom
  3548. initiated by the user. It returns an opaque object that describes the current
  3549. view, in a format compatible with :meth:`_set_view`.
  3550. The default implementation saves the view limits and autoscaling state.
  3551. Subclasses may override this as needed, as long as :meth:`_set_view` is also
  3552. adjusted accordingly.
  3553. """
  3554. return {
  3555. "xlim": self.get_xlim(), "autoscalex_on": self.get_autoscalex_on(),
  3556. "ylim": self.get_ylim(), "autoscaley_on": self.get_autoscaley_on(),
  3557. }
  3558. def _set_view(self, view):
  3559. """
  3560. Apply a previously saved view.
  3561. This method is called when restoring a view (with the return value of
  3562. :meth:`_get_view` as argument), such as with the navigation buttons.
  3563. Subclasses that override :meth:`_get_view` also need to override this method
  3564. accordingly.
  3565. """
  3566. self.set(**view)
  3567. def _prepare_view_from_bbox(self, bbox, direction='in',
  3568. mode=None, twinx=False, twiny=False):
  3569. """
  3570. Helper function to prepare the new bounds from a bbox.
  3571. This helper function returns the new x and y bounds from the zoom
  3572. bbox. This a convenience method to abstract the bbox logic
  3573. out of the base setter.
  3574. """
  3575. if len(bbox) == 3:
  3576. xp, yp, scl = bbox # Zooming code
  3577. if scl == 0: # Should not happen
  3578. scl = 1.
  3579. if scl > 1:
  3580. direction = 'in'
  3581. else:
  3582. direction = 'out'
  3583. scl = 1/scl
  3584. # get the limits of the axes
  3585. (xmin, ymin), (xmax, ymax) = self.transData.transform(
  3586. np.transpose([self.get_xlim(), self.get_ylim()]))
  3587. # set the range
  3588. xwidth = xmax - xmin
  3589. ywidth = ymax - ymin
  3590. xcen = (xmax + xmin)*.5
  3591. ycen = (ymax + ymin)*.5
  3592. xzc = (xp*(scl - 1) + xcen)/scl
  3593. yzc = (yp*(scl - 1) + ycen)/scl
  3594. bbox = [xzc - xwidth/2./scl, yzc - ywidth/2./scl,
  3595. xzc + xwidth/2./scl, yzc + ywidth/2./scl]
  3596. elif len(bbox) != 4:
  3597. # should be len 3 or 4 but nothing else
  3598. _api.warn_external(
  3599. "Warning in _set_view_from_bbox: bounding box is not a tuple "
  3600. "of length 3 or 4. Ignoring the view change.")
  3601. return
  3602. # Original limits.
  3603. xmin0, xmax0 = self.get_xbound()
  3604. ymin0, ymax0 = self.get_ybound()
  3605. # The zoom box in screen coords.
  3606. startx, starty, stopx, stopy = bbox
  3607. # Convert to data coords.
  3608. (startx, starty), (stopx, stopy) = self.transData.inverted().transform(
  3609. [(startx, starty), (stopx, stopy)])
  3610. # Clip to axes limits.
  3611. xmin, xmax = np.clip(sorted([startx, stopx]), xmin0, xmax0)
  3612. ymin, ymax = np.clip(sorted([starty, stopy]), ymin0, ymax0)
  3613. # Don't double-zoom twinned axes or if zooming only the other axis.
  3614. if twinx or mode == "y":
  3615. xmin, xmax = xmin0, xmax0
  3616. if twiny or mode == "x":
  3617. ymin, ymax = ymin0, ymax0
  3618. if direction == "in":
  3619. new_xbound = xmin, xmax
  3620. new_ybound = ymin, ymax
  3621. elif direction == "out":
  3622. x_trf = self.xaxis.get_transform()
  3623. sxmin0, sxmax0, sxmin, sxmax = x_trf.transform(
  3624. [xmin0, xmax0, xmin, xmax]) # To screen space.
  3625. factor = (sxmax0 - sxmin0) / (sxmax - sxmin) # Unzoom factor.
  3626. # Move original bounds away by
  3627. # (factor) x (distance between unzoom box and Axes bbox).
  3628. sxmin1 = sxmin0 - factor * (sxmin - sxmin0)
  3629. sxmax1 = sxmax0 + factor * (sxmax0 - sxmax)
  3630. # And back to data space.
  3631. new_xbound = x_trf.inverted().transform([sxmin1, sxmax1])
  3632. y_trf = self.yaxis.get_transform()
  3633. symin0, symax0, symin, symax = y_trf.transform(
  3634. [ymin0, ymax0, ymin, ymax])
  3635. factor = (symax0 - symin0) / (symax - symin)
  3636. symin1 = symin0 - factor * (symin - symin0)
  3637. symax1 = symax0 + factor * (symax0 - symax)
  3638. new_ybound = y_trf.inverted().transform([symin1, symax1])
  3639. return new_xbound, new_ybound
  3640. def _set_view_from_bbox(self, bbox, direction='in',
  3641. mode=None, twinx=False, twiny=False):
  3642. """
  3643. Update view from a selection bbox.
  3644. .. note::
  3645. Intended to be overridden by new projection types, but if not, the
  3646. default implementation sets the view limits to the bbox directly.
  3647. Parameters
  3648. ----------
  3649. bbox : 4-tuple or 3 tuple
  3650. * If bbox is a 4 tuple, it is the selected bounding box limits,
  3651. in *display* coordinates.
  3652. * If bbox is a 3 tuple, it is an (xp, yp, scl) triple, where
  3653. (xp, yp) is the center of zooming and scl the scale factor to
  3654. zoom by.
  3655. direction : str
  3656. The direction to apply the bounding box.
  3657. * `'in'` - The bounding box describes the view directly, i.e.,
  3658. it zooms in.
  3659. * `'out'` - The bounding box describes the size to make the
  3660. existing view, i.e., it zooms out.
  3661. mode : str or None
  3662. The selection mode, whether to apply the bounding box in only the
  3663. `'x'` direction, `'y'` direction or both (`None`).
  3664. twinx : bool
  3665. Whether this axis is twinned in the *x*-direction.
  3666. twiny : bool
  3667. Whether this axis is twinned in the *y*-direction.
  3668. """
  3669. new_xbound, new_ybound = self._prepare_view_from_bbox(
  3670. bbox, direction=direction, mode=mode, twinx=twinx, twiny=twiny)
  3671. if not twinx and mode != "y":
  3672. self.set_xbound(new_xbound)
  3673. self.set_autoscalex_on(False)
  3674. if not twiny and mode != "x":
  3675. self.set_ybound(new_ybound)
  3676. self.set_autoscaley_on(False)
  3677. def start_pan(self, x, y, button):
  3678. """
  3679. Called when a pan operation has started.
  3680. Parameters
  3681. ----------
  3682. x, y : float
  3683. The mouse coordinates in display coords.
  3684. button : `.MouseButton`
  3685. The pressed mouse button.
  3686. Notes
  3687. -----
  3688. This is intended to be overridden by new projection types.
  3689. """
  3690. self._pan_start = types.SimpleNamespace(
  3691. lim=self.viewLim.frozen(),
  3692. trans=self.transData.frozen(),
  3693. trans_inverse=self.transData.inverted().frozen(),
  3694. bbox=self.bbox.frozen(),
  3695. x=x,
  3696. y=y)
  3697. def end_pan(self):
  3698. """
  3699. Called when a pan operation completes (when the mouse button is up.)
  3700. Notes
  3701. -----
  3702. This is intended to be overridden by new projection types.
  3703. """
  3704. del self._pan_start
  3705. def _get_pan_points(self, button, key, x, y):
  3706. """
  3707. Helper function to return the new points after a pan.
  3708. This helper function returns the points on the axis after a pan has
  3709. occurred. This is a convenience method to abstract the pan logic
  3710. out of the base setter.
  3711. """
  3712. def format_deltas(key, dx, dy):
  3713. if key == 'control':
  3714. if abs(dx) > abs(dy):
  3715. dy = dx
  3716. else:
  3717. dx = dy
  3718. elif key == 'x':
  3719. dy = 0
  3720. elif key == 'y':
  3721. dx = 0
  3722. elif key == 'shift':
  3723. if 2 * abs(dx) < abs(dy):
  3724. dx = 0
  3725. elif 2 * abs(dy) < abs(dx):
  3726. dy = 0
  3727. elif abs(dx) > abs(dy):
  3728. dy = dy / abs(dy) * abs(dx)
  3729. else:
  3730. dx = dx / abs(dx) * abs(dy)
  3731. return dx, dy
  3732. p = self._pan_start
  3733. dx = x - p.x
  3734. dy = y - p.y
  3735. if dx == dy == 0:
  3736. return
  3737. if button == 1:
  3738. dx, dy = format_deltas(key, dx, dy)
  3739. result = p.bbox.translated(-dx, -dy).transformed(p.trans_inverse)
  3740. elif button == 3:
  3741. try:
  3742. dx = -dx / self.bbox.width
  3743. dy = -dy / self.bbox.height
  3744. dx, dy = format_deltas(key, dx, dy)
  3745. if self.get_aspect() != 'auto':
  3746. dx = dy = 0.5 * (dx + dy)
  3747. alpha = np.power(10.0, (dx, dy))
  3748. start = np.array([p.x, p.y])
  3749. oldpoints = p.lim.transformed(p.trans)
  3750. newpoints = start + alpha * (oldpoints - start)
  3751. result = (mtransforms.Bbox(newpoints)
  3752. .transformed(p.trans_inverse))
  3753. except OverflowError:
  3754. _api.warn_external('Overflow while panning')
  3755. return
  3756. else:
  3757. return
  3758. valid = np.isfinite(result.transformed(p.trans))
  3759. points = result.get_points().astype(object)
  3760. # Just ignore invalid limits (typically, underflow in log-scale).
  3761. points[~valid] = None
  3762. return points
  3763. def drag_pan(self, button, key, x, y):
  3764. """
  3765. Called when the mouse moves during a pan operation.
  3766. Parameters
  3767. ----------
  3768. button : `.MouseButton`
  3769. The pressed mouse button.
  3770. key : str or None
  3771. The pressed key, if any.
  3772. x, y : float
  3773. The mouse coordinates in display coords.
  3774. Notes
  3775. -----
  3776. This is intended to be overridden by new projection types.
  3777. """
  3778. points = self._get_pan_points(button, key, x, y)
  3779. if points is not None:
  3780. self.set_xlim(points[:, 0])
  3781. self.set_ylim(points[:, 1])
  3782. def get_children(self):
  3783. # docstring inherited.
  3784. return [
  3785. *self._children,
  3786. *self.spines.values(),
  3787. *self._axis_map.values(),
  3788. self.title, self._left_title, self._right_title,
  3789. *self.child_axes,
  3790. *([self.legend_] if self.legend_ is not None else []),
  3791. self.patch,
  3792. ]
  3793. def contains(self, mouseevent):
  3794. # docstring inherited.
  3795. return self.patch.contains(mouseevent)
  3796. def contains_point(self, point):
  3797. """
  3798. Return whether *point* (pair of pixel coordinates) is inside the Axes
  3799. patch.
  3800. """
  3801. return self.patch.contains_point(point, radius=1.0)
  3802. def get_default_bbox_extra_artists(self):
  3803. """
  3804. Return a default list of artists that are used for the bounding box
  3805. calculation.
  3806. Artists are excluded either by not being visible or
  3807. ``artist.set_in_layout(False)``.
  3808. """
  3809. artists = self.get_children()
  3810. for axis in self._axis_map.values():
  3811. # axis tight bboxes are calculated separately inside
  3812. # Axes.get_tightbbox() using for_layout_only=True
  3813. artists.remove(axis)
  3814. if not (self.axison and self._frameon):
  3815. # don't do bbox on spines if frame not on.
  3816. for spine in self.spines.values():
  3817. artists.remove(spine)
  3818. artists.remove(self.title)
  3819. artists.remove(self._left_title)
  3820. artists.remove(self._right_title)
  3821. # always include types that do not internally implement clipping
  3822. # to Axes. may have clip_on set to True and clip_box equivalent
  3823. # to ax.bbox but then ignore these properties during draws.
  3824. noclip = (_AxesBase, maxis.Axis,
  3825. offsetbox.AnnotationBbox, offsetbox.OffsetBox)
  3826. return [a for a in artists if a.get_visible() and a.get_in_layout()
  3827. and (isinstance(a, noclip) or not a._fully_clipped_to_axes())]
  3828. def get_tightbbox(self, renderer=None, *, call_axes_locator=True,
  3829. bbox_extra_artists=None, for_layout_only=False):
  3830. """
  3831. Return the tight bounding box of the Axes, including axis and their
  3832. decorators (xlabel, title, etc).
  3833. Artists that have ``artist.set_in_layout(False)`` are not included
  3834. in the bbox.
  3835. Parameters
  3836. ----------
  3837. renderer : `.RendererBase` subclass
  3838. renderer that will be used to draw the figures (i.e.
  3839. ``fig.canvas.get_renderer()``)
  3840. bbox_extra_artists : list of `.Artist` or ``None``
  3841. List of artists to include in the tight bounding box. If
  3842. ``None`` (default), then all artist children of the Axes are
  3843. included in the tight bounding box.
  3844. call_axes_locator : bool, default: True
  3845. If *call_axes_locator* is ``False``, it does not call the
  3846. ``_axes_locator`` attribute, which is necessary to get the correct
  3847. bounding box. ``call_axes_locator=False`` can be used if the
  3848. caller is only interested in the relative size of the tightbbox
  3849. compared to the Axes bbox.
  3850. for_layout_only : default: False
  3851. The bounding box will *not* include the x-extent of the title and
  3852. the xlabel, or the y-extent of the ylabel.
  3853. Returns
  3854. -------
  3855. `.BboxBase`
  3856. Bounding box in figure pixel coordinates.
  3857. See Also
  3858. --------
  3859. matplotlib.axes.Axes.get_window_extent
  3860. matplotlib.axis.Axis.get_tightbbox
  3861. matplotlib.spines.Spine.get_window_extent
  3862. """
  3863. bb = []
  3864. if renderer is None:
  3865. renderer = self.get_figure(root=True)._get_renderer()
  3866. if not self.get_visible():
  3867. return None
  3868. locator = self.get_axes_locator()
  3869. self.apply_aspect(
  3870. locator(self, renderer) if locator and call_axes_locator else None)
  3871. for axis in self._axis_map.values():
  3872. if self.axison and axis.get_visible():
  3873. ba = martist._get_tightbbox_for_layout_only(axis, renderer)
  3874. if ba:
  3875. bb.append(ba)
  3876. self._update_title_position(renderer)
  3877. axbbox = self.get_window_extent(renderer)
  3878. bb.append(axbbox)
  3879. for title in [self.title, self._left_title, self._right_title]:
  3880. if title.get_visible():
  3881. bt = title.get_window_extent(renderer)
  3882. if for_layout_only and bt.width > 0:
  3883. # make the title bbox 1 pixel wide so its width
  3884. # is not accounted for in bbox calculations in
  3885. # tight/constrained_layout
  3886. bt.x0 = (bt.x0 + bt.x1) / 2 - 0.5
  3887. bt.x1 = bt.x0 + 1.0
  3888. bb.append(bt)
  3889. bbox_artists = bbox_extra_artists
  3890. if bbox_artists is None:
  3891. bbox_artists = self.get_default_bbox_extra_artists()
  3892. for a in bbox_artists:
  3893. bbox = a.get_tightbbox(renderer)
  3894. if (bbox is not None
  3895. and 0 < bbox.width < np.inf
  3896. and 0 < bbox.height < np.inf):
  3897. bb.append(bbox)
  3898. return mtransforms.Bbox.union(
  3899. [b for b in bb if b.width != 0 or b.height != 0])
  3900. def _make_twin_axes(self, *args, **kwargs):
  3901. """Make a twinx Axes of self. This is used for twinx and twiny."""
  3902. if 'sharex' in kwargs and 'sharey' in kwargs:
  3903. # The following line is added in v2.2 to avoid breaking Seaborn,
  3904. # which currently uses this internal API.
  3905. if kwargs["sharex"] is not self and kwargs["sharey"] is not self:
  3906. raise ValueError("Twinned Axes may share only one axis")
  3907. ss = self.get_subplotspec()
  3908. if ss:
  3909. twin = self.get_figure(root=False).add_subplot(ss, *args, **kwargs)
  3910. else:
  3911. twin = self.get_figure(root=False).add_axes(
  3912. self.get_position(True), *args, **kwargs,
  3913. axes_locator=_TransformedBoundsLocator(
  3914. [0, 0, 1, 1], self.transAxes))
  3915. self.set_adjustable('datalim')
  3916. twin.set_adjustable('datalim')
  3917. twin.set_zorder(self.zorder)
  3918. self._twinned_axes.join(self, twin)
  3919. return twin
  3920. def twinx(self):
  3921. """
  3922. Create a twin Axes sharing the xaxis.
  3923. Create a new Axes with an invisible x-axis and an independent
  3924. y-axis positioned opposite to the original one (i.e. at right). The
  3925. x-axis autoscale setting will be inherited from the original
  3926. Axes. To ensure that the tick marks of both y-axes align, see
  3927. `~matplotlib.ticker.LinearLocator`.
  3928. Returns
  3929. -------
  3930. Axes
  3931. The newly created Axes instance
  3932. Notes
  3933. -----
  3934. For those who are 'picking' artists while using twinx, pick
  3935. events are only called for the artists in the top-most Axes.
  3936. """
  3937. ax2 = self._make_twin_axes(sharex=self)
  3938. ax2.yaxis.tick_right()
  3939. ax2.yaxis.set_label_position('right')
  3940. ax2.yaxis.set_offset_position('right')
  3941. ax2.set_autoscalex_on(self.get_autoscalex_on())
  3942. self.yaxis.tick_left()
  3943. ax2.xaxis.set_visible(False)
  3944. ax2.patch.set_visible(False)
  3945. ax2.xaxis.units = self.xaxis.units
  3946. return ax2
  3947. def twiny(self):
  3948. """
  3949. Create a twin Axes sharing the yaxis.
  3950. Create a new Axes with an invisible y-axis and an independent
  3951. x-axis positioned opposite to the original one (i.e. at top). The
  3952. y-axis autoscale setting will be inherited from the original Axes.
  3953. To ensure that the tick marks of both x-axes align, see
  3954. `~matplotlib.ticker.LinearLocator`.
  3955. Returns
  3956. -------
  3957. Axes
  3958. The newly created Axes instance
  3959. Notes
  3960. -----
  3961. For those who are 'picking' artists while using twiny, pick
  3962. events are only called for the artists in the top-most Axes.
  3963. """
  3964. ax2 = self._make_twin_axes(sharey=self)
  3965. ax2.xaxis.tick_top()
  3966. ax2.xaxis.set_label_position('top')
  3967. ax2.set_autoscaley_on(self.get_autoscaley_on())
  3968. self.xaxis.tick_bottom()
  3969. ax2.yaxis.set_visible(False)
  3970. ax2.patch.set_visible(False)
  3971. ax2.yaxis.units = self.yaxis.units
  3972. return ax2
  3973. def get_shared_x_axes(self):
  3974. """Return an immutable view on the shared x-axes Grouper."""
  3975. return cbook.GrouperView(self._shared_axes["x"])
  3976. def get_shared_y_axes(self):
  3977. """Return an immutable view on the shared y-axes Grouper."""
  3978. return cbook.GrouperView(self._shared_axes["y"])
  3979. def label_outer(self, remove_inner_ticks=False):
  3980. """
  3981. Only show "outer" labels and tick labels.
  3982. x-labels are only kept for subplots on the last row (or first row, if
  3983. labels are on the top side); y-labels only for subplots on the first
  3984. column (or last column, if labels are on the right side).
  3985. Parameters
  3986. ----------
  3987. remove_inner_ticks : bool, default: False
  3988. If True, remove the inner ticks as well (not only tick labels).
  3989. .. versionadded:: 3.8
  3990. """
  3991. self._label_outer_xaxis(skip_non_rectangular_axes=False,
  3992. remove_inner_ticks=remove_inner_ticks)
  3993. self._label_outer_yaxis(skip_non_rectangular_axes=False,
  3994. remove_inner_ticks=remove_inner_ticks)
  3995. def _get_subplotspec_with_optional_colorbar(self):
  3996. """
  3997. Return the subplotspec for this Axes, except that if this Axes has been
  3998. moved to a subgridspec to make room for a colorbar, then return the
  3999. subplotspec that encloses both this Axes and the colorbar Axes.
  4000. """
  4001. ss = self.get_subplotspec()
  4002. if any(cax.get_subplotspec() for cax in self._colorbars):
  4003. ss = ss.get_gridspec()._subplot_spec
  4004. return ss
  4005. def _label_outer_xaxis(self, *, skip_non_rectangular_axes,
  4006. remove_inner_ticks=False):
  4007. # see documentation in label_outer.
  4008. if skip_non_rectangular_axes and not isinstance(self.patch,
  4009. mpl.patches.Rectangle):
  4010. return
  4011. ss = self._get_subplotspec_with_optional_colorbar()
  4012. if ss is None:
  4013. return
  4014. label_position = self.xaxis.get_label_position()
  4015. if not ss.is_first_row(): # Remove top label/ticklabels/offsettext.
  4016. if label_position == "top":
  4017. self.set_xlabel("")
  4018. top_kw = {'top': False} if remove_inner_ticks else {}
  4019. self.xaxis.set_tick_params(
  4020. which="both", labeltop=False, **top_kw)
  4021. if self.xaxis.offsetText.get_position()[1] == 1:
  4022. self.xaxis.offsetText.set_visible(False)
  4023. if not ss.is_last_row(): # Remove bottom label/ticklabels/offsettext.
  4024. if label_position == "bottom":
  4025. self.set_xlabel("")
  4026. bottom_kw = {'bottom': False} if remove_inner_ticks else {}
  4027. self.xaxis.set_tick_params(
  4028. which="both", labelbottom=False, **bottom_kw)
  4029. if self.xaxis.offsetText.get_position()[1] == 0:
  4030. self.xaxis.offsetText.set_visible(False)
  4031. def _label_outer_yaxis(self, *, skip_non_rectangular_axes,
  4032. remove_inner_ticks=False):
  4033. # see documentation in label_outer.
  4034. if skip_non_rectangular_axes and not isinstance(self.patch,
  4035. mpl.patches.Rectangle):
  4036. return
  4037. ss = self._get_subplotspec_with_optional_colorbar()
  4038. if ss is None:
  4039. return
  4040. label_position = self.yaxis.get_label_position()
  4041. if not ss.is_first_col(): # Remove left label/ticklabels/offsettext.
  4042. if label_position == "left":
  4043. self.set_ylabel("")
  4044. left_kw = {'left': False} if remove_inner_ticks else {}
  4045. self.yaxis.set_tick_params(
  4046. which="both", labelleft=False, **left_kw)
  4047. if self.yaxis.offsetText.get_position()[0] == 0:
  4048. self.yaxis.offsetText.set_visible(False)
  4049. if not ss.is_last_col(): # Remove right label/ticklabels/offsettext.
  4050. if label_position == "right":
  4051. self.set_ylabel("")
  4052. right_kw = {'right': False} if remove_inner_ticks else {}
  4053. self.yaxis.set_tick_params(
  4054. which="both", labelright=False, **right_kw)
  4055. if self.yaxis.offsetText.get_position()[0] == 1:
  4056. self.yaxis.offsetText.set_visible(False)
  4057. def set_forward_navigation_events(self, forward):
  4058. """
  4059. Set how pan/zoom events are forwarded to Axes below this one.
  4060. Parameters
  4061. ----------
  4062. forward : bool or "auto"
  4063. Possible values:
  4064. - True: Forward events to other axes with lower or equal zorder.
  4065. - False: Events are only executed on this axes.
  4066. - "auto": Default behaviour (*True* for axes with an invisible
  4067. patch and *False* otherwise)
  4068. See Also
  4069. --------
  4070. matplotlib.axes.Axes.set_navigate
  4071. """
  4072. self._forward_navigation_events = forward
  4073. def get_forward_navigation_events(self):
  4074. """Get how pan/zoom events are forwarded to Axes below this one."""
  4075. return self._forward_navigation_events
  4076. def _draw_rasterized(figure, artists, renderer):
  4077. """
  4078. A helper function for rasterizing the list of artists.
  4079. The bookkeeping to track if we are or are not in rasterizing mode
  4080. with the mixed-mode backends is relatively complicated and is now
  4081. handled in the matplotlib.artist.allow_rasterization decorator.
  4082. This helper defines the absolute minimum methods and attributes on a
  4083. shim class to be compatible with that decorator and then uses it to
  4084. rasterize the list of artists.
  4085. This is maybe too-clever, but allows us to reuse the same code that is
  4086. used on normal artists to participate in the "are we rasterizing"
  4087. accounting.
  4088. Please do not use this outside of the "rasterize below a given zorder"
  4089. functionality of Axes.
  4090. Parameters
  4091. ----------
  4092. figure : matplotlib.figure.Figure
  4093. The figure all of the artists belong to (not checked). We need this
  4094. because we can at the figure level suppress composition and insert each
  4095. rasterized artist as its own image.
  4096. artists : List[matplotlib.artist.Artist]
  4097. The list of Artists to be rasterized. These are assumed to all
  4098. be in the same Figure.
  4099. renderer : matplotlib.backendbases.RendererBase
  4100. The currently active renderer
  4101. Returns
  4102. -------
  4103. None
  4104. """
  4105. class _MinimalArtist:
  4106. def get_rasterized(self):
  4107. return True
  4108. def get_agg_filter(self):
  4109. return None
  4110. def __init__(self, figure, artists):
  4111. self.figure = figure
  4112. self.artists = artists
  4113. def get_figure(self, root=False):
  4114. if root:
  4115. return self.figure.get_figure(root=True)
  4116. else:
  4117. return self.figure
  4118. @martist.allow_rasterization
  4119. def draw(self, renderer):
  4120. for a in self.artists:
  4121. a.draw(renderer)
  4122. return _MinimalArtist(figure, artists).draw(renderer)