axis_artist.py 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229
  1. """
  2. axis_artist.py module provides axis-related artists. They are
  3. * axis line
  4. * tick lines
  5. * tick labels
  6. * axis label
  7. * grid lines
  8. The main artist classes are `AxisArtist` and `GridlinesCollection`. While
  9. `GridlinesCollection` is responsible for drawing grid lines, `AxisArtist`
  10. is responsible for all other artists. `AxisArtist` has attributes that are
  11. associated with each type of artists:
  12. * line: axis line
  13. * major_ticks: major tick lines
  14. * major_ticklabels: major tick labels
  15. * minor_ticks: minor tick lines
  16. * minor_ticklabels: minor tick labels
  17. * label: axis label
  18. Typically, the `AxisArtist` associated with an axes will be accessed with the
  19. *axis* dictionary of the axes, i.e., the `AxisArtist` for the bottom axis is ::
  20. ax.axis["bottom"]
  21. where *ax* is an instance of `mpl_toolkits.axislines.Axes`. Thus,
  22. ``ax.axis["bottom"].line`` is an artist associated with the axis line, and
  23. ``ax.axis["bottom"].major_ticks`` is an artist associated with the major tick
  24. lines.
  25. You can change the colors, fonts, line widths, etc. of these artists
  26. by calling suitable set method. For example, to change the color of the major
  27. ticks of the bottom axis to red, use ::
  28. ax.axis["bottom"].major_ticks.set_color("r")
  29. However, things like the locations of ticks, and their ticklabels need to be
  30. changed from the side of the grid_helper.
  31. axis_direction
  32. --------------
  33. `AxisArtist`, `AxisLabel`, `TickLabels` have an *axis_direction* attribute,
  34. which adjusts the location, angle, etc. The *axis_direction* must be one of
  35. "left", "right", "bottom", "top", and follows the Matplotlib convention for
  36. rectangular axis.
  37. For example, for the *bottom* axis (the left and right is relative to the
  38. direction of the increasing coordinate),
  39. * ticklabels and axislabel are on the right
  40. * ticklabels and axislabel have text angle of 0
  41. * ticklabels are baseline, center-aligned
  42. * axislabel is top, center-aligned
  43. The text angles are actually relative to (90 + angle of the direction to the
  44. ticklabel), which gives 0 for bottom axis.
  45. =================== ====== ======== ====== ========
  46. Parameter left bottom right top
  47. =================== ====== ======== ====== ========
  48. ticklabels location left right right left
  49. axislabel location left right right left
  50. ticklabels angle 90 0 -90 180
  51. axislabel angle 180 0 0 180
  52. ticklabel va center baseline center baseline
  53. axislabel va center top center bottom
  54. ticklabel ha right center right center
  55. axislabel ha right center right center
  56. =================== ====== ======== ====== ========
  57. Ticks are by default direct opposite side of the ticklabels. To make ticks to
  58. the same side of the ticklabels, ::
  59. ax.axis["bottom"].major_ticks.set_ticks_out(True)
  60. The following attributes can be customized (use the ``set_xxx`` methods):
  61. * `Ticks`: ticksize, tick_out
  62. * `TickLabels`: pad
  63. * `AxisLabel`: pad
  64. """
  65. # FIXME :
  66. # angles are given in data coordinate - need to convert it to canvas coordinate
  67. from operator import methodcaller
  68. import numpy as np
  69. from matplotlib import cbook, rcParams
  70. import matplotlib.artist as martist
  71. import matplotlib.text as mtext
  72. from matplotlib.collections import LineCollection
  73. from matplotlib.lines import Line2D
  74. from matplotlib.patches import PathPatch
  75. from matplotlib.path import Path
  76. from matplotlib.transforms import (
  77. Affine2D, Bbox, IdentityTransform, ScaledTranslation, TransformedPath)
  78. from .axisline_style import AxislineStyle
  79. @cbook.deprecated("3.2", alternative="matplotlib.patches.PathPatch")
  80. class BezierPath(Line2D):
  81. def __init__(self, path, *args, **kwargs):
  82. """
  83. Parameters
  84. ----------
  85. path : `~.path.Path`
  86. The path to draw.
  87. **kwargs
  88. All remaining keyword arguments are passed to `.Line2D`.
  89. """
  90. Line2D.__init__(self, [], [], *args, **kwargs)
  91. self._path = path
  92. self._invalid = False
  93. def recache(self):
  94. self._transformed_path = TransformedPath(
  95. self._path, self.get_transform())
  96. self._invalid = False
  97. def set_path(self, path):
  98. self._path = path
  99. self._invalid = True
  100. def draw(self, renderer):
  101. if self._invalid:
  102. self.recache()
  103. if not self._visible:
  104. return
  105. renderer.open_group('line2d', gid=self.get_gid())
  106. gc = renderer.new_gc()
  107. self._set_gc_clip(gc)
  108. gc.set_foreground(self._color)
  109. gc.set_antialiased(self._antialiased)
  110. gc.set_linewidth(self._linewidth)
  111. gc.set_alpha(self._alpha)
  112. if self.is_dashed():
  113. cap = self._dashcapstyle
  114. join = self._dashjoinstyle
  115. else:
  116. cap = self._solidcapstyle
  117. join = self._solidjoinstyle
  118. gc.set_joinstyle(join)
  119. gc.set_capstyle(cap)
  120. gc.set_dashes(self._dashOffset, self._dashSeq)
  121. if self._lineStyles[self._linestyle] != '_draw_nothing':
  122. tpath, affine = (
  123. self._transformed_path.get_transformed_path_and_affine())
  124. renderer.draw_path(gc, tpath, affine.frozen())
  125. gc.restore()
  126. renderer.close_group('line2d')
  127. class AttributeCopier:
  128. @cbook.deprecated("3.2")
  129. def __init__(self, ref_artist, klass=martist.Artist):
  130. self._klass = klass
  131. self._ref_artist = ref_artist
  132. super().__init__()
  133. @cbook.deprecated("3.2")
  134. def set_ref_artist(self, artist):
  135. self._ref_artist = artist
  136. def get_ref_artist(self):
  137. """
  138. Return the underlying artist that actually defines some properties
  139. (e.g., color) of this artist.
  140. """
  141. raise RuntimeError("get_ref_artist must overridden")
  142. @cbook._delete_parameter("3.2", "default_value")
  143. def get_attribute_from_ref_artist(self, attr_name, default_value=None):
  144. getter = methodcaller("get_" + attr_name)
  145. prop = getter(super())
  146. return getter(self.get_ref_artist()) if prop == "auto" else prop
  147. class Ticks(AttributeCopier, Line2D):
  148. """
  149. Ticks are derived from Line2D, and note that ticks themselves
  150. are markers. Thus, you should use set_mec, set_mew, etc.
  151. To change the tick size (length), you need to use
  152. set_ticksize. To change the direction of the ticks (ticks are
  153. in opposite direction of ticklabels by default), use
  154. set_tick_out(False).
  155. """
  156. def __init__(self, ticksize, tick_out=False, *, axis=None, **kwargs):
  157. self._ticksize = ticksize
  158. self.locs_angles_labels = []
  159. self.set_tick_out(tick_out)
  160. self._axis = axis
  161. if self._axis is not None:
  162. if "color" not in kwargs:
  163. kwargs["color"] = "auto"
  164. if "mew" not in kwargs and "markeredgewidth" not in kwargs:
  165. kwargs["markeredgewidth"] = "auto"
  166. Line2D.__init__(self, [0.], [0.], **kwargs)
  167. self.set_snap(True)
  168. def get_ref_artist(self):
  169. # docstring inherited
  170. return self._axis.majorTicks[0].tick1line
  171. def get_color(self):
  172. return self.get_attribute_from_ref_artist("color")
  173. def get_markeredgecolor(self):
  174. return self.get_attribute_from_ref_artist("markeredgecolor")
  175. def get_markeredgewidth(self):
  176. return self.get_attribute_from_ref_artist("markeredgewidth")
  177. def set_tick_out(self, b):
  178. """Set whether ticks are drawn inside or outside the axes."""
  179. self._tick_out = b
  180. def get_tick_out(self):
  181. """Return whether ticks are drawn inside or outside the axes."""
  182. return self._tick_out
  183. def set_ticksize(self, ticksize):
  184. """Set length of the ticks in points."""
  185. self._ticksize = ticksize
  186. def get_ticksize(self):
  187. """Return length of the ticks in points."""
  188. return self._ticksize
  189. def set_locs_angles(self, locs_angles):
  190. self.locs_angles = locs_angles
  191. _tickvert_path = Path([[0., 0.], [1., 0.]])
  192. def draw(self, renderer):
  193. if not self.get_visible():
  194. return
  195. gc = renderer.new_gc()
  196. gc.set_foreground(self.get_markeredgecolor())
  197. gc.set_linewidth(self.get_markeredgewidth())
  198. gc.set_alpha(self._alpha)
  199. path_trans = self.get_transform()
  200. marker_transform = (Affine2D()
  201. .scale(renderer.points_to_pixels(self._ticksize)))
  202. if self.get_tick_out():
  203. marker_transform.rotate_deg(180)
  204. for loc, angle in self.locs_angles:
  205. locs = path_trans.transform_non_affine(np.array([loc]))
  206. if self.axes and not self.axes.viewLim.contains(*locs[0]):
  207. continue
  208. renderer.draw_markers(
  209. gc, self._tickvert_path,
  210. marker_transform + Affine2D().rotate_deg(angle),
  211. Path(locs), path_trans.get_affine())
  212. gc.restore()
  213. class LabelBase(mtext.Text):
  214. """
  215. A base class for AxisLabel and TickLabels. The position and angle
  216. of the text are calculated by to offset_ref_angle,
  217. text_ref_angle, and offset_radius attributes.
  218. """
  219. def __init__(self, *args, **kwargs):
  220. self.locs_angles_labels = []
  221. self._ref_angle = 0
  222. self._offset_radius = 0.
  223. super().__init__(*args, **kwargs)
  224. self.set_rotation_mode("anchor")
  225. self._text_follow_ref_angle = True
  226. def _set_ref_angle(self, a):
  227. self._ref_angle = a
  228. def _get_ref_angle(self):
  229. return self._ref_angle
  230. def _get_text_ref_angle(self):
  231. if self._text_follow_ref_angle:
  232. return self._get_ref_angle()+90
  233. else:
  234. return 0 # self.get_ref_angle()
  235. def _get_offset_ref_angle(self):
  236. return self._get_ref_angle()
  237. def _set_offset_radius(self, offset_radius):
  238. self._offset_radius = offset_radius
  239. def _get_offset_radius(self):
  240. return self._offset_radius
  241. _get_opposite_direction = {"left": "right",
  242. "right": "left",
  243. "top": "bottom",
  244. "bottom": "top"}.__getitem__
  245. def draw(self, renderer):
  246. if not self.get_visible():
  247. return
  248. # save original and adjust some properties
  249. tr = self.get_transform()
  250. angle_orig = self.get_rotation()
  251. text_ref_angle = self._get_text_ref_angle()
  252. offset_ref_angle = self._get_offset_ref_angle()
  253. theta = np.deg2rad(offset_ref_angle)
  254. dd = self._get_offset_radius()
  255. dx, dy = dd * np.cos(theta), dd * np.sin(theta)
  256. self.set_transform(tr + Affine2D().translate(dx, dy))
  257. self.set_rotation(text_ref_angle+angle_orig)
  258. super().draw(renderer)
  259. # restore original properties
  260. self.set_transform(tr)
  261. self.set_rotation(angle_orig)
  262. def get_window_extent(self, renderer):
  263. # save original and adjust some properties
  264. tr = self.get_transform()
  265. angle_orig = self.get_rotation()
  266. text_ref_angle = self._get_text_ref_angle()
  267. offset_ref_angle = self._get_offset_ref_angle()
  268. theta = np.deg2rad(offset_ref_angle)
  269. dd = self._get_offset_radius()
  270. dx, dy = dd * np.cos(theta), dd * np.sin(theta)
  271. self.set_transform(tr + Affine2D().translate(dx, dy))
  272. self.set_rotation(text_ref_angle+angle_orig)
  273. bbox = super().get_window_extent(renderer).frozen()
  274. # restore original properties
  275. self.set_transform(tr)
  276. self.set_rotation(angle_orig)
  277. return bbox
  278. class AxisLabel(AttributeCopier, LabelBase):
  279. """
  280. Axis Label. Derived from Text. The position of the text is updated
  281. in the fly, so changing text position has no effect. Otherwise, the
  282. properties can be changed as a normal Text.
  283. To change the pad between ticklabels and axis label, use set_pad.
  284. """
  285. def __init__(self, *args, axis_direction="bottom", axis=None, **kwargs):
  286. self._axis = axis
  287. self._pad = 5
  288. self._extra_pad = 0
  289. LabelBase.__init__(self, *args, **kwargs)
  290. self.set_axis_direction(axis_direction)
  291. def set_pad(self, pad):
  292. """
  293. Set the internal pad in points.
  294. The actual pad will be the sum of the internal pad and the
  295. external pad (the latter is set automatically by the AxisArtist).
  296. """
  297. self._pad = pad
  298. def get_pad(self):
  299. """
  300. Return the internal pad in points.
  301. See `.set_pad` for more details.
  302. """
  303. return self._pad
  304. def _set_external_pad(self, p):
  305. """Set external pad in pixels."""
  306. self._extra_pad = p
  307. def _get_external_pad(self):
  308. """Return external pad in pixels."""
  309. return self._extra_pad
  310. def get_ref_artist(self):
  311. # docstring inherited
  312. return self._axis.get_label()
  313. def get_text(self):
  314. t = super().get_text()
  315. if t == "__from_axes__":
  316. return self._axis.get_label().get_text()
  317. return self._text
  318. _default_alignments = dict(left=("bottom", "center"),
  319. right=("top", "center"),
  320. bottom=("top", "center"),
  321. top=("bottom", "center"))
  322. def set_default_alignment(self, d):
  323. va, ha = cbook._check_getitem(self._default_alignments, d=d)
  324. self.set_va(va)
  325. self.set_ha(ha)
  326. _default_angles = dict(left=180,
  327. right=0,
  328. bottom=0,
  329. top=180)
  330. def set_default_angle(self, d):
  331. self.set_rotation(cbook._check_getitem(self._default_angles, d=d))
  332. def set_axis_direction(self, d):
  333. """
  334. Adjust the text angle and text alignment of axis label
  335. according to the matplotlib convention.
  336. ===================== ========== ========= ========== ==========
  337. property left bottom right top
  338. ===================== ========== ========= ========== ==========
  339. axislabel angle 180 0 0 180
  340. axislabel va center top center bottom
  341. axislabel ha right center right center
  342. ===================== ========== ========= ========== ==========
  343. Note that the text angles are actually relative to (90 + angle
  344. of the direction to the ticklabel), which gives 0 for bottom
  345. axis.
  346. """
  347. self.set_default_alignment(d)
  348. self.set_default_angle(d)
  349. def get_color(self):
  350. return self.get_attribute_from_ref_artist("color")
  351. def draw(self, renderer):
  352. if not self.get_visible():
  353. return
  354. pad = renderer.points_to_pixels(self.get_pad())
  355. r = self._get_external_pad() + pad
  356. self._set_offset_radius(r)
  357. super().draw(renderer)
  358. def get_window_extent(self, renderer):
  359. if not self.get_visible():
  360. return
  361. pad = renderer.points_to_pixels(self.get_pad())
  362. r = self._get_external_pad() + pad
  363. self._set_offset_radius(r)
  364. bb = super().get_window_extent(renderer)
  365. return bb
  366. class TickLabels(AxisLabel): # mtext.Text
  367. """
  368. Tick Labels. While derived from Text, this single artist draws all
  369. ticklabels. As in AxisLabel, the position of the text is updated
  370. in the fly, so changing text position has no effect. Otherwise,
  371. the properties can be changed as a normal Text. Unlike the
  372. ticklabels of the mainline matplotlib, properties of single
  373. ticklabel alone cannot modified.
  374. To change the pad between ticks and ticklabels, use set_pad.
  375. """
  376. def __init__(self, *, axis_direction="bottom", **kwargs):
  377. AxisLabel.__init__(self, **kwargs)
  378. self.set_axis_direction(axis_direction)
  379. self._axislabel_pad = 0
  380. def get_ref_artist(self):
  381. # docstring inherited
  382. return self._axis.get_ticklabels()[0]
  383. def set_axis_direction(self, label_direction):
  384. """
  385. Adjust the text angle and text alignment of ticklabels
  386. according to the matplotlib convention.
  387. The *label_direction* must be one of [left, right, bottom, top].
  388. ===================== ========== ========= ========== ==========
  389. property left bottom right top
  390. ===================== ========== ========= ========== ==========
  391. ticklabels angle 90 0 -90 180
  392. ticklabel va center baseline center baseline
  393. ticklabel ha right center right center
  394. ===================== ========== ========= ========== ==========
  395. Note that the text angles are actually relative to (90 + angle
  396. of the direction to the ticklabel), which gives 0 for bottom
  397. axis.
  398. """
  399. self.set_default_alignment(label_direction)
  400. self.set_default_angle(label_direction)
  401. self._axis_direction = label_direction
  402. def invert_axis_direction(self):
  403. label_direction = self._get_opposite_direction(self._axis_direction)
  404. self.set_axis_direction(label_direction)
  405. def _get_ticklabels_offsets(self, renderer, label_direction):
  406. """
  407. Calculate the ticklabel offsets from the tick and their total heights.
  408. The offset only takes account the offset due to the vertical alignment
  409. of the ticklabels: if axis direction is bottom and va is 'top', it will
  410. return 0; if va is 'baseline', it will return (height-descent).
  411. """
  412. whd_list = self.get_texts_widths_heights_descents(renderer)
  413. if not whd_list:
  414. return 0, 0
  415. r = 0
  416. va, ha = self.get_va(), self.get_ha()
  417. if label_direction == "left":
  418. pad = max(w for w, h, d in whd_list)
  419. if ha == "left":
  420. r = pad
  421. elif ha == "center":
  422. r = .5 * pad
  423. elif label_direction == "right":
  424. pad = max(w for w, h, d in whd_list)
  425. if ha == "right":
  426. r = pad
  427. elif ha == "center":
  428. r = .5 * pad
  429. elif label_direction == "bottom":
  430. pad = max(h for w, h, d in whd_list)
  431. if va == "bottom":
  432. r = pad
  433. elif va == "center":
  434. r = .5 * pad
  435. elif va == "baseline":
  436. max_ascent = max(h - d for w, h, d in whd_list)
  437. max_descent = max(d for w, h, d in whd_list)
  438. r = max_ascent
  439. pad = max_ascent + max_descent
  440. elif label_direction == "top":
  441. pad = max(h for w, h, d in whd_list)
  442. if va == "top":
  443. r = pad
  444. elif va == "center":
  445. r = .5 * pad
  446. elif va == "baseline":
  447. max_ascent = max(h - d for w, h, d in whd_list)
  448. max_descent = max(d for w, h, d in whd_list)
  449. r = max_descent
  450. pad = max_ascent + max_descent
  451. # r : offset
  452. # pad : total height of the ticklabels. This will be used to
  453. # calculate the pad for the axislabel.
  454. return r, pad
  455. _default_alignments = dict(left=("center", "right"),
  456. right=("center", "left"),
  457. bottom=("baseline", "center"),
  458. top=("baseline", "center"))
  459. _default_angles = dict(left=90,
  460. right=-90,
  461. bottom=0,
  462. top=180)
  463. def draw(self, renderer):
  464. if not self.get_visible():
  465. self._axislabel_pad = self._get_external_pad()
  466. return
  467. r, total_width = self._get_ticklabels_offsets(renderer,
  468. self._axis_direction)
  469. pad = (self._get_external_pad()
  470. + renderer.points_to_pixels(self.get_pad()))
  471. self._set_offset_radius(r+pad)
  472. for (x, y), a, l in self._locs_angles_labels:
  473. if not l.strip():
  474. continue
  475. self._set_ref_angle(a) # + add_angle
  476. self.set_x(x)
  477. self.set_y(y)
  478. self.set_text(l)
  479. LabelBase.draw(self, renderer)
  480. # the value saved will be used to draw axislabel.
  481. self._axislabel_pad = total_width + pad
  482. def set_locs_angles_labels(self, locs_angles_labels):
  483. self._locs_angles_labels = locs_angles_labels
  484. def get_window_extents(self, renderer):
  485. if not self.get_visible():
  486. self._axislabel_pad = self._get_external_pad()
  487. return []
  488. bboxes = []
  489. r, total_width = self._get_ticklabels_offsets(renderer,
  490. self._axis_direction)
  491. pad = self._get_external_pad() + \
  492. renderer.points_to_pixels(self.get_pad())
  493. self._set_offset_radius(r+pad)
  494. for (x, y), a, l in self._locs_angles_labels:
  495. self._set_ref_angle(a) # + add_angle
  496. self.set_x(x)
  497. self.set_y(y)
  498. self.set_text(l)
  499. bb = LabelBase.get_window_extent(self, renderer)
  500. bboxes.append(bb)
  501. # the value saved will be used to draw axislabel.
  502. self._axislabel_pad = total_width + pad
  503. return bboxes
  504. def get_texts_widths_heights_descents(self, renderer):
  505. """
  506. Return a list of ``(width, height, descent)`` tuples for ticklabels.
  507. Empty labels are left out.
  508. """
  509. whd_list = []
  510. for _loc, _angle, label in self._locs_angles_labels:
  511. if not label.strip():
  512. continue
  513. clean_line, ismath = self._preprocess_math(label)
  514. whd = renderer.get_text_width_height_descent(
  515. clean_line, self._fontproperties, ismath=ismath)
  516. whd_list.append(whd)
  517. return whd_list
  518. class GridlinesCollection(LineCollection):
  519. def __init__(self, *args, which="major", axis="both", **kwargs):
  520. """
  521. Parameters
  522. ----------
  523. which : {"major", "minor"}
  524. axis : {"both", "x", "y"}
  525. """
  526. self._which = which
  527. self._axis = axis
  528. super().__init__(*args, **kwargs)
  529. self.set_grid_helper(None)
  530. def set_which(self, which):
  531. self._which = which
  532. def set_axis(self, axis):
  533. self._axis = axis
  534. def set_grid_helper(self, grid_helper):
  535. self._grid_helper = grid_helper
  536. def draw(self, renderer):
  537. if self._grid_helper is not None:
  538. self._grid_helper.update_lim(self.axes)
  539. gl = self._grid_helper.get_gridlines(self._which, self._axis)
  540. if gl:
  541. self.set_segments([np.transpose(l) for l in gl])
  542. else:
  543. self.set_segments([])
  544. super().draw(renderer)
  545. class AxisArtist(martist.Artist):
  546. """
  547. An artist which draws axis (a line along which the n-th axes coord
  548. is constant) line, ticks, ticklabels, and axis label.
  549. """
  550. zorder = ZORDER = 2.5 # ZORDER is a backcompat alias.
  551. @property
  552. def LABELPAD(self):
  553. return self.label.get_pad()
  554. @LABELPAD.setter
  555. def LABELPAD(self, v):
  556. self.label.set_pad(v)
  557. def __init__(self, axes,
  558. helper,
  559. offset=None,
  560. axis_direction="bottom",
  561. **kwargs):
  562. """
  563. Parameters
  564. ----------
  565. axes : `mpl_toolkits.axisartist.axislines.Axes`
  566. helper : `~mpl_toolkits.axisartist.axislines.AxisArtistHelper`
  567. """
  568. #axes is also used to follow the axis attribute (tick color, etc).
  569. super().__init__(**kwargs)
  570. self.axes = axes
  571. self._axis_artist_helper = helper
  572. if offset is None:
  573. offset = (0, 0)
  574. self.offset_transform = ScaledTranslation(
  575. *offset,
  576. Affine2D().scale(1 / 72) # points to inches.
  577. + self.axes.figure.dpi_scale_trans)
  578. if axis_direction in ["left", "right"]:
  579. self.axis = axes.yaxis
  580. else:
  581. self.axis = axes.xaxis
  582. self._axisline_style = None
  583. self._axis_direction = axis_direction
  584. self._init_line()
  585. self._init_ticks(**kwargs)
  586. self._init_offsetText(axis_direction)
  587. self._init_label()
  588. # axis direction
  589. self._ticklabel_add_angle = 0.
  590. self._axislabel_add_angle = 0.
  591. self.set_axis_direction(axis_direction)
  592. @cbook.deprecated("3.3")
  593. @property
  594. def dpi_transform(self):
  595. return Affine2D().scale(1 / 72) + self.axes.figure.dpi_scale_trans
  596. # axis direction
  597. def set_axis_direction(self, axis_direction):
  598. """
  599. Adjust the direction, text angle, text alignment of
  600. ticklabels, labels following the matplotlib convention for
  601. the rectangle axes.
  602. The *axis_direction* must be one of [left, right, bottom, top].
  603. ===================== ========== ========= ========== ==========
  604. property left bottom right top
  605. ===================== ========== ========= ========== ==========
  606. ticklabels location "-" "+" "+" "-"
  607. axislabel location "-" "+" "+" "-"
  608. ticklabels angle 90 0 -90 180
  609. ticklabel va center baseline center baseline
  610. ticklabel ha right center right center
  611. axislabel angle 180 0 0 180
  612. axislabel va center top center bottom
  613. axislabel ha right center right center
  614. ===================== ========== ========= ========== ==========
  615. Note that the direction "+" and "-" are relative to the direction of
  616. the increasing coordinate. Also, the text angles are actually
  617. relative to (90 + angle of the direction to the ticklabel),
  618. which gives 0 for bottom axis.
  619. """
  620. self.major_ticklabels.set_axis_direction(axis_direction)
  621. self.label.set_axis_direction(axis_direction)
  622. self._axis_direction = axis_direction
  623. if axis_direction in ["left", "top"]:
  624. self.set_ticklabel_direction("-")
  625. self.set_axislabel_direction("-")
  626. else:
  627. self.set_ticklabel_direction("+")
  628. self.set_axislabel_direction("+")
  629. def set_ticklabel_direction(self, tick_direction):
  630. r"""
  631. Adjust the direction of the ticklabel.
  632. Note that the *label_direction*\s '+' and '-' are relative to the
  633. direction of the increasing coordinate.
  634. Parameters
  635. ----------
  636. tick_direction : {"+", "-"}
  637. """
  638. self._ticklabel_add_angle = cbook._check_getitem(
  639. {"+": 0, "-": 180}, tick_direction=tick_direction)
  640. def invert_ticklabel_direction(self):
  641. self._ticklabel_add_angle = (self._ticklabel_add_angle + 180) % 360
  642. self.major_ticklabels.invert_axis_direction()
  643. self.minor_ticklabels.invert_axis_direction()
  644. def set_axislabel_direction(self, label_direction):
  645. r"""
  646. Adjust the direction of the axislabel.
  647. Note that the *label_direction*\s '+' and '-' are relative to the
  648. direction of the increasing coordinate.
  649. Parameters
  650. ----------
  651. tick_direction : {"+", "-"}
  652. """
  653. self._axislabel_add_angle = cbook._check_getitem(
  654. {"+": 0, "-": 180}, label_direction=label_direction)
  655. def get_transform(self):
  656. return self.axes.transAxes + self.offset_transform
  657. def get_helper(self):
  658. """
  659. Return axis artist helper instance.
  660. """
  661. return self._axis_artist_helper
  662. def set_axisline_style(self, axisline_style=None, **kwargs):
  663. """
  664. Set the axisline style.
  665. The new style is completely defined by the passed attributes. Existing
  666. style attributes are forgotten.
  667. Parameters
  668. ----------
  669. axisline_style : str or None
  670. The line style, e.g. '->', optionally followed by a comma-separated
  671. list of attributes. Alternatively, the attributes can be provided
  672. as keywords.
  673. If *None* this returns a string containing the available styles.
  674. Examples
  675. --------
  676. The following two commands are equal:
  677. >>> set_axisline_style("->,size=1.5")
  678. >>> set_axisline_style("->", size=1.5)
  679. """
  680. if axisline_style is None:
  681. return AxislineStyle.pprint_styles()
  682. if isinstance(axisline_style, AxislineStyle._Base):
  683. self._axisline_style = axisline_style
  684. else:
  685. self._axisline_style = AxislineStyle(axisline_style, **kwargs)
  686. self._init_line()
  687. def get_axisline_style(self):
  688. """Return the current axisline style."""
  689. return self._axisline_style
  690. def _init_line(self):
  691. """
  692. Initialize the *line* artist that is responsible to draw the axis line.
  693. """
  694. tran = (self._axis_artist_helper.get_line_transform(self.axes)
  695. + self.offset_transform)
  696. axisline_style = self.get_axisline_style()
  697. if axisline_style is None:
  698. self.line = PathPatch(
  699. self._axis_artist_helper.get_line(self.axes),
  700. color=rcParams['axes.edgecolor'],
  701. fill=False,
  702. linewidth=rcParams['axes.linewidth'],
  703. capstyle=rcParams['lines.solid_capstyle'],
  704. joinstyle=rcParams['lines.solid_joinstyle'],
  705. transform=tran)
  706. else:
  707. self.line = axisline_style(self, transform=tran)
  708. def _draw_line(self, renderer):
  709. self.line.set_path(self._axis_artist_helper.get_line(self.axes))
  710. if self.get_axisline_style() is not None:
  711. self.line.set_line_mutation_scale(self.major_ticklabels.get_size())
  712. self.line.draw(renderer)
  713. def _init_ticks(self, **kwargs):
  714. axis_name = self.axis.axis_name
  715. trans = (self._axis_artist_helper.get_tick_transform(self.axes)
  716. + self.offset_transform)
  717. self.major_ticks = Ticks(
  718. kwargs.get(
  719. "major_tick_size", rcParams[f"{axis_name}tick.major.size"]),
  720. axis=self.axis, transform=trans)
  721. self.minor_ticks = Ticks(
  722. kwargs.get(
  723. "minor_tick_size", rcParams[f"{axis_name}tick.minor.size"]),
  724. axis=self.axis, transform=trans)
  725. size = rcParams[f"{axis_name}tick.labelsize"]
  726. self.major_ticklabels = TickLabels(
  727. axis=self.axis,
  728. axis_direction=self._axis_direction,
  729. figure=self.axes.figure,
  730. transform=trans,
  731. fontsize=size,
  732. pad=kwargs.get(
  733. "major_tick_pad", rcParams[f"{axis_name}tick.major.pad"]),
  734. )
  735. self.minor_ticklabels = TickLabels(
  736. axis=self.axis,
  737. axis_direction=self._axis_direction,
  738. figure=self.axes.figure,
  739. transform=trans,
  740. fontsize=size,
  741. pad=kwargs.get(
  742. "minor_tick_pad", rcParams[f"{axis_name}tick.minor.pad"]),
  743. )
  744. def _get_tick_info(self, tick_iter):
  745. """
  746. Return a pair of:
  747. - list of locs and angles for ticks
  748. - list of locs, angles and labels for ticklabels.
  749. """
  750. ticks_loc_angle = []
  751. ticklabels_loc_angle_label = []
  752. ticklabel_add_angle = self._ticklabel_add_angle
  753. for loc, angle_normal, angle_tangent, label in tick_iter:
  754. angle_label = angle_tangent - 90 + ticklabel_add_angle
  755. angle_tick = (angle_normal
  756. if 90 <= (angle_label - angle_normal) % 360 <= 270
  757. else angle_normal + 180)
  758. ticks_loc_angle.append([loc, angle_tick])
  759. ticklabels_loc_angle_label.append([loc, angle_label, label])
  760. return ticks_loc_angle, ticklabels_loc_angle_label
  761. def _update_ticks(self, renderer):
  762. # set extra pad for major and minor ticklabels: use ticksize of
  763. # majorticks even for minor ticks. not clear what is best.
  764. dpi_cor = renderer.points_to_pixels(1.)
  765. if self.major_ticks.get_visible() and self.major_ticks.get_tick_out():
  766. self.major_ticklabels._set_external_pad(
  767. self.major_ticks._ticksize * dpi_cor)
  768. self.minor_ticklabels._set_external_pad(
  769. self.major_ticks._ticksize * dpi_cor)
  770. else:
  771. self.major_ticklabels._set_external_pad(0)
  772. self.minor_ticklabels._set_external_pad(0)
  773. majortick_iter, minortick_iter = \
  774. self._axis_artist_helper.get_tick_iterators(self.axes)
  775. tick_loc_angle, ticklabel_loc_angle_label = \
  776. self._get_tick_info(majortick_iter)
  777. self.major_ticks.set_locs_angles(tick_loc_angle)
  778. self.major_ticklabels.set_locs_angles_labels(ticklabel_loc_angle_label)
  779. # minor ticks
  780. tick_loc_angle, ticklabel_loc_angle_label = \
  781. self._get_tick_info(minortick_iter)
  782. self.minor_ticks.set_locs_angles(tick_loc_angle)
  783. self.minor_ticklabels.set_locs_angles_labels(ticklabel_loc_angle_label)
  784. return self.major_ticklabels.get_window_extents(renderer)
  785. def _draw_ticks(self, renderer):
  786. extents = self._update_ticks(renderer)
  787. self.major_ticks.draw(renderer)
  788. self.major_ticklabels.draw(renderer)
  789. self.minor_ticks.draw(renderer)
  790. self.minor_ticklabels.draw(renderer)
  791. if (self.major_ticklabels.get_visible()
  792. or self.minor_ticklabels.get_visible()):
  793. self._draw_offsetText(renderer)
  794. return extents
  795. def _draw_ticks2(self, renderer):
  796. # set extra pad for major and minor ticklabels: use ticksize of
  797. # majorticks even for minor ticks. not clear what is best.
  798. dpi_cor = renderer.points_to_pixels(1.)
  799. if self.major_ticks.get_visible() and self.major_ticks.get_tick_out():
  800. self.major_ticklabels._set_external_pad(
  801. self.major_ticks._ticksize * dpi_cor)
  802. self.minor_ticklabels._set_external_pad(
  803. self.major_ticks._ticksize * dpi_cor)
  804. else:
  805. self.major_ticklabels._set_external_pad(0)
  806. self.minor_ticklabels._set_external_pad(0)
  807. majortick_iter, minortick_iter = \
  808. self._axis_artist_helper.get_tick_iterators(self.axes)
  809. tick_loc_angle, ticklabel_loc_angle_label = \
  810. self._get_tick_info(majortick_iter)
  811. self.major_ticks.set_locs_angles(tick_loc_angle)
  812. self.major_ticklabels.set_locs_angles_labels(ticklabel_loc_angle_label)
  813. self.major_ticks.draw(renderer)
  814. self.major_ticklabels.draw(renderer)
  815. # minor ticks
  816. tick_loc_angle, ticklabel_loc_angle_label = \
  817. self._get_tick_info(minortick_iter)
  818. self.minor_ticks.set_locs_angles(tick_loc_angle)
  819. self.minor_ticklabels.set_locs_angles_labels(ticklabel_loc_angle_label)
  820. self.minor_ticks.draw(renderer)
  821. self.minor_ticklabels.draw(renderer)
  822. if (self.major_ticklabels.get_visible()
  823. or self.minor_ticklabels.get_visible()):
  824. self._draw_offsetText(renderer)
  825. return self.major_ticklabels.get_window_extents(renderer)
  826. _offsetText_pos = dict(left=(0, 1, "bottom", "right"),
  827. right=(1, 1, "bottom", "left"),
  828. bottom=(1, 0, "top", "right"),
  829. top=(1, 1, "bottom", "right"))
  830. def _init_offsetText(self, direction):
  831. x, y, va, ha = self._offsetText_pos[direction]
  832. self.offsetText = mtext.Annotation(
  833. "",
  834. xy=(x, y), xycoords="axes fraction",
  835. xytext=(0, 0), textcoords="offset points",
  836. color=rcParams['xtick.color'],
  837. horizontalalignment=ha, verticalalignment=va,
  838. )
  839. self.offsetText.set_transform(IdentityTransform())
  840. self.axes._set_artist_props(self.offsetText)
  841. def _update_offsetText(self):
  842. self.offsetText.set_text(self.axis.major.formatter.get_offset())
  843. self.offsetText.set_size(self.major_ticklabels.get_size())
  844. offset = (self.major_ticklabels.get_pad()
  845. + self.major_ticklabels.get_size()
  846. + 2)
  847. self.offsetText.xyann = (0, offset)
  848. def _draw_offsetText(self, renderer):
  849. self._update_offsetText()
  850. self.offsetText.draw(renderer)
  851. def _init_label(self, **kwargs):
  852. tr = (self._axis_artist_helper.get_axislabel_transform(self.axes)
  853. + self.offset_transform)
  854. self.label = AxisLabel(
  855. 0, 0, "__from_axes__",
  856. color="auto",
  857. fontsize=kwargs.get("labelsize", rcParams['axes.labelsize']),
  858. fontweight=rcParams['axes.labelweight'],
  859. axis=self.axis,
  860. transform=tr,
  861. axis_direction=self._axis_direction,
  862. )
  863. self.label.set_figure(self.axes.figure)
  864. labelpad = kwargs.get("labelpad", 5)
  865. self.label.set_pad(labelpad)
  866. def _update_label(self, renderer):
  867. if not self.label.get_visible():
  868. return
  869. if self._ticklabel_add_angle != self._axislabel_add_angle:
  870. if ((self.major_ticks.get_visible()
  871. and not self.major_ticks.get_tick_out())
  872. or (self.minor_ticks.get_visible()
  873. and not self.major_ticks.get_tick_out())):
  874. axislabel_pad = self.major_ticks._ticksize
  875. else:
  876. axislabel_pad = 0
  877. else:
  878. axislabel_pad = max(self.major_ticklabels._axislabel_pad,
  879. self.minor_ticklabels._axislabel_pad)
  880. self.label._set_external_pad(axislabel_pad)
  881. xy, angle_tangent = \
  882. self._axis_artist_helper.get_axislabel_pos_angle(self.axes)
  883. if xy is None:
  884. return
  885. angle_label = angle_tangent - 90
  886. x, y = xy
  887. self.label._set_ref_angle(angle_label+self._axislabel_add_angle)
  888. self.label.set(x=x, y=y)
  889. def _draw_label(self, renderer):
  890. self._update_label(renderer)
  891. self.label.draw(renderer)
  892. def _draw_label2(self, renderer):
  893. if not self.label.get_visible():
  894. return
  895. if self._ticklabel_add_angle != self._axislabel_add_angle:
  896. if ((self.major_ticks.get_visible()
  897. and not self.major_ticks.get_tick_out())
  898. or (self.minor_ticks.get_visible()
  899. and not self.major_ticks.get_tick_out())):
  900. axislabel_pad = self.major_ticks._ticksize
  901. else:
  902. axislabel_pad = 0
  903. else:
  904. axislabel_pad = max(self.major_ticklabels._axislabel_pad,
  905. self.minor_ticklabels._axislabel_pad)
  906. self.label._set_external_pad(axislabel_pad)
  907. xy, angle_tangent = \
  908. self._axis_artist_helper.get_axislabel_pos_angle(self.axes)
  909. if xy is None:
  910. return
  911. angle_label = angle_tangent - 90
  912. x, y = xy
  913. self.label._set_ref_angle(angle_label+self._axislabel_add_angle)
  914. self.label.set(x=x, y=y)
  915. self.label.draw(renderer)
  916. def set_label(self, s):
  917. self.label.set_text(s)
  918. def get_tightbbox(self, renderer):
  919. if not self.get_visible():
  920. return
  921. self._axis_artist_helper.update_lim(self.axes)
  922. self._update_ticks(renderer)
  923. self._update_label(renderer)
  924. bb = [
  925. *self.major_ticklabels.get_window_extents(renderer),
  926. *self.minor_ticklabels.get_window_extents(renderer),
  927. self.label.get_window_extent(renderer),
  928. self.offsetText.get_window_extent(renderer),
  929. ]
  930. bb = [b for b in bb if b and (b.width != 0 or b.height != 0)]
  931. if bb:
  932. _bbox = Bbox.union(bb)
  933. return _bbox
  934. else:
  935. return None
  936. @martist.allow_rasterization
  937. def draw(self, renderer):
  938. # docstring inherited
  939. if not self.get_visible():
  940. return
  941. renderer.open_group(__name__, gid=self.get_gid())
  942. self._axis_artist_helper.update_lim(self.axes)
  943. self._draw_ticks(renderer)
  944. self._draw_line(renderer)
  945. self._draw_label(renderer)
  946. renderer.close_group(__name__)
  947. def toggle(self, all=None, ticks=None, ticklabels=None, label=None):
  948. """
  949. Toggle visibility of ticks, ticklabels, and (axis) label.
  950. To turn all off, ::
  951. axis.toggle(all=False)
  952. To turn all off but ticks on ::
  953. axis.toggle(all=False, ticks=True)
  954. To turn all on but (axis) label off ::
  955. axis.toggle(all=True, label=False))
  956. """
  957. if all:
  958. _ticks, _ticklabels, _label = True, True, True
  959. elif all is not None:
  960. _ticks, _ticklabels, _label = False, False, False
  961. else:
  962. _ticks, _ticklabels, _label = None, None, None
  963. if ticks is not None:
  964. _ticks = ticks
  965. if ticklabels is not None:
  966. _ticklabels = ticklabels
  967. if label is not None:
  968. _label = label
  969. if _ticks is not None:
  970. self.major_ticks.set_visible(_ticks)
  971. self.minor_ticks.set_visible(_ticks)
  972. if _ticklabels is not None:
  973. self.major_ticklabels.set_visible(_ticklabels)
  974. self.minor_ticklabels.set_visible(_ticklabels)
  975. if _label is not None:
  976. self.label.set_visible(_label)