axis.py 102 KB

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