_base.py 174 KB

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