axis.py 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766
  1. """
  2. Classes for the ticks and x- and y-axis.
  3. """
  4. import datetime
  5. import functools
  6. import logging
  7. from numbers import Real
  8. import warnings
  9. import numpy as np
  10. import matplotlib as mpl
  11. from matplotlib import _api, cbook
  12. import matplotlib.artist as martist
  13. import matplotlib.colors as mcolors
  14. import matplotlib.lines as mlines
  15. import matplotlib.scale as mscale
  16. import matplotlib.text as mtext
  17. import matplotlib.ticker as mticker
  18. import matplotlib.transforms as mtransforms
  19. import matplotlib.units as munits
  20. _log = logging.getLogger(__name__)
  21. GRIDLINE_INTERPOLATION_STEPS = 180
  22. # This list is being used for compatibility with Axes.grid, which
  23. # allows all Line2D kwargs.
  24. _line_inspector = martist.ArtistInspector(mlines.Line2D)
  25. _line_param_names = _line_inspector.get_setters()
  26. _line_param_aliases = [list(d)[0] for d in _line_inspector.aliasd.values()]
  27. _gridline_param_names = ['grid_' + name
  28. for name in _line_param_names + _line_param_aliases]
  29. _MARKER_DICT = {
  30. 'out': (mlines.TICKDOWN, mlines.TICKUP),
  31. 'in': (mlines.TICKUP, mlines.TICKDOWN),
  32. 'inout': ('|', '|'),
  33. }
  34. class Tick(martist.Artist):
  35. """
  36. Abstract base class for the axis ticks, grid lines and labels.
  37. Ticks mark a position on an Axis. They contain two lines as markers and
  38. two labels; one each for the bottom and top positions (in case of an
  39. `.XAxis`) or for the left and right positions (in case of a `.YAxis`).
  40. Attributes
  41. ----------
  42. tick1line : `~matplotlib.lines.Line2D`
  43. The left/bottom tick marker.
  44. tick2line : `~matplotlib.lines.Line2D`
  45. The right/top tick marker.
  46. gridline : `~matplotlib.lines.Line2D`
  47. The grid line associated with the label position.
  48. label1 : `~matplotlib.text.Text`
  49. The left/bottom tick label.
  50. label2 : `~matplotlib.text.Text`
  51. The right/top tick label.
  52. """
  53. def __init__(
  54. self, axes, loc, *,
  55. size=None, # points
  56. width=None,
  57. color=None,
  58. tickdir=None,
  59. pad=None,
  60. labelsize=None,
  61. labelcolor=None,
  62. labelfontfamily=None,
  63. zorder=None,
  64. gridOn=None, # defaults to axes.grid depending on axes.grid.which
  65. tick1On=True,
  66. tick2On=True,
  67. label1On=True,
  68. label2On=False,
  69. major=True,
  70. labelrotation=0,
  71. grid_color=None,
  72. grid_linestyle=None,
  73. grid_linewidth=None,
  74. grid_alpha=None,
  75. **kwargs, # Other Line2D kwargs applied to gridlines.
  76. ):
  77. """
  78. bbox is the Bound2D bounding box in display coords of the Axes
  79. loc is the tick location in data coords
  80. size is the tick size in points
  81. """
  82. super().__init__()
  83. if gridOn is None:
  84. which = mpl.rcParams['axes.grid.which']
  85. if major and (which in ('both', 'major')):
  86. gridOn = mpl.rcParams['axes.grid']
  87. elif (not major) and (which in ('both', 'minor')):
  88. gridOn = mpl.rcParams['axes.grid']
  89. else:
  90. gridOn = False
  91. self.set_figure(axes.figure)
  92. self.axes = axes
  93. self._loc = loc
  94. self._major = major
  95. name = self.__name__
  96. major_minor = "major" if major else "minor"
  97. if size is None:
  98. size = mpl.rcParams[f"{name}.{major_minor}.size"]
  99. self._size = size
  100. if width is None:
  101. width = mpl.rcParams[f"{name}.{major_minor}.width"]
  102. self._width = width
  103. if color is None:
  104. color = mpl.rcParams[f"{name}.color"]
  105. if pad is None:
  106. pad = mpl.rcParams[f"{name}.{major_minor}.pad"]
  107. self._base_pad = pad
  108. if labelcolor is None:
  109. labelcolor = mpl.rcParams[f"{name}.labelcolor"]
  110. if cbook._str_equal(labelcolor, 'inherit'):
  111. # inherit from tick color
  112. labelcolor = mpl.rcParams[f"{name}.color"]
  113. if labelsize is None:
  114. labelsize = mpl.rcParams[f"{name}.labelsize"]
  115. self._set_labelrotation(labelrotation)
  116. if zorder is None:
  117. if major:
  118. zorder = mlines.Line2D.zorder + 0.01
  119. else:
  120. zorder = mlines.Line2D.zorder
  121. self._zorder = zorder
  122. grid_color = mpl._val_or_rc(grid_color, "grid.color")
  123. grid_linestyle = mpl._val_or_rc(grid_linestyle, "grid.linestyle")
  124. grid_linewidth = mpl._val_or_rc(grid_linewidth, "grid.linewidth")
  125. if grid_alpha is None and not mcolors._has_alpha_channel(grid_color):
  126. # alpha precedence: kwarg > color alpha > rcParams['grid.alpha']
  127. # Note: only resolve to rcParams if the color does not have alpha
  128. # otherwise `grid(color=(1, 1, 1, 0.5))` would work like
  129. # grid(color=(1, 1, 1, 0.5), alpha=rcParams['grid.alpha'])
  130. # so the that the rcParams default would override color alpha.
  131. grid_alpha = mpl.rcParams["grid.alpha"]
  132. grid_kw = {k[5:]: v for k, v in kwargs.items()}
  133. self.tick1line = mlines.Line2D(
  134. [], [],
  135. color=color, linestyle="none", zorder=zorder, visible=tick1On,
  136. markeredgecolor=color, markersize=size, markeredgewidth=width,
  137. )
  138. self.tick2line = mlines.Line2D(
  139. [], [],
  140. color=color, linestyle="none", zorder=zorder, visible=tick2On,
  141. markeredgecolor=color, markersize=size, markeredgewidth=width,
  142. )
  143. self.gridline = mlines.Line2D(
  144. [], [],
  145. color=grid_color, alpha=grid_alpha, visible=gridOn,
  146. linestyle=grid_linestyle, linewidth=grid_linewidth, marker="",
  147. **grid_kw,
  148. )
  149. self.gridline.get_path()._interpolation_steps = \
  150. GRIDLINE_INTERPOLATION_STEPS
  151. self.label1 = mtext.Text(
  152. np.nan, np.nan,
  153. fontsize=labelsize, color=labelcolor, visible=label1On,
  154. fontfamily=labelfontfamily, rotation=self._labelrotation[1])
  155. self.label2 = mtext.Text(
  156. np.nan, np.nan,
  157. fontsize=labelsize, color=labelcolor, visible=label2On,
  158. fontfamily=labelfontfamily, rotation=self._labelrotation[1])
  159. self._apply_tickdir(tickdir)
  160. for artist in [self.tick1line, self.tick2line, self.gridline,
  161. self.label1, self.label2]:
  162. self._set_artist_props(artist)
  163. self.update_position(loc)
  164. def _set_labelrotation(self, labelrotation):
  165. if isinstance(labelrotation, str):
  166. mode = labelrotation
  167. angle = 0
  168. elif isinstance(labelrotation, (tuple, list)):
  169. mode, angle = labelrotation
  170. else:
  171. mode = 'default'
  172. angle = labelrotation
  173. _api.check_in_list(['auto', 'default'], labelrotation=mode)
  174. self._labelrotation = (mode, angle)
  175. def _apply_tickdir(self, tickdir):
  176. """Set tick direction. Valid values are 'out', 'in', 'inout'."""
  177. # This method is responsible for updating `_pad`, and, in subclasses,
  178. # for setting the tick{1,2}line markers as well. From the user
  179. # perspective this should always be called though _apply_params, which
  180. # further updates ticklabel positions using the new pads.
  181. if tickdir is None:
  182. tickdir = mpl.rcParams[f'{self.__name__}.direction']
  183. else:
  184. _api.check_in_list(['in', 'out', 'inout'], tickdir=tickdir)
  185. self._tickdir = tickdir
  186. self._pad = self._base_pad + self.get_tick_padding()
  187. def get_tickdir(self):
  188. return self._tickdir
  189. def get_tick_padding(self):
  190. """Get the length of the tick outside of the Axes."""
  191. padding = {
  192. 'in': 0.0,
  193. 'inout': 0.5,
  194. 'out': 1.0
  195. }
  196. return self._size * padding[self._tickdir]
  197. def get_children(self):
  198. children = [self.tick1line, self.tick2line,
  199. self.gridline, self.label1, self.label2]
  200. return children
  201. @_api.rename_parameter("3.8", "clippath", "path")
  202. def set_clip_path(self, path, transform=None):
  203. # docstring inherited
  204. super().set_clip_path(path, transform)
  205. self.gridline.set_clip_path(path, transform)
  206. self.stale = True
  207. def contains(self, mouseevent):
  208. """
  209. Test whether the mouse event occurred in the Tick marks.
  210. This function always returns false. It is more useful to test if the
  211. axis as a whole contains the mouse rather than the set of tick marks.
  212. """
  213. return False, {}
  214. def set_pad(self, val):
  215. """
  216. Set the tick label pad in points
  217. Parameters
  218. ----------
  219. val : float
  220. """
  221. self._apply_params(pad=val)
  222. self.stale = True
  223. def get_pad(self):
  224. """Get the value of the tick label pad in points."""
  225. return self._base_pad
  226. def _get_text1(self):
  227. """Get the default Text 1 instance."""
  228. def _get_text2(self):
  229. """Get the default Text 2 instance."""
  230. def _get_tick1line(self):
  231. """Get the default `.Line2D` instance for tick1."""
  232. def _get_tick2line(self):
  233. """Get the default `.Line2D` instance for tick2."""
  234. def _get_gridline(self):
  235. """Get the default grid `.Line2D` instance for this tick."""
  236. def get_loc(self):
  237. """Return the tick location (data coords) as a scalar."""
  238. return self._loc
  239. @martist.allow_rasterization
  240. def draw(self, renderer):
  241. if not self.get_visible():
  242. self.stale = False
  243. return
  244. renderer.open_group(self.__name__, gid=self.get_gid())
  245. for artist in [self.gridline, self.tick1line, self.tick2line,
  246. self.label1, self.label2]:
  247. artist.draw(renderer)
  248. renderer.close_group(self.__name__)
  249. self.stale = False
  250. @_api.deprecated("3.8")
  251. def set_label1(self, s):
  252. """
  253. Set the label1 text.
  254. Parameters
  255. ----------
  256. s : str
  257. """
  258. self.label1.set_text(s)
  259. self.stale = True
  260. set_label = set_label1
  261. @_api.deprecated("3.8")
  262. def set_label2(self, s):
  263. """
  264. Set the label2 text.
  265. Parameters
  266. ----------
  267. s : str
  268. """
  269. self.label2.set_text(s)
  270. self.stale = True
  271. def set_url(self, url):
  272. """
  273. Set the url of label1 and label2.
  274. Parameters
  275. ----------
  276. url : str
  277. """
  278. super().set_url(url)
  279. self.label1.set_url(url)
  280. self.label2.set_url(url)
  281. self.stale = True
  282. def _set_artist_props(self, a):
  283. a.set_figure(self.figure)
  284. def get_view_interval(self):
  285. """
  286. Return the view limits ``(min, max)`` of the axis the tick belongs to.
  287. """
  288. raise NotImplementedError('Derived must override')
  289. def _apply_params(self, **kwargs):
  290. for name, target in [("gridOn", self.gridline),
  291. ("tick1On", self.tick1line),
  292. ("tick2On", self.tick2line),
  293. ("label1On", self.label1),
  294. ("label2On", self.label2)]:
  295. if name in kwargs:
  296. target.set_visible(kwargs.pop(name))
  297. if any(k in kwargs for k in ['size', 'width', 'pad', 'tickdir']):
  298. self._size = kwargs.pop('size', self._size)
  299. # Width could be handled outside this block, but it is
  300. # convenient to leave it here.
  301. self._width = kwargs.pop('width', self._width)
  302. self._base_pad = kwargs.pop('pad', self._base_pad)
  303. # _apply_tickdir uses _size and _base_pad to make _pad, and also
  304. # sets the ticklines markers.
  305. self._apply_tickdir(kwargs.pop('tickdir', self._tickdir))
  306. for line in (self.tick1line, self.tick2line):
  307. line.set_markersize(self._size)
  308. line.set_markeredgewidth(self._width)
  309. # _get_text1_transform uses _pad from _apply_tickdir.
  310. trans = self._get_text1_transform()[0]
  311. self.label1.set_transform(trans)
  312. trans = self._get_text2_transform()[0]
  313. self.label2.set_transform(trans)
  314. tick_kw = {k: v for k, v in kwargs.items() if k in ['color', 'zorder']}
  315. if 'color' in kwargs:
  316. tick_kw['markeredgecolor'] = kwargs['color']
  317. self.tick1line.set(**tick_kw)
  318. self.tick2line.set(**tick_kw)
  319. for k, v in tick_kw.items():
  320. setattr(self, '_' + k, v)
  321. if 'labelrotation' in kwargs:
  322. self._set_labelrotation(kwargs.pop('labelrotation'))
  323. self.label1.set(rotation=self._labelrotation[1])
  324. self.label2.set(rotation=self._labelrotation[1])
  325. label_kw = {k[5:]: v for k, v in kwargs.items()
  326. if k in ['labelsize', 'labelcolor', 'labelfontfamily']}
  327. self.label1.set(**label_kw)
  328. self.label2.set(**label_kw)
  329. grid_kw = {k[5:]: v for k, v in kwargs.items()
  330. if k in _gridline_param_names}
  331. self.gridline.set(**grid_kw)
  332. def update_position(self, loc):
  333. """Set the location of tick in data coords with scalar *loc*."""
  334. raise NotImplementedError('Derived must override')
  335. def _get_text1_transform(self):
  336. raise NotImplementedError('Derived must override')
  337. def _get_text2_transform(self):
  338. raise NotImplementedError('Derived must override')
  339. class XTick(Tick):
  340. """
  341. Contains all the Artists needed to make an x tick - the tick line,
  342. the label text and the grid line
  343. """
  344. __name__ = 'xtick'
  345. def __init__(self, *args, **kwargs):
  346. super().__init__(*args, **kwargs)
  347. # x in data coords, y in axes coords
  348. ax = self.axes
  349. self.tick1line.set(
  350. data=([0], [0]), transform=ax.get_xaxis_transform("tick1"))
  351. self.tick2line.set(
  352. data=([0], [1]), transform=ax.get_xaxis_transform("tick2"))
  353. self.gridline.set(
  354. data=([0, 0], [0, 1]), transform=ax.get_xaxis_transform("grid"))
  355. # the y loc is 3 points below the min of y axis
  356. trans, va, ha = self._get_text1_transform()
  357. self.label1.set(
  358. x=0, y=0,
  359. verticalalignment=va, horizontalalignment=ha, transform=trans,
  360. )
  361. trans, va, ha = self._get_text2_transform()
  362. self.label2.set(
  363. x=0, y=1,
  364. verticalalignment=va, horizontalalignment=ha, transform=trans,
  365. )
  366. def _get_text1_transform(self):
  367. return self.axes.get_xaxis_text1_transform(self._pad)
  368. def _get_text2_transform(self):
  369. return self.axes.get_xaxis_text2_transform(self._pad)
  370. def _apply_tickdir(self, tickdir):
  371. # docstring inherited
  372. super()._apply_tickdir(tickdir)
  373. mark1, mark2 = _MARKER_DICT[self._tickdir]
  374. self.tick1line.set_marker(mark1)
  375. self.tick2line.set_marker(mark2)
  376. def update_position(self, loc):
  377. """Set the location of tick in data coords with scalar *loc*."""
  378. self.tick1line.set_xdata((loc,))
  379. self.tick2line.set_xdata((loc,))
  380. self.gridline.set_xdata((loc,))
  381. self.label1.set_x(loc)
  382. self.label2.set_x(loc)
  383. self._loc = loc
  384. self.stale = True
  385. def get_view_interval(self):
  386. # docstring inherited
  387. return self.axes.viewLim.intervalx
  388. class YTick(Tick):
  389. """
  390. Contains all the Artists needed to make a Y tick - the tick line,
  391. the label text and the grid line
  392. """
  393. __name__ = 'ytick'
  394. def __init__(self, *args, **kwargs):
  395. super().__init__(*args, **kwargs)
  396. # x in axes coords, y in data coords
  397. ax = self.axes
  398. self.tick1line.set(
  399. data=([0], [0]), transform=ax.get_yaxis_transform("tick1"))
  400. self.tick2line.set(
  401. data=([1], [0]), transform=ax.get_yaxis_transform("tick2"))
  402. self.gridline.set(
  403. data=([0, 1], [0, 0]), transform=ax.get_yaxis_transform("grid"))
  404. # the y loc is 3 points below the min of y axis
  405. trans, va, ha = self._get_text1_transform()
  406. self.label1.set(
  407. x=0, y=0,
  408. verticalalignment=va, horizontalalignment=ha, transform=trans,
  409. )
  410. trans, va, ha = self._get_text2_transform()
  411. self.label2.set(
  412. x=1, y=0,
  413. verticalalignment=va, horizontalalignment=ha, transform=trans,
  414. )
  415. def _get_text1_transform(self):
  416. return self.axes.get_yaxis_text1_transform(self._pad)
  417. def _get_text2_transform(self):
  418. return self.axes.get_yaxis_text2_transform(self._pad)
  419. def _apply_tickdir(self, tickdir):
  420. # docstring inherited
  421. super()._apply_tickdir(tickdir)
  422. mark1, mark2 = {
  423. 'out': (mlines.TICKLEFT, mlines.TICKRIGHT),
  424. 'in': (mlines.TICKRIGHT, mlines.TICKLEFT),
  425. 'inout': ('_', '_'),
  426. }[self._tickdir]
  427. self.tick1line.set_marker(mark1)
  428. self.tick2line.set_marker(mark2)
  429. def update_position(self, loc):
  430. """Set the location of tick in data coords with scalar *loc*."""
  431. self.tick1line.set_ydata((loc,))
  432. self.tick2line.set_ydata((loc,))
  433. self.gridline.set_ydata((loc,))
  434. self.label1.set_y(loc)
  435. self.label2.set_y(loc)
  436. self._loc = loc
  437. self.stale = True
  438. def get_view_interval(self):
  439. # docstring inherited
  440. return self.axes.viewLim.intervaly
  441. class Ticker:
  442. """
  443. A container for the objects defining tick position and format.
  444. Attributes
  445. ----------
  446. locator : `~matplotlib.ticker.Locator` subclass
  447. Determines the positions of the ticks.
  448. formatter : `~matplotlib.ticker.Formatter` subclass
  449. Determines the format of the tick labels.
  450. """
  451. def __init__(self):
  452. self._locator = None
  453. self._formatter = None
  454. self._locator_is_default = True
  455. self._formatter_is_default = True
  456. @property
  457. def locator(self):
  458. return self._locator
  459. @locator.setter
  460. def locator(self, locator):
  461. if not isinstance(locator, mticker.Locator):
  462. raise TypeError('locator must be a subclass of '
  463. 'matplotlib.ticker.Locator')
  464. self._locator = locator
  465. @property
  466. def formatter(self):
  467. return self._formatter
  468. @formatter.setter
  469. def formatter(self, formatter):
  470. if not isinstance(formatter, mticker.Formatter):
  471. raise TypeError('formatter must be a subclass of '
  472. 'matplotlib.ticker.Formatter')
  473. self._formatter = formatter
  474. class _LazyTickList:
  475. """
  476. A descriptor for lazy instantiation of tick lists.
  477. See comment above definition of the ``majorTicks`` and ``minorTicks``
  478. attributes.
  479. """
  480. def __init__(self, major):
  481. self._major = major
  482. def __get__(self, instance, owner):
  483. if instance is None:
  484. return self
  485. else:
  486. # instance._get_tick() can itself try to access the majorTicks
  487. # attribute (e.g. in certain projection classes which override
  488. # e.g. get_xaxis_text1_transform). In order to avoid infinite
  489. # recursion, first set the majorTicks on the instance to an empty
  490. # list, then create the tick and append it.
  491. if self._major:
  492. instance.majorTicks = []
  493. tick = instance._get_tick(major=True)
  494. instance.majorTicks.append(tick)
  495. return instance.majorTicks
  496. else:
  497. instance.minorTicks = []
  498. tick = instance._get_tick(major=False)
  499. instance.minorTicks.append(tick)
  500. return instance.minorTicks
  501. class Axis(martist.Artist):
  502. """
  503. Base class for `.XAxis` and `.YAxis`.
  504. Attributes
  505. ----------
  506. isDefault_label : bool
  507. axes : `~matplotlib.axes.Axes`
  508. The `~.axes.Axes` to which the Axis belongs.
  509. major : `~matplotlib.axis.Ticker`
  510. Determines the major tick positions and their label format.
  511. minor : `~matplotlib.axis.Ticker`
  512. Determines the minor tick positions and their label format.
  513. callbacks : `~matplotlib.cbook.CallbackRegistry`
  514. label : `~matplotlib.text.Text`
  515. The axis label.
  516. labelpad : float
  517. The distance between the axis label and the tick labels.
  518. Defaults to :rc:`axes.labelpad` = 4.
  519. offsetText : `~matplotlib.text.Text`
  520. A `.Text` object containing the data offset of the ticks (if any).
  521. pickradius : float
  522. The acceptance radius for containment tests. See also `.Axis.contains`.
  523. majorTicks : list of `.Tick`
  524. The major ticks.
  525. .. warning::
  526. Ticks are not guaranteed to be persistent. Various operations
  527. can create, delete and modify the Tick instances. There is an
  528. imminent risk that changes to individual ticks will not
  529. survive if you work on the figure further (including also
  530. panning/zooming on a displayed figure).
  531. Working on the individual ticks is a method of last resort.
  532. Use `.set_tick_params` instead if possible.
  533. minorTicks : list of `.Tick`
  534. The minor ticks.
  535. """
  536. OFFSETTEXTPAD = 3
  537. # The class used in _get_tick() to create tick instances. Must either be
  538. # overwritten in subclasses, or subclasses must reimplement _get_tick().
  539. _tick_class = None
  540. def __str__(self):
  541. return "{}({},{})".format(
  542. type(self).__name__, *self.axes.transAxes.transform((0, 0)))
  543. def __init__(self, axes, *, pickradius=15, clear=True):
  544. """
  545. Parameters
  546. ----------
  547. axes : `~matplotlib.axes.Axes`
  548. The `~.axes.Axes` to which the created Axis belongs.
  549. pickradius : float
  550. The acceptance radius for containment tests. See also
  551. `.Axis.contains`.
  552. clear : bool, default: True
  553. Whether to clear the Axis on creation. This is not required, e.g., when
  554. creating an Axis as part of an Axes, as ``Axes.clear`` will call
  555. ``Axis.clear``.
  556. .. versionadded:: 3.8
  557. """
  558. super().__init__()
  559. self._remove_overlapping_locs = True
  560. self.set_figure(axes.figure)
  561. self.isDefault_label = True
  562. self.axes = axes
  563. self.major = Ticker()
  564. self.minor = Ticker()
  565. self.callbacks = cbook.CallbackRegistry(signals=["units"])
  566. self._autolabelpos = True
  567. self.label = mtext.Text(
  568. np.nan, np.nan,
  569. fontsize=mpl.rcParams['axes.labelsize'],
  570. fontweight=mpl.rcParams['axes.labelweight'],
  571. color=mpl.rcParams['axes.labelcolor'],
  572. )
  573. self._set_artist_props(self.label)
  574. self.offsetText = mtext.Text(np.nan, np.nan)
  575. self._set_artist_props(self.offsetText)
  576. self.labelpad = mpl.rcParams['axes.labelpad']
  577. self.pickradius = pickradius
  578. # Initialize here for testing; later add API
  579. self._major_tick_kw = dict()
  580. self._minor_tick_kw = dict()
  581. if clear:
  582. self.clear()
  583. else:
  584. self.converter = None
  585. self.units = None
  586. self._autoscale_on = True
  587. @property
  588. def isDefault_majloc(self):
  589. return self.major._locator_is_default
  590. @isDefault_majloc.setter
  591. def isDefault_majloc(self, value):
  592. self.major._locator_is_default = value
  593. @property
  594. def isDefault_majfmt(self):
  595. return self.major._formatter_is_default
  596. @isDefault_majfmt.setter
  597. def isDefault_majfmt(self, value):
  598. self.major._formatter_is_default = value
  599. @property
  600. def isDefault_minloc(self):
  601. return self.minor._locator_is_default
  602. @isDefault_minloc.setter
  603. def isDefault_minloc(self, value):
  604. self.minor._locator_is_default = value
  605. @property
  606. def isDefault_minfmt(self):
  607. return self.minor._formatter_is_default
  608. @isDefault_minfmt.setter
  609. def isDefault_minfmt(self, value):
  610. self.minor._formatter_is_default = value
  611. def _get_shared_axes(self):
  612. """Return Grouper of shared axes for current axis."""
  613. return self.axes._shared_axes[
  614. self._get_axis_name()].get_siblings(self.axes)
  615. def _get_shared_axis(self):
  616. """Return list of shared axis for current axis."""
  617. name = self._get_axis_name()
  618. return [ax._axis_map[name] for ax in self._get_shared_axes()]
  619. def _get_axis_name(self):
  620. """Return the axis name."""
  621. return [name for name, axis in self.axes._axis_map.items()
  622. if axis is self][0]
  623. # During initialization, Axis objects often create ticks that are later
  624. # unused; this turns out to be a very slow step. Instead, use a custom
  625. # descriptor to make the tick lists lazy and instantiate them as needed.
  626. majorTicks = _LazyTickList(major=True)
  627. minorTicks = _LazyTickList(major=False)
  628. def get_remove_overlapping_locs(self):
  629. return self._remove_overlapping_locs
  630. def set_remove_overlapping_locs(self, val):
  631. self._remove_overlapping_locs = bool(val)
  632. remove_overlapping_locs = property(
  633. get_remove_overlapping_locs, set_remove_overlapping_locs,
  634. doc=('If minor ticker locations that overlap with major '
  635. 'ticker locations should be trimmed.'))
  636. def set_label_coords(self, x, y, transform=None):
  637. """
  638. Set the coordinates of the label.
  639. By default, the x coordinate of the y label and the y coordinate of the
  640. x label are determined by the tick label bounding boxes, but this can
  641. lead to poor alignment of multiple labels if there are multiple axes.
  642. You can also specify the coordinate system of the label with the
  643. transform. If None, the default coordinate system will be the axes
  644. coordinate system: (0, 0) is bottom left, (0.5, 0.5) is center, etc.
  645. """
  646. self._autolabelpos = False
  647. if transform is None:
  648. transform = self.axes.transAxes
  649. self.label.set_transform(transform)
  650. self.label.set_position((x, y))
  651. self.stale = True
  652. def get_transform(self):
  653. """Return the transform used in the Axis' scale"""
  654. return self._scale.get_transform()
  655. def get_scale(self):
  656. """Return this Axis' scale (as a str)."""
  657. return self._scale.name
  658. def _set_scale(self, value, **kwargs):
  659. if not isinstance(value, mscale.ScaleBase):
  660. self._scale = mscale.scale_factory(value, self, **kwargs)
  661. else:
  662. self._scale = value
  663. self._scale.set_default_locators_and_formatters(self)
  664. self.isDefault_majloc = True
  665. self.isDefault_minloc = True
  666. self.isDefault_majfmt = True
  667. self.isDefault_minfmt = True
  668. # This method is directly wrapped by Axes.set_{x,y}scale.
  669. def _set_axes_scale(self, value, **kwargs):
  670. """
  671. Set this Axis' scale.
  672. Parameters
  673. ----------
  674. value : {"linear", "log", "symlog", "logit", ...} or `.ScaleBase`
  675. The axis scale type to apply.
  676. **kwargs
  677. Different keyword arguments are accepted, depending on the scale.
  678. See the respective class keyword arguments:
  679. - `matplotlib.scale.LinearScale`
  680. - `matplotlib.scale.LogScale`
  681. - `matplotlib.scale.SymmetricalLogScale`
  682. - `matplotlib.scale.LogitScale`
  683. - `matplotlib.scale.FuncScale`
  684. Notes
  685. -----
  686. By default, Matplotlib supports the above-mentioned scales.
  687. Additionally, custom scales may be registered using
  688. `matplotlib.scale.register_scale`. These scales can then also
  689. be used here.
  690. """
  691. name = self._get_axis_name()
  692. old_default_lims = (self.get_major_locator()
  693. .nonsingular(-np.inf, np.inf))
  694. for ax in self._get_shared_axes():
  695. ax._axis_map[name]._set_scale(value, **kwargs)
  696. ax._update_transScale()
  697. ax.stale = True
  698. new_default_lims = (self.get_major_locator()
  699. .nonsingular(-np.inf, np.inf))
  700. if old_default_lims != new_default_lims:
  701. # Force autoscaling now, to take advantage of the scale locator's
  702. # nonsingular() before it possibly gets swapped out by the user.
  703. self.axes.autoscale_view(
  704. **{f"scale{k}": k == name for k in self.axes._axis_names})
  705. def limit_range_for_scale(self, vmin, vmax):
  706. return self._scale.limit_range_for_scale(vmin, vmax, self.get_minpos())
  707. def _get_autoscale_on(self):
  708. """Return whether this Axis is autoscaled."""
  709. return self._autoscale_on
  710. def _set_autoscale_on(self, b):
  711. """
  712. Set whether this Axis is autoscaled when drawing or by
  713. `.Axes.autoscale_view`.
  714. Parameters
  715. ----------
  716. b : bool
  717. """
  718. self._autoscale_on = b
  719. def get_children(self):
  720. return [self.label, self.offsetText,
  721. *self.get_major_ticks(), *self.get_minor_ticks()]
  722. def _reset_major_tick_kw(self):
  723. self._major_tick_kw.clear()
  724. self._major_tick_kw['gridOn'] = (
  725. mpl.rcParams['axes.grid'] and
  726. mpl.rcParams['axes.grid.which'] in ('both', 'major'))
  727. def _reset_minor_tick_kw(self):
  728. self._minor_tick_kw.clear()
  729. self._minor_tick_kw['gridOn'] = (
  730. mpl.rcParams['axes.grid'] and
  731. mpl.rcParams['axes.grid.which'] in ('both', 'minor'))
  732. def clear(self):
  733. """
  734. Clear the axis.
  735. This resets axis properties to their default values:
  736. - the label
  737. - the scale
  738. - locators, formatters and ticks
  739. - major and minor grid
  740. - units
  741. - registered callbacks
  742. """
  743. self.label._reset_visual_defaults()
  744. # The above resets the label formatting using text rcParams,
  745. # so we then update the formatting using axes rcParams
  746. self.label.set_color(mpl.rcParams['axes.labelcolor'])
  747. self.label.set_fontsize(mpl.rcParams['axes.labelsize'])
  748. self.label.set_fontweight(mpl.rcParams['axes.labelweight'])
  749. self.offsetText._reset_visual_defaults()
  750. self.labelpad = mpl.rcParams['axes.labelpad']
  751. self._init()
  752. self._set_scale('linear')
  753. # Clear the callback registry for this axis, or it may "leak"
  754. self.callbacks = cbook.CallbackRegistry(signals=["units"])
  755. # whether the grids are on
  756. self._major_tick_kw['gridOn'] = (
  757. mpl.rcParams['axes.grid'] and
  758. mpl.rcParams['axes.grid.which'] in ('both', 'major'))
  759. self._minor_tick_kw['gridOn'] = (
  760. mpl.rcParams['axes.grid'] and
  761. mpl.rcParams['axes.grid.which'] in ('both', 'minor'))
  762. self.reset_ticks()
  763. self.converter = None
  764. self.units = None
  765. self.stale = True
  766. def reset_ticks(self):
  767. """
  768. Re-initialize the major and minor Tick lists.
  769. Each list starts with a single fresh Tick.
  770. """
  771. # Restore the lazy tick lists.
  772. try:
  773. del self.majorTicks
  774. except AttributeError:
  775. pass
  776. try:
  777. del self.minorTicks
  778. except AttributeError:
  779. pass
  780. try:
  781. self.set_clip_path(self.axes.patch)
  782. except AttributeError:
  783. pass
  784. def set_tick_params(self, which='major', reset=False, **kwargs):
  785. """
  786. Set appearance parameters for ticks, ticklabels, and gridlines.
  787. For documentation of keyword arguments, see
  788. :meth:`matplotlib.axes.Axes.tick_params`.
  789. See Also
  790. --------
  791. .Axis.get_tick_params
  792. View the current style settings for ticks, ticklabels, and
  793. gridlines.
  794. """
  795. _api.check_in_list(['major', 'minor', 'both'], which=which)
  796. kwtrans = self._translate_tick_params(kwargs)
  797. # the kwargs are stored in self._major/minor_tick_kw so that any
  798. # future new ticks will automatically get them
  799. if reset:
  800. if which in ['major', 'both']:
  801. self._reset_major_tick_kw()
  802. self._major_tick_kw.update(kwtrans)
  803. if which in ['minor', 'both']:
  804. self._reset_minor_tick_kw()
  805. self._minor_tick_kw.update(kwtrans)
  806. self.reset_ticks()
  807. else:
  808. if which in ['major', 'both']:
  809. self._major_tick_kw.update(kwtrans)
  810. for tick in self.majorTicks:
  811. tick._apply_params(**kwtrans)
  812. if which in ['minor', 'both']:
  813. self._minor_tick_kw.update(kwtrans)
  814. for tick in self.minorTicks:
  815. tick._apply_params(**kwtrans)
  816. # labelOn and labelcolor also apply to the offset text.
  817. if 'label1On' in kwtrans or 'label2On' in kwtrans:
  818. self.offsetText.set_visible(
  819. self._major_tick_kw.get('label1On', False)
  820. or self._major_tick_kw.get('label2On', False))
  821. if 'labelcolor' in kwtrans:
  822. self.offsetText.set_color(kwtrans['labelcolor'])
  823. self.stale = True
  824. def get_tick_params(self, which='major'):
  825. """
  826. Get appearance parameters for ticks, ticklabels, and gridlines.
  827. .. versionadded:: 3.7
  828. Parameters
  829. ----------
  830. which : {'major', 'minor'}, default: 'major'
  831. The group of ticks for which the parameters are retrieved.
  832. Returns
  833. -------
  834. dict
  835. Properties for styling tick elements added to the axis.
  836. Notes
  837. -----
  838. This method returns the appearance parameters for styling *new*
  839. elements added to this axis and may be different from the values
  840. on current elements if they were modified directly by the user
  841. (e.g., via ``set_*`` methods on individual tick objects).
  842. Examples
  843. --------
  844. ::
  845. >>> ax.yaxis.set_tick_params(labelsize=30, labelcolor='red',
  846. direction='out', which='major')
  847. >>> ax.yaxis.get_tick_params(which='major')
  848. {'direction': 'out',
  849. 'left': True,
  850. 'right': False,
  851. 'labelleft': True,
  852. 'labelright': False,
  853. 'gridOn': False,
  854. 'labelsize': 30,
  855. 'labelcolor': 'red'}
  856. >>> ax.yaxis.get_tick_params(which='minor')
  857. {'left': True,
  858. 'right': False,
  859. 'labelleft': True,
  860. 'labelright': False,
  861. 'gridOn': False}
  862. """
  863. _api.check_in_list(['major', 'minor'], which=which)
  864. if which == 'major':
  865. return self._translate_tick_params(
  866. self._major_tick_kw, reverse=True
  867. )
  868. return self._translate_tick_params(self._minor_tick_kw, reverse=True)
  869. @staticmethod
  870. def _translate_tick_params(kw, reverse=False):
  871. """
  872. Translate the kwargs supported by `.Axis.set_tick_params` to kwargs
  873. supported by `.Tick._apply_params`.
  874. In particular, this maps axis specific names like 'top', 'left'
  875. to the generic tick1, tick2 logic of the axis. Additionally, there
  876. are some other name translations.
  877. Returns a new dict of translated kwargs.
  878. Note: Use reverse=True to translate from those supported by
  879. `.Tick._apply_params` back to those supported by
  880. `.Axis.set_tick_params`.
  881. """
  882. kw_ = {**kw}
  883. # The following lists may be moved to a more accessible location.
  884. allowed_keys = [
  885. 'size', 'width', 'color', 'tickdir', 'pad',
  886. 'labelsize', 'labelcolor', 'labelfontfamily', 'zorder', 'gridOn',
  887. 'tick1On', 'tick2On', 'label1On', 'label2On',
  888. 'length', 'direction', 'left', 'bottom', 'right', 'top',
  889. 'labelleft', 'labelbottom', 'labelright', 'labeltop',
  890. 'labelrotation',
  891. *_gridline_param_names]
  892. keymap = {
  893. # tick_params key -> axis key
  894. 'length': 'size',
  895. 'direction': 'tickdir',
  896. 'rotation': 'labelrotation',
  897. 'left': 'tick1On',
  898. 'bottom': 'tick1On',
  899. 'right': 'tick2On',
  900. 'top': 'tick2On',
  901. 'labelleft': 'label1On',
  902. 'labelbottom': 'label1On',
  903. 'labelright': 'label2On',
  904. 'labeltop': 'label2On',
  905. }
  906. if reverse:
  907. kwtrans = {
  908. oldkey: kw_.pop(newkey)
  909. for oldkey, newkey in keymap.items() if newkey in kw_
  910. }
  911. else:
  912. kwtrans = {
  913. newkey: kw_.pop(oldkey)
  914. for oldkey, newkey in keymap.items() if oldkey in kw_
  915. }
  916. if 'colors' in kw_:
  917. c = kw_.pop('colors')
  918. kwtrans['color'] = c
  919. kwtrans['labelcolor'] = c
  920. # Maybe move the checking up to the caller of this method.
  921. for key in kw_:
  922. if key not in allowed_keys:
  923. raise ValueError(
  924. "keyword %s is not recognized; valid keywords are %s"
  925. % (key, allowed_keys))
  926. kwtrans.update(kw_)
  927. return kwtrans
  928. @_api.rename_parameter("3.8", "clippath", "path")
  929. def set_clip_path(self, path, transform=None):
  930. super().set_clip_path(path, transform)
  931. for child in self.majorTicks + self.minorTicks:
  932. child.set_clip_path(path, transform)
  933. self.stale = True
  934. def get_view_interval(self):
  935. """Return the ``(min, max)`` view limits of this axis."""
  936. raise NotImplementedError('Derived must override')
  937. def set_view_interval(self, vmin, vmax, ignore=False):
  938. """
  939. Set the axis view limits. This method is for internal use; Matplotlib
  940. users should typically use e.g. `~.Axes.set_xlim` or `~.Axes.set_ylim`.
  941. If *ignore* is False (the default), this method will never reduce the
  942. preexisting view limits, only expand them if *vmin* or *vmax* are not
  943. within them. Moreover, the order of *vmin* and *vmax* does not matter;
  944. the orientation of the axis will not change.
  945. If *ignore* is True, the view limits will be set exactly to ``(vmin,
  946. vmax)`` in that order.
  947. """
  948. raise NotImplementedError('Derived must override')
  949. def get_data_interval(self):
  950. """Return the ``(min, max)`` data limits of this axis."""
  951. raise NotImplementedError('Derived must override')
  952. def set_data_interval(self, vmin, vmax, ignore=False):
  953. """
  954. Set the axis data limits. This method is for internal use.
  955. If *ignore* is False (the default), this method will never reduce the
  956. preexisting data limits, only expand them if *vmin* or *vmax* are not
  957. within them. Moreover, the order of *vmin* and *vmax* does not matter;
  958. the orientation of the axis will not change.
  959. If *ignore* is True, the data limits will be set exactly to ``(vmin,
  960. vmax)`` in that order.
  961. """
  962. raise NotImplementedError('Derived must override')
  963. def get_inverted(self):
  964. """
  965. Return whether this Axis is oriented in the "inverse" direction.
  966. The "normal" direction is increasing to the right for the x-axis and to
  967. the top for the y-axis; the "inverse" direction is increasing to the
  968. left for the x-axis and to the bottom for the y-axis.
  969. """
  970. low, high = self.get_view_interval()
  971. return high < low
  972. def set_inverted(self, inverted):
  973. """
  974. Set whether this Axis is oriented in the "inverse" direction.
  975. The "normal" direction is increasing to the right for the x-axis and to
  976. the top for the y-axis; the "inverse" direction is increasing to the
  977. left for the x-axis and to the bottom for the y-axis.
  978. """
  979. a, b = self.get_view_interval()
  980. # cast to bool to avoid bad interaction between python 3.8 and np.bool_
  981. self._set_lim(*sorted((a, b), reverse=bool(inverted)), auto=None)
  982. def set_default_intervals(self):
  983. """
  984. Set the default limits for the axis data and view interval if they
  985. have not been not mutated yet.
  986. """
  987. # this is mainly in support of custom object plotting. For
  988. # example, if someone passes in a datetime object, we do not
  989. # know automagically how to set the default min/max of the
  990. # data and view limits. The unit conversion AxisInfo
  991. # interface provides a hook for custom types to register
  992. # default limits through the AxisInfo.default_limits
  993. # attribute, and the derived code below will check for that
  994. # and use it if it's available (else just use 0..1)
  995. def _set_lim(self, v0, v1, *, emit=True, auto):
  996. """
  997. Set view limits.
  998. This method is a helper for the Axes ``set_xlim``, ``set_ylim``, and
  999. ``set_zlim`` methods.
  1000. Parameters
  1001. ----------
  1002. v0, v1 : float
  1003. The view limits. (Passing *v0* as a (low, high) pair is not
  1004. supported; normalization must occur in the Axes setters.)
  1005. emit : bool, default: True
  1006. Whether to notify observers of limit change.
  1007. auto : bool or None, default: False
  1008. Whether to turn on autoscaling of the x-axis. True turns on, False
  1009. turns off, None leaves unchanged.
  1010. """
  1011. name = self._get_axis_name()
  1012. self.axes._process_unit_info([(name, (v0, v1))], convert=False)
  1013. v0 = self.axes._validate_converted_limits(v0, self.convert_units)
  1014. v1 = self.axes._validate_converted_limits(v1, self.convert_units)
  1015. if v0 is None or v1 is None:
  1016. # Axes init calls set_xlim(0, 1) before get_xlim() can be called,
  1017. # so only grab the limits if we really need them.
  1018. old0, old1 = self.get_view_interval()
  1019. if v0 is None:
  1020. v0 = old0
  1021. if v1 is None:
  1022. v1 = old1
  1023. if self.get_scale() == 'log' and (v0 <= 0 or v1 <= 0):
  1024. # Axes init calls set_xlim(0, 1) before get_xlim() can be called,
  1025. # so only grab the limits if we really need them.
  1026. old0, old1 = self.get_view_interval()
  1027. if v0 <= 0:
  1028. _api.warn_external(f"Attempt to set non-positive {name}lim on "
  1029. f"a log-scaled axis will be ignored.")
  1030. v0 = old0
  1031. if v1 <= 0:
  1032. _api.warn_external(f"Attempt to set non-positive {name}lim on "
  1033. f"a log-scaled axis will be ignored.")
  1034. v1 = old1
  1035. if v0 == v1:
  1036. _api.warn_external(
  1037. f"Attempting to set identical low and high {name}lims "
  1038. f"makes transformation singular; automatically expanding.")
  1039. reverse = bool(v0 > v1) # explicit cast needed for python3.8+np.bool_.
  1040. v0, v1 = self.get_major_locator().nonsingular(v0, v1)
  1041. v0, v1 = self.limit_range_for_scale(v0, v1)
  1042. v0, v1 = sorted([v0, v1], reverse=bool(reverse))
  1043. self.set_view_interval(v0, v1, ignore=True)
  1044. # Mark viewlims as no longer stale without triggering an autoscale.
  1045. for ax in self._get_shared_axes():
  1046. ax._stale_viewlims[name] = False
  1047. if auto is not None:
  1048. self._set_autoscale_on(bool(auto))
  1049. if emit:
  1050. self.axes.callbacks.process(f"{name}lim_changed", self.axes)
  1051. # Call all of the other axes that are shared with this one
  1052. for other in self._get_shared_axes():
  1053. if other is self.axes:
  1054. continue
  1055. other._axis_map[name]._set_lim(v0, v1, emit=False, auto=auto)
  1056. if emit:
  1057. other.callbacks.process(f"{name}lim_changed", other)
  1058. if other.figure != self.figure:
  1059. other.figure.canvas.draw_idle()
  1060. self.stale = True
  1061. return v0, v1
  1062. def _set_artist_props(self, a):
  1063. if a is None:
  1064. return
  1065. a.set_figure(self.figure)
  1066. def _update_ticks(self):
  1067. """
  1068. Update ticks (position and labels) using the current data interval of
  1069. the axes. Return the list of ticks that will be drawn.
  1070. """
  1071. major_locs = self.get_majorticklocs()
  1072. major_labels = self.major.formatter.format_ticks(major_locs)
  1073. major_ticks = self.get_major_ticks(len(major_locs))
  1074. for tick, loc, label in zip(major_ticks, major_locs, major_labels):
  1075. tick.update_position(loc)
  1076. tick.label1.set_text(label)
  1077. tick.label2.set_text(label)
  1078. minor_locs = self.get_minorticklocs()
  1079. minor_labels = self.minor.formatter.format_ticks(minor_locs)
  1080. minor_ticks = self.get_minor_ticks(len(minor_locs))
  1081. for tick, loc, label in zip(minor_ticks, minor_locs, minor_labels):
  1082. tick.update_position(loc)
  1083. tick.label1.set_text(label)
  1084. tick.label2.set_text(label)
  1085. ticks = [*major_ticks, *minor_ticks]
  1086. view_low, view_high = self.get_view_interval()
  1087. if view_low > view_high:
  1088. view_low, view_high = view_high, view_low
  1089. interval_t = self.get_transform().transform([view_low, view_high])
  1090. ticks_to_draw = []
  1091. for tick in ticks:
  1092. try:
  1093. loc_t = self.get_transform().transform(tick.get_loc())
  1094. except AssertionError:
  1095. # transforms.transform doesn't allow masked values but
  1096. # some scales might make them, so we need this try/except.
  1097. pass
  1098. else:
  1099. if mtransforms._interval_contains_close(interval_t, loc_t):
  1100. ticks_to_draw.append(tick)
  1101. return ticks_to_draw
  1102. def _get_ticklabel_bboxes(self, ticks, renderer=None):
  1103. """Return lists of bboxes for ticks' label1's and label2's."""
  1104. if renderer is None:
  1105. renderer = self.figure._get_renderer()
  1106. return ([tick.label1.get_window_extent(renderer)
  1107. for tick in ticks if tick.label1.get_visible()],
  1108. [tick.label2.get_window_extent(renderer)
  1109. for tick in ticks if tick.label2.get_visible()])
  1110. def get_tightbbox(self, renderer=None, *, for_layout_only=False):
  1111. """
  1112. Return a bounding box that encloses the axis. It only accounts
  1113. tick labels, axis label, and offsetText.
  1114. If *for_layout_only* is True, then the width of the label (if this
  1115. is an x-axis) or the height of the label (if this is a y-axis) is
  1116. collapsed to near zero. This allows tight/constrained_layout to ignore
  1117. too-long labels when doing their layout.
  1118. """
  1119. if not self.get_visible():
  1120. return
  1121. if renderer is None:
  1122. renderer = self.figure._get_renderer()
  1123. ticks_to_draw = self._update_ticks()
  1124. self._update_label_position(renderer)
  1125. # go back to just this axis's tick labels
  1126. tlb1, tlb2 = self._get_ticklabel_bboxes(ticks_to_draw, renderer)
  1127. self._update_offset_text_position(tlb1, tlb2)
  1128. self.offsetText.set_text(self.major.formatter.get_offset())
  1129. bboxes = [
  1130. *(a.get_window_extent(renderer)
  1131. for a in [self.offsetText]
  1132. if a.get_visible()),
  1133. *tlb1, *tlb2,
  1134. ]
  1135. # take care of label
  1136. if self.label.get_visible():
  1137. bb = self.label.get_window_extent(renderer)
  1138. # for constrained/tight_layout, we want to ignore the label's
  1139. # width/height because the adjustments they make can't be improved.
  1140. # this code collapses the relevant direction
  1141. if for_layout_only:
  1142. if self.axis_name == "x" and bb.width > 0:
  1143. bb.x0 = (bb.x0 + bb.x1) / 2 - 0.5
  1144. bb.x1 = bb.x0 + 1.0
  1145. if self.axis_name == "y" and bb.height > 0:
  1146. bb.y0 = (bb.y0 + bb.y1) / 2 - 0.5
  1147. bb.y1 = bb.y0 + 1.0
  1148. bboxes.append(bb)
  1149. bboxes = [b for b in bboxes
  1150. if 0 < b.width < np.inf and 0 < b.height < np.inf]
  1151. if bboxes:
  1152. return mtransforms.Bbox.union(bboxes)
  1153. else:
  1154. return None
  1155. def get_tick_padding(self):
  1156. values = []
  1157. if len(self.majorTicks):
  1158. values.append(self.majorTicks[0].get_tick_padding())
  1159. if len(self.minorTicks):
  1160. values.append(self.minorTicks[0].get_tick_padding())
  1161. return max(values, default=0)
  1162. @martist.allow_rasterization
  1163. def draw(self, renderer, *args, **kwargs):
  1164. # docstring inherited
  1165. if not self.get_visible():
  1166. return
  1167. renderer.open_group(__name__, gid=self.get_gid())
  1168. ticks_to_draw = self._update_ticks()
  1169. tlb1, tlb2 = self._get_ticklabel_bboxes(ticks_to_draw, renderer)
  1170. for tick in ticks_to_draw:
  1171. tick.draw(renderer)
  1172. # Shift label away from axes to avoid overlapping ticklabels.
  1173. self._update_label_position(renderer)
  1174. self.label.draw(renderer)
  1175. self._update_offset_text_position(tlb1, tlb2)
  1176. self.offsetText.set_text(self.major.formatter.get_offset())
  1177. self.offsetText.draw(renderer)
  1178. renderer.close_group(__name__)
  1179. self.stale = False
  1180. def get_gridlines(self):
  1181. r"""Return this Axis' grid lines as a list of `.Line2D`\s."""
  1182. ticks = self.get_major_ticks()
  1183. return cbook.silent_list('Line2D gridline',
  1184. [tick.gridline for tick in ticks])
  1185. def get_label(self):
  1186. """Return the axis label as a Text instance."""
  1187. return self.label
  1188. def get_offset_text(self):
  1189. """Return the axis offsetText as a Text instance."""
  1190. return self.offsetText
  1191. def get_pickradius(self):
  1192. """Return the depth of the axis used by the picker."""
  1193. return self._pickradius
  1194. def get_majorticklabels(self):
  1195. """Return this Axis' major tick labels, as a list of `~.text.Text`."""
  1196. self._update_ticks()
  1197. ticks = self.get_major_ticks()
  1198. labels1 = [tick.label1 for tick in ticks if tick.label1.get_visible()]
  1199. labels2 = [tick.label2 for tick in ticks if tick.label2.get_visible()]
  1200. return labels1 + labels2
  1201. def get_minorticklabels(self):
  1202. """Return this Axis' minor tick labels, as a list of `~.text.Text`."""
  1203. self._update_ticks()
  1204. ticks = self.get_minor_ticks()
  1205. labels1 = [tick.label1 for tick in ticks if tick.label1.get_visible()]
  1206. labels2 = [tick.label2 for tick in ticks if tick.label2.get_visible()]
  1207. return labels1 + labels2
  1208. def get_ticklabels(self, minor=False, which=None):
  1209. """
  1210. Get this Axis' tick labels.
  1211. Parameters
  1212. ----------
  1213. minor : bool
  1214. Whether to return the minor or the major ticklabels.
  1215. which : None, ('minor', 'major', 'both')
  1216. Overrides *minor*.
  1217. Selects which ticklabels to return
  1218. Returns
  1219. -------
  1220. list of `~matplotlib.text.Text`
  1221. """
  1222. if which is not None:
  1223. if which == 'minor':
  1224. return self.get_minorticklabels()
  1225. elif which == 'major':
  1226. return self.get_majorticklabels()
  1227. elif which == 'both':
  1228. return self.get_majorticklabels() + self.get_minorticklabels()
  1229. else:
  1230. _api.check_in_list(['major', 'minor', 'both'], which=which)
  1231. if minor:
  1232. return self.get_minorticklabels()
  1233. return self.get_majorticklabels()
  1234. def get_majorticklines(self):
  1235. r"""Return this Axis' major tick lines as a list of `.Line2D`\s."""
  1236. lines = []
  1237. ticks = self.get_major_ticks()
  1238. for tick in ticks:
  1239. lines.append(tick.tick1line)
  1240. lines.append(tick.tick2line)
  1241. return cbook.silent_list('Line2D ticklines', lines)
  1242. def get_minorticklines(self):
  1243. r"""Return this Axis' minor tick lines as a list of `.Line2D`\s."""
  1244. lines = []
  1245. ticks = self.get_minor_ticks()
  1246. for tick in ticks:
  1247. lines.append(tick.tick1line)
  1248. lines.append(tick.tick2line)
  1249. return cbook.silent_list('Line2D ticklines', lines)
  1250. def get_ticklines(self, minor=False):
  1251. r"""Return this Axis' tick lines as a list of `.Line2D`\s."""
  1252. if minor:
  1253. return self.get_minorticklines()
  1254. return self.get_majorticklines()
  1255. def get_majorticklocs(self):
  1256. """Return this Axis' major tick locations in data coordinates."""
  1257. return self.major.locator()
  1258. def get_minorticklocs(self):
  1259. """Return this Axis' minor tick locations in data coordinates."""
  1260. # Remove minor ticks duplicating major ticks.
  1261. minor_locs = np.asarray(self.minor.locator())
  1262. if self.remove_overlapping_locs:
  1263. major_locs = self.major.locator()
  1264. transform = self._scale.get_transform()
  1265. tr_minor_locs = transform.transform(minor_locs)
  1266. tr_major_locs = transform.transform(major_locs)
  1267. lo, hi = sorted(transform.transform(self.get_view_interval()))
  1268. # Use the transformed view limits as scale. 1e-5 is the default
  1269. # rtol for np.isclose.
  1270. tol = (hi - lo) * 1e-5
  1271. mask = np.isclose(tr_minor_locs[:, None], tr_major_locs[None, :],
  1272. atol=tol, rtol=0).any(axis=1)
  1273. minor_locs = minor_locs[~mask]
  1274. return minor_locs
  1275. def get_ticklocs(self, *, minor=False):
  1276. """
  1277. Return this Axis' tick locations in data coordinates.
  1278. The locations are not clipped to the current axis limits and hence
  1279. may contain locations that are not visible in the output.
  1280. Parameters
  1281. ----------
  1282. minor : bool, default: False
  1283. True to return the minor tick directions,
  1284. False to return the major tick directions.
  1285. Returns
  1286. -------
  1287. array of tick locations
  1288. """
  1289. return self.get_minorticklocs() if minor else self.get_majorticklocs()
  1290. def get_ticks_direction(self, minor=False):
  1291. """
  1292. Return an array of this Axis' tick directions.
  1293. Parameters
  1294. ----------
  1295. minor : bool, default: False
  1296. True to return the minor tick directions,
  1297. False to return the major tick directions.
  1298. Returns
  1299. -------
  1300. array of tick directions
  1301. """
  1302. if minor:
  1303. return np.array(
  1304. [tick._tickdir for tick in self.get_minor_ticks()])
  1305. else:
  1306. return np.array(
  1307. [tick._tickdir for tick in self.get_major_ticks()])
  1308. def _get_tick(self, major):
  1309. """Return the default tick instance."""
  1310. if self._tick_class is None:
  1311. raise NotImplementedError(
  1312. f"The Axis subclass {self.__class__.__name__} must define "
  1313. "_tick_class or reimplement _get_tick()")
  1314. tick_kw = self._major_tick_kw if major else self._minor_tick_kw
  1315. return self._tick_class(self.axes, 0, major=major, **tick_kw)
  1316. def _get_tick_label_size(self, axis_name):
  1317. """
  1318. Return the text size of tick labels for this Axis.
  1319. This is a convenience function to avoid having to create a `Tick` in
  1320. `.get_tick_space`, since it is expensive.
  1321. """
  1322. tick_kw = self._major_tick_kw
  1323. size = tick_kw.get('labelsize',
  1324. mpl.rcParams[f'{axis_name}tick.labelsize'])
  1325. return mtext.FontProperties(size=size).get_size_in_points()
  1326. def _copy_tick_props(self, src, dest):
  1327. """Copy the properties from *src* tick to *dest* tick."""
  1328. if src is None or dest is None:
  1329. return
  1330. dest.label1.update_from(src.label1)
  1331. dest.label2.update_from(src.label2)
  1332. dest.tick1line.update_from(src.tick1line)
  1333. dest.tick2line.update_from(src.tick2line)
  1334. dest.gridline.update_from(src.gridline)
  1335. def get_label_text(self):
  1336. """Get the text of the label."""
  1337. return self.label.get_text()
  1338. def get_major_locator(self):
  1339. """Get the locator of the major ticker."""
  1340. return self.major.locator
  1341. def get_minor_locator(self):
  1342. """Get the locator of the minor ticker."""
  1343. return self.minor.locator
  1344. def get_major_formatter(self):
  1345. """Get the formatter of the major ticker."""
  1346. return self.major.formatter
  1347. def get_minor_formatter(self):
  1348. """Get the formatter of the minor ticker."""
  1349. return self.minor.formatter
  1350. def get_major_ticks(self, numticks=None):
  1351. r"""
  1352. Return the list of major `.Tick`\s.
  1353. .. warning::
  1354. Ticks are not guaranteed to be persistent. Various operations
  1355. can create, delete and modify the Tick instances. There is an
  1356. imminent risk that changes to individual ticks will not
  1357. survive if you work on the figure further (including also
  1358. panning/zooming on a displayed figure).
  1359. Working on the individual ticks is a method of last resort.
  1360. Use `.set_tick_params` instead if possible.
  1361. """
  1362. if numticks is None:
  1363. numticks = len(self.get_majorticklocs())
  1364. while len(self.majorTicks) < numticks:
  1365. # Update the new tick label properties from the old.
  1366. tick = self._get_tick(major=True)
  1367. self.majorTicks.append(tick)
  1368. self._copy_tick_props(self.majorTicks[0], tick)
  1369. return self.majorTicks[:numticks]
  1370. def get_minor_ticks(self, numticks=None):
  1371. r"""
  1372. Return the list of minor `.Tick`\s.
  1373. .. warning::
  1374. Ticks are not guaranteed to be persistent. Various operations
  1375. can create, delete and modify the Tick instances. There is an
  1376. imminent risk that changes to individual ticks will not
  1377. survive if you work on the figure further (including also
  1378. panning/zooming on a displayed figure).
  1379. Working on the individual ticks is a method of last resort.
  1380. Use `.set_tick_params` instead if possible.
  1381. """
  1382. if numticks is None:
  1383. numticks = len(self.get_minorticklocs())
  1384. while len(self.minorTicks) < numticks:
  1385. # Update the new tick label properties from the old.
  1386. tick = self._get_tick(major=False)
  1387. self.minorTicks.append(tick)
  1388. self._copy_tick_props(self.minorTicks[0], tick)
  1389. return self.minorTicks[:numticks]
  1390. def grid(self, visible=None, which='major', **kwargs):
  1391. """
  1392. Configure the grid lines.
  1393. Parameters
  1394. ----------
  1395. visible : bool or None
  1396. Whether to show the grid lines. If any *kwargs* are supplied, it
  1397. is assumed you want the grid on and *visible* will be set to True.
  1398. If *visible* is *None* and there are no *kwargs*, this toggles the
  1399. visibility of the lines.
  1400. which : {'major', 'minor', 'both'}
  1401. The grid lines to apply the changes on.
  1402. **kwargs : `~matplotlib.lines.Line2D` properties
  1403. Define the line properties of the grid, e.g.::
  1404. grid(color='r', linestyle='-', linewidth=2)
  1405. """
  1406. if kwargs:
  1407. if visible is None:
  1408. visible = True
  1409. elif not visible: # something false-like but not None
  1410. _api.warn_external('First parameter to grid() is false, '
  1411. 'but line properties are supplied. The '
  1412. 'grid will be enabled.')
  1413. visible = True
  1414. which = which.lower()
  1415. _api.check_in_list(['major', 'minor', 'both'], which=which)
  1416. gridkw = {f'grid_{name}': value for name, value in kwargs.items()}
  1417. if which in ['minor', 'both']:
  1418. gridkw['gridOn'] = (not self._minor_tick_kw['gridOn']
  1419. if visible is None else visible)
  1420. self.set_tick_params(which='minor', **gridkw)
  1421. if which in ['major', 'both']:
  1422. gridkw['gridOn'] = (not self._major_tick_kw['gridOn']
  1423. if visible is None else visible)
  1424. self.set_tick_params(which='major', **gridkw)
  1425. self.stale = True
  1426. def update_units(self, data):
  1427. """
  1428. Introspect *data* for units converter and update the
  1429. ``axis.converter`` instance if necessary. Return *True*
  1430. if *data* is registered for unit conversion.
  1431. """
  1432. converter = munits.registry.get_converter(data)
  1433. if converter is None:
  1434. return False
  1435. neednew = self.converter != converter
  1436. self.converter = converter
  1437. default = self.converter.default_units(data, self)
  1438. if default is not None and self.units is None:
  1439. self.set_units(default)
  1440. elif neednew:
  1441. self._update_axisinfo()
  1442. self.stale = True
  1443. return True
  1444. def _update_axisinfo(self):
  1445. """
  1446. Check the axis converter for the stored units to see if the
  1447. axis info needs to be updated.
  1448. """
  1449. if self.converter is None:
  1450. return
  1451. info = self.converter.axisinfo(self.units, self)
  1452. if info is None:
  1453. return
  1454. if info.majloc is not None and \
  1455. self.major.locator != info.majloc and self.isDefault_majloc:
  1456. self.set_major_locator(info.majloc)
  1457. self.isDefault_majloc = True
  1458. if info.minloc is not None and \
  1459. self.minor.locator != info.minloc and self.isDefault_minloc:
  1460. self.set_minor_locator(info.minloc)
  1461. self.isDefault_minloc = True
  1462. if info.majfmt is not None and \
  1463. self.major.formatter != info.majfmt and self.isDefault_majfmt:
  1464. self.set_major_formatter(info.majfmt)
  1465. self.isDefault_majfmt = True
  1466. if info.minfmt is not None and \
  1467. self.minor.formatter != info.minfmt and self.isDefault_minfmt:
  1468. self.set_minor_formatter(info.minfmt)
  1469. self.isDefault_minfmt = True
  1470. if info.label is not None and self.isDefault_label:
  1471. self.set_label_text(info.label)
  1472. self.isDefault_label = True
  1473. self.set_default_intervals()
  1474. def have_units(self):
  1475. return self.converter is not None or self.units is not None
  1476. def convert_units(self, x):
  1477. # If x is natively supported by Matplotlib, doesn't need converting
  1478. if munits._is_natively_supported(x):
  1479. return x
  1480. if self.converter is None:
  1481. self.converter = munits.registry.get_converter(x)
  1482. if self.converter is None:
  1483. return x
  1484. try:
  1485. ret = self.converter.convert(x, self.units, self)
  1486. except Exception as e:
  1487. raise munits.ConversionError('Failed to convert value(s) to axis '
  1488. f'units: {x!r}') from e
  1489. return ret
  1490. def set_units(self, u):
  1491. """
  1492. Set the units for axis.
  1493. Parameters
  1494. ----------
  1495. u : units tag
  1496. Notes
  1497. -----
  1498. The units of any shared axis will also be updated.
  1499. """
  1500. if u == self.units:
  1501. return
  1502. for axis in self._get_shared_axis():
  1503. axis.units = u
  1504. axis._update_axisinfo()
  1505. axis.callbacks.process('units')
  1506. axis.stale = True
  1507. def get_units(self):
  1508. """Return the units for axis."""
  1509. return self.units
  1510. def set_label_text(self, label, fontdict=None, **kwargs):
  1511. """
  1512. Set the text value of the axis label.
  1513. Parameters
  1514. ----------
  1515. label : str
  1516. Text string.
  1517. fontdict : dict
  1518. Text properties.
  1519. .. admonition:: Discouraged
  1520. The use of *fontdict* is discouraged. Parameters should be passed as
  1521. individual keyword arguments or using dictionary-unpacking
  1522. ``set_label_text(..., **fontdict)``.
  1523. **kwargs
  1524. Merged into fontdict.
  1525. """
  1526. self.isDefault_label = False
  1527. self.label.set_text(label)
  1528. if fontdict is not None:
  1529. self.label.update(fontdict)
  1530. self.label.update(kwargs)
  1531. self.stale = True
  1532. return self.label
  1533. def set_major_formatter(self, formatter):
  1534. """
  1535. Set the formatter of the major ticker.
  1536. In addition to a `~matplotlib.ticker.Formatter` instance,
  1537. this also accepts a ``str`` or function.
  1538. For a ``str`` a `~matplotlib.ticker.StrMethodFormatter` is used.
  1539. The field used for the value must be labeled ``'x'`` and the field used
  1540. for the position must be labeled ``'pos'``.
  1541. See the `~matplotlib.ticker.StrMethodFormatter` documentation for
  1542. more information.
  1543. For a function, a `~matplotlib.ticker.FuncFormatter` is used.
  1544. The function must take two inputs (a tick value ``x`` and a
  1545. position ``pos``), and return a string containing the corresponding
  1546. tick label.
  1547. See the `~matplotlib.ticker.FuncFormatter` documentation for
  1548. more information.
  1549. Parameters
  1550. ----------
  1551. formatter : `~matplotlib.ticker.Formatter`, ``str``, or function
  1552. """
  1553. self._set_formatter(formatter, self.major)
  1554. def set_minor_formatter(self, formatter):
  1555. """
  1556. Set the formatter of the minor ticker.
  1557. In addition to a `~matplotlib.ticker.Formatter` instance,
  1558. this also accepts a ``str`` or function.
  1559. See `.Axis.set_major_formatter` for more information.
  1560. Parameters
  1561. ----------
  1562. formatter : `~matplotlib.ticker.Formatter`, ``str``, or function
  1563. """
  1564. self._set_formatter(formatter, self.minor)
  1565. def _set_formatter(self, formatter, level):
  1566. if isinstance(formatter, str):
  1567. formatter = mticker.StrMethodFormatter(formatter)
  1568. # Don't allow any other TickHelper to avoid easy-to-make errors,
  1569. # like using a Locator instead of a Formatter.
  1570. elif (callable(formatter) and
  1571. not isinstance(formatter, mticker.TickHelper)):
  1572. formatter = mticker.FuncFormatter(formatter)
  1573. else:
  1574. _api.check_isinstance(mticker.Formatter, formatter=formatter)
  1575. if (isinstance(formatter, mticker.FixedFormatter)
  1576. and len(formatter.seq) > 0
  1577. and not isinstance(level.locator, mticker.FixedLocator)):
  1578. _api.warn_external('FixedFormatter should only be used together '
  1579. 'with FixedLocator')
  1580. if level == self.major:
  1581. self.isDefault_majfmt = False
  1582. else:
  1583. self.isDefault_minfmt = False
  1584. level.formatter = formatter
  1585. formatter.set_axis(self)
  1586. self.stale = True
  1587. def set_major_locator(self, locator):
  1588. """
  1589. Set the locator of the major ticker.
  1590. Parameters
  1591. ----------
  1592. locator : `~matplotlib.ticker.Locator`
  1593. """
  1594. _api.check_isinstance(mticker.Locator, locator=locator)
  1595. self.isDefault_majloc = False
  1596. self.major.locator = locator
  1597. if self.major.formatter:
  1598. self.major.formatter._set_locator(locator)
  1599. locator.set_axis(self)
  1600. self.stale = True
  1601. def set_minor_locator(self, locator):
  1602. """
  1603. Set the locator of the minor ticker.
  1604. Parameters
  1605. ----------
  1606. locator : `~matplotlib.ticker.Locator`
  1607. """
  1608. _api.check_isinstance(mticker.Locator, locator=locator)
  1609. self.isDefault_minloc = False
  1610. self.minor.locator = locator
  1611. if self.minor.formatter:
  1612. self.minor.formatter._set_locator(locator)
  1613. locator.set_axis(self)
  1614. self.stale = True
  1615. def set_pickradius(self, pickradius):
  1616. """
  1617. Set the depth of the axis used by the picker.
  1618. Parameters
  1619. ----------
  1620. pickradius : float
  1621. The acceptance radius for containment tests.
  1622. See also `.Axis.contains`.
  1623. """
  1624. if not isinstance(pickradius, Real) or pickradius < 0:
  1625. raise ValueError("pick radius should be a distance")
  1626. self._pickradius = pickradius
  1627. pickradius = property(
  1628. get_pickradius, set_pickradius, doc="The acceptance radius for "
  1629. "containment tests. See also `.Axis.contains`.")
  1630. # Helper for set_ticklabels. Defining it here makes it picklable.
  1631. @staticmethod
  1632. def _format_with_dict(tickd, x, pos):
  1633. return tickd.get(x, "")
  1634. @_api.rename_parameter("3.7", "ticklabels", "labels")
  1635. def set_ticklabels(self, labels, *, minor=False, fontdict=None, **kwargs):
  1636. r"""
  1637. [*Discouraged*] Set this Axis' tick labels with list of string labels.
  1638. .. admonition:: Discouraged
  1639. The use of this method is discouraged, because of the dependency on
  1640. tick positions. In most cases, you'll want to use
  1641. ``Axes.set_[x/y/z]ticks(positions, labels)`` or ``Axis.set_ticks``
  1642. instead.
  1643. If you are using this method, you should always fix the tick
  1644. positions before, e.g. by using `.Axis.set_ticks` or by explicitly
  1645. setting a `~.ticker.FixedLocator`. Otherwise, ticks are free to
  1646. move and the labels may end up in unexpected positions.
  1647. Parameters
  1648. ----------
  1649. labels : sequence of str or of `.Text`\s
  1650. Texts for labeling each tick location in the sequence set by
  1651. `.Axis.set_ticks`; the number of labels must match the number of
  1652. locations.
  1653. minor : bool
  1654. If True, set minor ticks instead of major ticks.
  1655. fontdict : dict, optional
  1656. .. admonition:: Discouraged
  1657. The use of *fontdict* is discouraged. Parameters should be passed as
  1658. individual keyword arguments or using dictionary-unpacking
  1659. ``set_ticklabels(..., **fontdict)``.
  1660. A dictionary controlling the appearance of the ticklabels.
  1661. The default *fontdict* is::
  1662. {'fontsize': rcParams['axes.titlesize'],
  1663. 'fontweight': rcParams['axes.titleweight'],
  1664. 'verticalalignment': 'baseline',
  1665. 'horizontalalignment': loc}
  1666. **kwargs
  1667. Text properties.
  1668. .. warning::
  1669. This only sets the properties of the current ticks.
  1670. Ticks are not guaranteed to be persistent. Various operations
  1671. can create, delete and modify the Tick instances. There is an
  1672. imminent risk that these settings can get lost if you work on
  1673. the figure further (including also panning/zooming on a
  1674. displayed figure).
  1675. Use `.set_tick_params` instead if possible.
  1676. Returns
  1677. -------
  1678. list of `.Text`\s
  1679. For each tick, includes ``tick.label1`` if it is visible, then
  1680. ``tick.label2`` if it is visible, in that order.
  1681. """
  1682. try:
  1683. labels = [t.get_text() if hasattr(t, 'get_text') else t
  1684. for t in labels]
  1685. except TypeError:
  1686. raise TypeError(f"{labels:=} must be a sequence") from None
  1687. locator = (self.get_minor_locator() if minor
  1688. else self.get_major_locator())
  1689. if not labels:
  1690. # eg labels=[]:
  1691. formatter = mticker.NullFormatter()
  1692. elif isinstance(locator, mticker.FixedLocator):
  1693. # Passing [] as a list of labels is often used as a way to
  1694. # remove all tick labels, so only error for > 0 labels
  1695. if len(locator.locs) != len(labels) and len(labels) != 0:
  1696. raise ValueError(
  1697. "The number of FixedLocator locations"
  1698. f" ({len(locator.locs)}), usually from a call to"
  1699. " set_ticks, does not match"
  1700. f" the number of labels ({len(labels)}).")
  1701. tickd = {loc: lab for loc, lab in zip(locator.locs, labels)}
  1702. func = functools.partial(self._format_with_dict, tickd)
  1703. formatter = mticker.FuncFormatter(func)
  1704. else:
  1705. _api.warn_external(
  1706. "set_ticklabels() should only be used with a fixed number of "
  1707. "ticks, i.e. after set_ticks() or using a FixedLocator.")
  1708. formatter = mticker.FixedFormatter(labels)
  1709. with warnings.catch_warnings():
  1710. warnings.filterwarnings(
  1711. "ignore",
  1712. message="FixedFormatter should only be used together with FixedLocator")
  1713. if minor:
  1714. self.set_minor_formatter(formatter)
  1715. locs = self.get_minorticklocs()
  1716. ticks = self.get_minor_ticks(len(locs))
  1717. else:
  1718. self.set_major_formatter(formatter)
  1719. locs = self.get_majorticklocs()
  1720. ticks = self.get_major_ticks(len(locs))
  1721. ret = []
  1722. if fontdict is not None:
  1723. kwargs.update(fontdict)
  1724. for pos, (loc, tick) in enumerate(zip(locs, ticks)):
  1725. tick.update_position(loc)
  1726. tick_label = formatter(loc, pos)
  1727. # deal with label1
  1728. tick.label1.set_text(tick_label)
  1729. tick.label1._internal_update(kwargs)
  1730. # deal with label2
  1731. tick.label2.set_text(tick_label)
  1732. tick.label2._internal_update(kwargs)
  1733. # only return visible tick labels
  1734. if tick.label1.get_visible():
  1735. ret.append(tick.label1)
  1736. if tick.label2.get_visible():
  1737. ret.append(tick.label2)
  1738. self.stale = True
  1739. return ret
  1740. def _set_tick_locations(self, ticks, *, minor=False):
  1741. # see docstring of set_ticks
  1742. # XXX if the user changes units, the information will be lost here
  1743. ticks = self.convert_units(ticks)
  1744. locator = mticker.FixedLocator(ticks) # validate ticks early.
  1745. if len(ticks):
  1746. for axis in self._get_shared_axis():
  1747. # set_view_interval maintains any preexisting inversion.
  1748. axis.set_view_interval(min(ticks), max(ticks))
  1749. self.axes.stale = True
  1750. if minor:
  1751. self.set_minor_locator(locator)
  1752. return self.get_minor_ticks(len(ticks))
  1753. else:
  1754. self.set_major_locator(locator)
  1755. return self.get_major_ticks(len(ticks))
  1756. def set_ticks(self, ticks, labels=None, *, minor=False, **kwargs):
  1757. """
  1758. Set this Axis' tick locations and optionally tick labels.
  1759. If necessary, the view limits of the Axis are expanded so that all
  1760. given ticks are visible.
  1761. Parameters
  1762. ----------
  1763. ticks : 1D array-like
  1764. Array of tick locations. The axis `.Locator` is replaced by a
  1765. `~.ticker.FixedLocator`.
  1766. The values may be either floats or in axis units.
  1767. Pass an empty list to remove all ticks::
  1768. set_ticks([])
  1769. Some tick formatters will not label arbitrary tick positions;
  1770. e.g. log formatters only label decade ticks by default. In
  1771. such a case you can set a formatter explicitly on the axis
  1772. using `.Axis.set_major_formatter` or provide formatted
  1773. *labels* yourself.
  1774. labels : list of str, optional
  1775. Tick labels for each location in *ticks*. *labels* must be of the same
  1776. length as *ticks*. If not set, the labels are generate using the axis
  1777. tick `.Formatter`.
  1778. minor : bool, default: False
  1779. If ``False``, set the major ticks; if ``True``, the minor ticks.
  1780. **kwargs
  1781. `.Text` properties for the labels. Using these is only allowed if
  1782. you pass *labels*. In other cases, please use `~.Axes.tick_params`.
  1783. Notes
  1784. -----
  1785. The mandatory expansion of the view limits is an intentional design
  1786. choice to prevent the surprise of a non-visible tick. If you need
  1787. other limits, you should set the limits explicitly after setting the
  1788. ticks.
  1789. """
  1790. if labels is None and kwargs:
  1791. first_key = next(iter(kwargs))
  1792. raise ValueError(
  1793. f"Incorrect use of keyword argument {first_key!r}. Keyword arguments "
  1794. "other than 'minor' modify the text labels and can only be used if "
  1795. "'labels' are passed as well.")
  1796. result = self._set_tick_locations(ticks, minor=minor)
  1797. if labels is not None:
  1798. self.set_ticklabels(labels, minor=minor, **kwargs)
  1799. return result
  1800. def _get_tick_boxes_siblings(self, renderer):
  1801. """
  1802. Get the bounding boxes for this `.axis` and its siblings
  1803. as set by `.Figure.align_xlabels` or `.Figure.align_ylabels`.
  1804. By default, it just gets bboxes for *self*.
  1805. """
  1806. # Get the Grouper keeping track of x or y label groups for this figure.
  1807. name = self._get_axis_name()
  1808. if name not in self.figure._align_label_groups:
  1809. return [], []
  1810. grouper = self.figure._align_label_groups[name]
  1811. bboxes = []
  1812. bboxes2 = []
  1813. # If we want to align labels from other Axes:
  1814. for ax in grouper.get_siblings(self.axes):
  1815. axis = ax._axis_map[name]
  1816. ticks_to_draw = axis._update_ticks()
  1817. tlb, tlb2 = axis._get_ticklabel_bboxes(ticks_to_draw, renderer)
  1818. bboxes.extend(tlb)
  1819. bboxes2.extend(tlb2)
  1820. return bboxes, bboxes2
  1821. def _update_label_position(self, renderer):
  1822. """
  1823. Update the label position based on the bounding box enclosing
  1824. all the ticklabels and axis spine.
  1825. """
  1826. raise NotImplementedError('Derived must override')
  1827. def _update_offset_text_position(self, bboxes, bboxes2):
  1828. """
  1829. Update the offset text position based on the sequence of bounding
  1830. boxes of all the ticklabels.
  1831. """
  1832. raise NotImplementedError('Derived must override')
  1833. def axis_date(self, tz=None):
  1834. """
  1835. Set up axis ticks and labels to treat data along this Axis as dates.
  1836. Parameters
  1837. ----------
  1838. tz : str or `datetime.tzinfo`, default: :rc:`timezone`
  1839. The timezone used to create date labels.
  1840. """
  1841. # By providing a sample datetime instance with the desired timezone,
  1842. # the registered converter can be selected, and the "units" attribute,
  1843. # which is the timezone, can be set.
  1844. if isinstance(tz, str):
  1845. import dateutil.tz
  1846. tz = dateutil.tz.gettz(tz)
  1847. self.update_units(datetime.datetime(2009, 1, 1, 0, 0, 0, 0, tz))
  1848. def get_tick_space(self):
  1849. """Return the estimated number of ticks that can fit on the axis."""
  1850. # Must be overridden in the subclass
  1851. raise NotImplementedError()
  1852. def _get_ticks_position(self):
  1853. """
  1854. Helper for `XAxis.get_ticks_position` and `YAxis.get_ticks_position`.
  1855. Check the visibility of tick1line, label1, tick2line, and label2 on
  1856. the first major and the first minor ticks, and return
  1857. - 1 if only tick1line and label1 are visible (which corresponds to
  1858. "bottom" for the x-axis and "left" for the y-axis);
  1859. - 2 if only tick2line and label2 are visible (which corresponds to
  1860. "top" for the x-axis and "right" for the y-axis);
  1861. - "default" if only tick1line, tick2line and label1 are visible;
  1862. - "unknown" otherwise.
  1863. """
  1864. major = self.majorTicks[0]
  1865. minor = self.minorTicks[0]
  1866. if all(tick.tick1line.get_visible()
  1867. and not tick.tick2line.get_visible()
  1868. and tick.label1.get_visible()
  1869. and not tick.label2.get_visible()
  1870. for tick in [major, minor]):
  1871. return 1
  1872. elif all(tick.tick2line.get_visible()
  1873. and not tick.tick1line.get_visible()
  1874. and tick.label2.get_visible()
  1875. and not tick.label1.get_visible()
  1876. for tick in [major, minor]):
  1877. return 2
  1878. elif all(tick.tick1line.get_visible()
  1879. and tick.tick2line.get_visible()
  1880. and tick.label1.get_visible()
  1881. and not tick.label2.get_visible()
  1882. for tick in [major, minor]):
  1883. return "default"
  1884. else:
  1885. return "unknown"
  1886. def get_label_position(self):
  1887. """
  1888. Return the label position (top or bottom)
  1889. """
  1890. return self.label_position
  1891. def set_label_position(self, position):
  1892. """
  1893. Set the label position (top or bottom)
  1894. Parameters
  1895. ----------
  1896. position : {'top', 'bottom'}
  1897. """
  1898. raise NotImplementedError()
  1899. def get_minpos(self):
  1900. raise NotImplementedError()
  1901. def _make_getset_interval(method_name, lim_name, attr_name):
  1902. """
  1903. Helper to generate ``get_{data,view}_interval`` and
  1904. ``set_{data,view}_interval`` implementations.
  1905. """
  1906. def getter(self):
  1907. # docstring inherited.
  1908. return getattr(getattr(self.axes, lim_name), attr_name)
  1909. def setter(self, vmin, vmax, ignore=False):
  1910. # docstring inherited.
  1911. if ignore:
  1912. setattr(getattr(self.axes, lim_name), attr_name, (vmin, vmax))
  1913. else:
  1914. oldmin, oldmax = getter(self)
  1915. if oldmin < oldmax:
  1916. setter(self, min(vmin, vmax, oldmin), max(vmin, vmax, oldmax),
  1917. ignore=True)
  1918. else:
  1919. setter(self, max(vmin, vmax, oldmin), min(vmin, vmax, oldmax),
  1920. ignore=True)
  1921. self.stale = True
  1922. getter.__name__ = f"get_{method_name}_interval"
  1923. setter.__name__ = f"set_{method_name}_interval"
  1924. return getter, setter
  1925. class XAxis(Axis):
  1926. __name__ = 'xaxis'
  1927. axis_name = 'x' #: Read-only name identifying the axis.
  1928. _tick_class = XTick
  1929. def __init__(self, *args, **kwargs):
  1930. super().__init__(*args, **kwargs)
  1931. self._init()
  1932. def _init(self):
  1933. """
  1934. Initialize the label and offsetText instance values and
  1935. `label_position` / `offset_text_position`.
  1936. """
  1937. # x in axes coords, y in display coords (to be updated at draw time by
  1938. # _update_label_positions and _update_offset_text_position).
  1939. self.label.set(
  1940. x=0.5, y=0,
  1941. verticalalignment='top', horizontalalignment='center',
  1942. transform=mtransforms.blended_transform_factory(
  1943. self.axes.transAxes, mtransforms.IdentityTransform()),
  1944. )
  1945. self.label_position = 'bottom'
  1946. if mpl.rcParams['xtick.labelcolor'] == 'inherit':
  1947. tick_color = mpl.rcParams['xtick.color']
  1948. else:
  1949. tick_color = mpl.rcParams['xtick.labelcolor']
  1950. self.offsetText.set(
  1951. x=1, y=0,
  1952. verticalalignment='top', horizontalalignment='right',
  1953. transform=mtransforms.blended_transform_factory(
  1954. self.axes.transAxes, mtransforms.IdentityTransform()),
  1955. fontsize=mpl.rcParams['xtick.labelsize'],
  1956. color=tick_color
  1957. )
  1958. self.offset_text_position = 'bottom'
  1959. def contains(self, mouseevent):
  1960. """Test whether the mouse event occurred in the x-axis."""
  1961. if self._different_canvas(mouseevent):
  1962. return False, {}
  1963. x, y = mouseevent.x, mouseevent.y
  1964. try:
  1965. trans = self.axes.transAxes.inverted()
  1966. xaxes, yaxes = trans.transform((x, y))
  1967. except ValueError:
  1968. return False, {}
  1969. (l, b), (r, t) = self.axes.transAxes.transform([(0, 0), (1, 1)])
  1970. inaxis = 0 <= xaxes <= 1 and (
  1971. b - self._pickradius < y < b or
  1972. t < y < t + self._pickradius)
  1973. return inaxis, {}
  1974. def set_label_position(self, position):
  1975. """
  1976. Set the label position (top or bottom)
  1977. Parameters
  1978. ----------
  1979. position : {'top', 'bottom'}
  1980. """
  1981. self.label.set_verticalalignment(_api.check_getitem({
  1982. 'top': 'baseline', 'bottom': 'top',
  1983. }, position=position))
  1984. self.label_position = position
  1985. self.stale = True
  1986. def _update_label_position(self, renderer):
  1987. """
  1988. Update the label position based on the bounding box enclosing
  1989. all the ticklabels and axis spine
  1990. """
  1991. if not self._autolabelpos:
  1992. return
  1993. # get bounding boxes for this axis and any siblings
  1994. # that have been set by `fig.align_xlabels()`
  1995. bboxes, bboxes2 = self._get_tick_boxes_siblings(renderer=renderer)
  1996. x, y = self.label.get_position()
  1997. if self.label_position == 'bottom':
  1998. try:
  1999. spine = self.axes.spines['bottom']
  2000. spinebbox = spine.get_window_extent()
  2001. except KeyError:
  2002. # use Axes if spine doesn't exist
  2003. spinebbox = self.axes.bbox
  2004. bbox = mtransforms.Bbox.union(bboxes + [spinebbox])
  2005. bottom = bbox.y0
  2006. self.label.set_position(
  2007. (x, bottom - self.labelpad * self.figure.dpi / 72)
  2008. )
  2009. else:
  2010. try:
  2011. spine = self.axes.spines['top']
  2012. spinebbox = spine.get_window_extent()
  2013. except KeyError:
  2014. # use Axes if spine doesn't exist
  2015. spinebbox = self.axes.bbox
  2016. bbox = mtransforms.Bbox.union(bboxes2 + [spinebbox])
  2017. top = bbox.y1
  2018. self.label.set_position(
  2019. (x, top + self.labelpad * self.figure.dpi / 72)
  2020. )
  2021. def _update_offset_text_position(self, bboxes, bboxes2):
  2022. """
  2023. Update the offset_text position based on the sequence of bounding
  2024. boxes of all the ticklabels
  2025. """
  2026. x, y = self.offsetText.get_position()
  2027. if not hasattr(self, '_tick_position'):
  2028. self._tick_position = 'bottom'
  2029. if self._tick_position == 'bottom':
  2030. if not len(bboxes):
  2031. bottom = self.axes.bbox.ymin
  2032. else:
  2033. bbox = mtransforms.Bbox.union(bboxes)
  2034. bottom = bbox.y0
  2035. y = bottom - self.OFFSETTEXTPAD * self.figure.dpi / 72
  2036. else:
  2037. if not len(bboxes2):
  2038. top = self.axes.bbox.ymax
  2039. else:
  2040. bbox = mtransforms.Bbox.union(bboxes2)
  2041. top = bbox.y1
  2042. y = top + self.OFFSETTEXTPAD * self.figure.dpi / 72
  2043. self.offsetText.set_position((x, y))
  2044. def set_ticks_position(self, position):
  2045. """
  2046. Set the ticks position.
  2047. Parameters
  2048. ----------
  2049. position : {'top', 'bottom', 'both', 'default', 'none'}
  2050. 'both' sets the ticks to appear on both positions, but does not
  2051. change the tick labels. 'default' resets the tick positions to
  2052. the default: ticks on both positions, labels at bottom. 'none'
  2053. can be used if you don't want any ticks. 'none' and 'both'
  2054. affect only the ticks, not the labels.
  2055. """
  2056. if position == 'top':
  2057. self.set_tick_params(which='both', top=True, labeltop=True,
  2058. bottom=False, labelbottom=False)
  2059. self._tick_position = 'top'
  2060. self.offsetText.set_verticalalignment('bottom')
  2061. elif position == 'bottom':
  2062. self.set_tick_params(which='both', top=False, labeltop=False,
  2063. bottom=True, labelbottom=True)
  2064. self._tick_position = 'bottom'
  2065. self.offsetText.set_verticalalignment('top')
  2066. elif position == 'both':
  2067. self.set_tick_params(which='both', top=True,
  2068. bottom=True)
  2069. elif position == 'none':
  2070. self.set_tick_params(which='both', top=False,
  2071. bottom=False)
  2072. elif position == 'default':
  2073. self.set_tick_params(which='both', top=True, labeltop=False,
  2074. bottom=True, labelbottom=True)
  2075. self._tick_position = 'bottom'
  2076. self.offsetText.set_verticalalignment('top')
  2077. else:
  2078. _api.check_in_list(['top', 'bottom', 'both', 'default', 'none'],
  2079. position=position)
  2080. self.stale = True
  2081. def tick_top(self):
  2082. """
  2083. Move ticks and ticklabels (if present) to the top of the Axes.
  2084. """
  2085. label = True
  2086. if 'label1On' in self._major_tick_kw:
  2087. label = (self._major_tick_kw['label1On']
  2088. or self._major_tick_kw['label2On'])
  2089. self.set_ticks_position('top')
  2090. # If labels were turned off before this was called, leave them off.
  2091. self.set_tick_params(which='both', labeltop=label)
  2092. def tick_bottom(self):
  2093. """
  2094. Move ticks and ticklabels (if present) to the bottom of the Axes.
  2095. """
  2096. label = True
  2097. if 'label1On' in self._major_tick_kw:
  2098. label = (self._major_tick_kw['label1On']
  2099. or self._major_tick_kw['label2On'])
  2100. self.set_ticks_position('bottom')
  2101. # If labels were turned off before this was called, leave them off.
  2102. self.set_tick_params(which='both', labelbottom=label)
  2103. def get_ticks_position(self):
  2104. """
  2105. Return the ticks position ("top", "bottom", "default", or "unknown").
  2106. """
  2107. return {1: "bottom", 2: "top",
  2108. "default": "default", "unknown": "unknown"}[
  2109. self._get_ticks_position()]
  2110. get_view_interval, set_view_interval = _make_getset_interval(
  2111. "view", "viewLim", "intervalx")
  2112. get_data_interval, set_data_interval = _make_getset_interval(
  2113. "data", "dataLim", "intervalx")
  2114. def get_minpos(self):
  2115. return self.axes.dataLim.minposx
  2116. def set_default_intervals(self):
  2117. # docstring inherited
  2118. # only change view if dataLim has not changed and user has
  2119. # not changed the view:
  2120. if (not self.axes.dataLim.mutatedx() and
  2121. not self.axes.viewLim.mutatedx()):
  2122. if self.converter is not None:
  2123. info = self.converter.axisinfo(self.units, self)
  2124. if info.default_limits is not None:
  2125. xmin, xmax = self.convert_units(info.default_limits)
  2126. self.axes.viewLim.intervalx = xmin, xmax
  2127. self.stale = True
  2128. def get_tick_space(self):
  2129. ends = mtransforms.Bbox.unit().transformed(
  2130. self.axes.transAxes - self.figure.dpi_scale_trans)
  2131. length = ends.width * 72
  2132. # There is a heuristic here that the aspect ratio of tick text
  2133. # is no more than 3:1
  2134. size = self._get_tick_label_size('x') * 3
  2135. if size > 0:
  2136. return int(np.floor(length / size))
  2137. else:
  2138. return 2**31 - 1
  2139. class YAxis(Axis):
  2140. __name__ = 'yaxis'
  2141. axis_name = 'y' #: Read-only name identifying the axis.
  2142. _tick_class = YTick
  2143. def __init__(self, *args, **kwargs):
  2144. super().__init__(*args, **kwargs)
  2145. self._init()
  2146. def _init(self):
  2147. """
  2148. Initialize the label and offsetText instance values and
  2149. `label_position` / `offset_text_position`.
  2150. """
  2151. # x in display coords, y in axes coords (to be updated at draw time by
  2152. # _update_label_positions and _update_offset_text_position).
  2153. self.label.set(
  2154. x=0, y=0.5,
  2155. verticalalignment='bottom', horizontalalignment='center',
  2156. rotation='vertical', rotation_mode='anchor',
  2157. transform=mtransforms.blended_transform_factory(
  2158. mtransforms.IdentityTransform(), self.axes.transAxes),
  2159. )
  2160. self.label_position = 'left'
  2161. if mpl.rcParams['ytick.labelcolor'] == 'inherit':
  2162. tick_color = mpl.rcParams['ytick.color']
  2163. else:
  2164. tick_color = mpl.rcParams['ytick.labelcolor']
  2165. # x in axes coords, y in display coords(!).
  2166. self.offsetText.set(
  2167. x=0, y=0.5,
  2168. verticalalignment='baseline', horizontalalignment='left',
  2169. transform=mtransforms.blended_transform_factory(
  2170. self.axes.transAxes, mtransforms.IdentityTransform()),
  2171. fontsize=mpl.rcParams['ytick.labelsize'],
  2172. color=tick_color
  2173. )
  2174. self.offset_text_position = 'left'
  2175. def contains(self, mouseevent):
  2176. # docstring inherited
  2177. if self._different_canvas(mouseevent):
  2178. return False, {}
  2179. x, y = mouseevent.x, mouseevent.y
  2180. try:
  2181. trans = self.axes.transAxes.inverted()
  2182. xaxes, yaxes = trans.transform((x, y))
  2183. except ValueError:
  2184. return False, {}
  2185. (l, b), (r, t) = self.axes.transAxes.transform([(0, 0), (1, 1)])
  2186. inaxis = 0 <= yaxes <= 1 and (
  2187. l - self._pickradius < x < l or
  2188. r < x < r + self._pickradius)
  2189. return inaxis, {}
  2190. def set_label_position(self, position):
  2191. """
  2192. Set the label position (left or right)
  2193. Parameters
  2194. ----------
  2195. position : {'left', 'right'}
  2196. """
  2197. self.label.set_rotation_mode('anchor')
  2198. self.label.set_verticalalignment(_api.check_getitem({
  2199. 'left': 'bottom', 'right': 'top',
  2200. }, position=position))
  2201. self.label_position = position
  2202. self.stale = True
  2203. def _update_label_position(self, renderer):
  2204. """
  2205. Update the label position based on the bounding box enclosing
  2206. all the ticklabels and axis spine
  2207. """
  2208. if not self._autolabelpos:
  2209. return
  2210. # get bounding boxes for this axis and any siblings
  2211. # that have been set by `fig.align_ylabels()`
  2212. bboxes, bboxes2 = self._get_tick_boxes_siblings(renderer=renderer)
  2213. x, y = self.label.get_position()
  2214. if self.label_position == 'left':
  2215. try:
  2216. spine = self.axes.spines['left']
  2217. spinebbox = spine.get_window_extent()
  2218. except KeyError:
  2219. # use Axes if spine doesn't exist
  2220. spinebbox = self.axes.bbox
  2221. bbox = mtransforms.Bbox.union(bboxes + [spinebbox])
  2222. left = bbox.x0
  2223. self.label.set_position(
  2224. (left - self.labelpad * self.figure.dpi / 72, y)
  2225. )
  2226. else:
  2227. try:
  2228. spine = self.axes.spines['right']
  2229. spinebbox = spine.get_window_extent()
  2230. except KeyError:
  2231. # use Axes if spine doesn't exist
  2232. spinebbox = self.axes.bbox
  2233. bbox = mtransforms.Bbox.union(bboxes2 + [spinebbox])
  2234. right = bbox.x1
  2235. self.label.set_position(
  2236. (right + self.labelpad * self.figure.dpi / 72, y)
  2237. )
  2238. def _update_offset_text_position(self, bboxes, bboxes2):
  2239. """
  2240. Update the offset_text position based on the sequence of bounding
  2241. boxes of all the ticklabels
  2242. """
  2243. x, _ = self.offsetText.get_position()
  2244. if 'outline' in self.axes.spines:
  2245. # Special case for colorbars:
  2246. bbox = self.axes.spines['outline'].get_window_extent()
  2247. else:
  2248. bbox = self.axes.bbox
  2249. top = bbox.ymax
  2250. self.offsetText.set_position(
  2251. (x, top + self.OFFSETTEXTPAD * self.figure.dpi / 72)
  2252. )
  2253. def set_offset_position(self, position):
  2254. """
  2255. Parameters
  2256. ----------
  2257. position : {'left', 'right'}
  2258. """
  2259. x, y = self.offsetText.get_position()
  2260. x = _api.check_getitem({'left': 0, 'right': 1}, position=position)
  2261. self.offsetText.set_ha(position)
  2262. self.offsetText.set_position((x, y))
  2263. self.stale = True
  2264. def set_ticks_position(self, position):
  2265. """
  2266. Set the ticks position.
  2267. Parameters
  2268. ----------
  2269. position : {'left', 'right', 'both', 'default', 'none'}
  2270. 'both' sets the ticks to appear on both positions, but does not
  2271. change the tick labels. 'default' resets the tick positions to
  2272. the default: ticks on both positions, labels at left. 'none'
  2273. can be used if you don't want any ticks. 'none' and 'both'
  2274. affect only the ticks, not the labels.
  2275. """
  2276. if position == 'right':
  2277. self.set_tick_params(which='both', right=True, labelright=True,
  2278. left=False, labelleft=False)
  2279. self.set_offset_position(position)
  2280. elif position == 'left':
  2281. self.set_tick_params(which='both', right=False, labelright=False,
  2282. left=True, labelleft=True)
  2283. self.set_offset_position(position)
  2284. elif position == 'both':
  2285. self.set_tick_params(which='both', right=True,
  2286. left=True)
  2287. elif position == 'none':
  2288. self.set_tick_params(which='both', right=False,
  2289. left=False)
  2290. elif position == 'default':
  2291. self.set_tick_params(which='both', right=True, labelright=False,
  2292. left=True, labelleft=True)
  2293. else:
  2294. _api.check_in_list(['left', 'right', 'both', 'default', 'none'],
  2295. position=position)
  2296. self.stale = True
  2297. def tick_right(self):
  2298. """
  2299. Move ticks and ticklabels (if present) to the right of the Axes.
  2300. """
  2301. label = True
  2302. if 'label1On' in self._major_tick_kw:
  2303. label = (self._major_tick_kw['label1On']
  2304. or self._major_tick_kw['label2On'])
  2305. self.set_ticks_position('right')
  2306. # if labels were turned off before this was called
  2307. # leave them off
  2308. self.set_tick_params(which='both', labelright=label)
  2309. def tick_left(self):
  2310. """
  2311. Move ticks and ticklabels (if present) to the left of the Axes.
  2312. """
  2313. label = True
  2314. if 'label1On' in self._major_tick_kw:
  2315. label = (self._major_tick_kw['label1On']
  2316. or self._major_tick_kw['label2On'])
  2317. self.set_ticks_position('left')
  2318. # if labels were turned off before this was called
  2319. # leave them off
  2320. self.set_tick_params(which='both', labelleft=label)
  2321. def get_ticks_position(self):
  2322. """
  2323. Return the ticks position ("left", "right", "default", or "unknown").
  2324. """
  2325. return {1: "left", 2: "right",
  2326. "default": "default", "unknown": "unknown"}[
  2327. self._get_ticks_position()]
  2328. get_view_interval, set_view_interval = _make_getset_interval(
  2329. "view", "viewLim", "intervaly")
  2330. get_data_interval, set_data_interval = _make_getset_interval(
  2331. "data", "dataLim", "intervaly")
  2332. def get_minpos(self):
  2333. return self.axes.dataLim.minposy
  2334. def set_default_intervals(self):
  2335. # docstring inherited
  2336. # only change view if dataLim has not changed and user has
  2337. # not changed the view:
  2338. if (not self.axes.dataLim.mutatedy() and
  2339. not self.axes.viewLim.mutatedy()):
  2340. if self.converter is not None:
  2341. info = self.converter.axisinfo(self.units, self)
  2342. if info.default_limits is not None:
  2343. ymin, ymax = self.convert_units(info.default_limits)
  2344. self.axes.viewLim.intervaly = ymin, ymax
  2345. self.stale = True
  2346. def get_tick_space(self):
  2347. ends = mtransforms.Bbox.unit().transformed(
  2348. self.axes.transAxes - self.figure.dpi_scale_trans)
  2349. length = ends.height * 72
  2350. # Having a spacing of at least 2 just looks good.
  2351. size = self._get_tick_label_size('y') * 2
  2352. if size > 0:
  2353. return int(np.floor(length / size))
  2354. else:
  2355. return 2**31 - 1