_base.py 156 KB

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