text.py 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937
  1. """
  2. Classes for including text in a figure.
  3. """
  4. import contextlib
  5. import logging
  6. import math
  7. import weakref
  8. import numpy as np
  9. from . import artist, cbook, docstring, rcParams
  10. from .artist import Artist
  11. from .font_manager import FontProperties
  12. from .patches import FancyArrowPatch, FancyBboxPatch, Rectangle
  13. from .textpath import TextPath # Unused, but imported by others.
  14. from .transforms import (
  15. Affine2D, Bbox, BboxBase, BboxTransformTo, IdentityTransform, Transform)
  16. _log = logging.getLogger(__name__)
  17. @contextlib.contextmanager
  18. def _wrap_text(textobj):
  19. """Temporarily inserts newlines if the wrap option is enabled."""
  20. if textobj.get_wrap():
  21. old_text = textobj.get_text()
  22. try:
  23. textobj.set_text(textobj._get_wrapped_text())
  24. yield textobj
  25. finally:
  26. textobj.set_text(old_text)
  27. else:
  28. yield textobj
  29. # Extracted from Text's method to serve as a function
  30. def get_rotation(rotation):
  31. """
  32. Return *rotation* normalized to an angle between 0 and 360 degrees.
  33. Parameters
  34. ----------
  35. rotation : float or {None, 'horizontal', 'vertical'}
  36. Rotation angle in degrees. *None* and 'horizontal' equal 0,
  37. 'vertical' equals 90.
  38. Returns
  39. -------
  40. float
  41. """
  42. try:
  43. return float(rotation) % 360
  44. except (ValueError, TypeError) as err:
  45. if cbook._str_equal(rotation, 'horizontal') or rotation is None:
  46. return 0.
  47. elif cbook._str_equal(rotation, 'vertical'):
  48. return 90.
  49. else:
  50. raise ValueError("rotation is {!r}; expected either 'horizontal', "
  51. "'vertical', numeric value, or None"
  52. .format(rotation)) from err
  53. def _get_textbox(text, renderer):
  54. """
  55. Calculate the bounding box of the text. Unlike
  56. :meth:`matplotlib.text.Text.get_extents` method, The bbox size of
  57. the text before the rotation is calculated.
  58. """
  59. # TODO : This function may move into the Text class as a method. As a
  60. # matter of fact, The information from the _get_textbox function
  61. # should be available during the Text._get_layout() call, which is
  62. # called within the _get_textbox. So, it would better to move this
  63. # function as a method with some refactoring of _get_layout method.
  64. projected_xs = []
  65. projected_ys = []
  66. theta = np.deg2rad(text.get_rotation())
  67. tr = Affine2D().rotate(-theta)
  68. _, parts, d = text._get_layout(renderer)
  69. for t, wh, x, y in parts:
  70. w, h = wh
  71. xt1, yt1 = tr.transform((x, y))
  72. yt1 -= d
  73. xt2, yt2 = xt1 + w, yt1 + h
  74. projected_xs.extend([xt1, xt2])
  75. projected_ys.extend([yt1, yt2])
  76. xt_box, yt_box = min(projected_xs), min(projected_ys)
  77. w_box, h_box = max(projected_xs) - xt_box, max(projected_ys) - yt_box
  78. x_box, y_box = Affine2D().rotate(theta).transform((xt_box, yt_box))
  79. return x_box, y_box, w_box, h_box
  80. @cbook._define_aliases({
  81. "color": ["c"],
  82. "fontfamily": ["family"],
  83. "fontproperties": ["font", "font_properties"],
  84. "horizontalalignment": ["ha"],
  85. "multialignment": ["ma"],
  86. "fontname": ["name"],
  87. "fontsize": ["size"],
  88. "fontstretch": ["stretch"],
  89. "fontstyle": ["style"],
  90. "fontvariant": ["variant"],
  91. "verticalalignment": ["va"],
  92. "fontweight": ["weight"],
  93. })
  94. class Text(Artist):
  95. """Handle storing and drawing of text in window or data coordinates."""
  96. zorder = 3
  97. _cached = cbook.maxdict(50)
  98. def __repr__(self):
  99. return "Text(%s, %s, %s)" % (self._x, self._y, repr(self._text))
  100. def __init__(self,
  101. x=0, y=0, text='',
  102. color=None, # defaults to rc params
  103. verticalalignment='baseline',
  104. horizontalalignment='left',
  105. multialignment=None,
  106. fontproperties=None, # defaults to FontProperties()
  107. rotation=None,
  108. linespacing=None,
  109. rotation_mode=None,
  110. usetex=None, # defaults to rcParams['text.usetex']
  111. wrap=False,
  112. **kwargs
  113. ):
  114. """
  115. Create a `.Text` instance at *x*, *y* with string *text*.
  116. Valid keyword arguments are:
  117. %(Text)s
  118. """
  119. Artist.__init__(self)
  120. self._x, self._y = x, y
  121. self._text = ''
  122. self.set_text(text)
  123. self.set_color(color if color is not None else rcParams["text.color"])
  124. self.set_fontproperties(fontproperties)
  125. self.set_usetex(usetex)
  126. self.set_wrap(wrap)
  127. self.set_verticalalignment(verticalalignment)
  128. self.set_horizontalalignment(horizontalalignment)
  129. self._multialignment = multialignment
  130. self._rotation = rotation
  131. self._bbox_patch = None # a FancyBboxPatch instance
  132. self._renderer = None
  133. if linespacing is None:
  134. linespacing = 1.2 # Maybe use rcParam later.
  135. self._linespacing = linespacing
  136. self.set_rotation_mode(rotation_mode)
  137. self.update(kwargs)
  138. def update(self, kwargs):
  139. # docstring inherited
  140. # make a copy so we do not mutate user input!
  141. kwargs = dict(kwargs)
  142. sentinel = object() # bbox can be None, so use another sentinel.
  143. # Update fontproperties first, as it has lowest priority.
  144. fontproperties = kwargs.pop("fontproperties", sentinel)
  145. if fontproperties is not sentinel:
  146. self.set_fontproperties(fontproperties)
  147. # Update bbox last, as it depends on font properties.
  148. bbox = kwargs.pop("bbox", sentinel)
  149. super().update(kwargs)
  150. if bbox is not sentinel:
  151. self.set_bbox(bbox)
  152. def __getstate__(self):
  153. d = super().__getstate__()
  154. # remove the cached _renderer (if it exists)
  155. d['_renderer'] = None
  156. return d
  157. def contains(self, mouseevent):
  158. """
  159. Return whether the mouse event occurred inside the axis-aligned
  160. bounding-box of the text.
  161. """
  162. inside, info = self._default_contains(mouseevent)
  163. if inside is not None:
  164. return inside, info
  165. if not self.get_visible() or self._renderer is None:
  166. return False, {}
  167. # Explicitly use Text.get_window_extent(self) and not
  168. # self.get_window_extent() so that Annotation.contains does not
  169. # accidentally cover the entire annotation bounding box.
  170. bbox = Text.get_window_extent(self)
  171. inside = (bbox.x0 <= mouseevent.x <= bbox.x1
  172. and bbox.y0 <= mouseevent.y <= bbox.y1)
  173. cattr = {}
  174. # if the text has a surrounding patch, also check containment for it,
  175. # and merge the results with the results for the text.
  176. if self._bbox_patch:
  177. patch_inside, patch_cattr = self._bbox_patch.contains(mouseevent)
  178. inside = inside or patch_inside
  179. cattr["bbox_patch"] = patch_cattr
  180. return inside, cattr
  181. def _get_xy_display(self):
  182. """
  183. Get the (possibly unit converted) transformed x, y in display coords.
  184. """
  185. x, y = self.get_unitless_position()
  186. return self.get_transform().transform((x, y))
  187. def _get_multialignment(self):
  188. if self._multialignment is not None:
  189. return self._multialignment
  190. else:
  191. return self._horizontalalignment
  192. def get_rotation(self):
  193. """Return the text angle in degrees between 0 and 360."""
  194. return get_rotation(self._rotation) # string_or_number -> number
  195. def set_rotation_mode(self, m):
  196. """
  197. Set text rotation mode.
  198. Parameters
  199. ----------
  200. m : {None, 'default', 'anchor'}
  201. If ``None`` or ``"default"``, the text will be first rotated, then
  202. aligned according to their horizontal and vertical alignments. If
  203. ``"anchor"``, then alignment occurs before rotation.
  204. """
  205. cbook._check_in_list(["anchor", "default", None], rotation_mode=m)
  206. self._rotation_mode = m
  207. self.stale = True
  208. def get_rotation_mode(self):
  209. """Return the text rotation mode."""
  210. return self._rotation_mode
  211. def update_from(self, other):
  212. # docstring inherited
  213. Artist.update_from(self, other)
  214. self._color = other._color
  215. self._multialignment = other._multialignment
  216. self._verticalalignment = other._verticalalignment
  217. self._horizontalalignment = other._horizontalalignment
  218. self._fontproperties = other._fontproperties.copy()
  219. self._usetex = other._usetex
  220. self._rotation = other._rotation
  221. self._picker = other._picker
  222. self._linespacing = other._linespacing
  223. self.stale = True
  224. def _get_layout(self, renderer):
  225. """
  226. Return the extent (bbox) of the text together with
  227. multiple-alignment information. Note that it returns an extent
  228. of a rotated text when necessary.
  229. """
  230. key = self.get_prop_tup(renderer=renderer)
  231. if key in self._cached:
  232. return self._cached[key]
  233. thisx, thisy = 0.0, 0.0
  234. lines = self.get_text().split("\n") # Ensures lines is not empty.
  235. ws = []
  236. hs = []
  237. xs = []
  238. ys = []
  239. # Full vertical extent of font, including ascenders and descenders:
  240. _, lp_h, lp_d = renderer.get_text_width_height_descent(
  241. "lp", self._fontproperties,
  242. ismath="TeX" if self.get_usetex() else False)
  243. min_dy = (lp_h - lp_d) * self._linespacing
  244. for i, line in enumerate(lines):
  245. clean_line, ismath = self._preprocess_math(line)
  246. if clean_line:
  247. w, h, d = renderer.get_text_width_height_descent(
  248. clean_line, self._fontproperties, ismath=ismath)
  249. else:
  250. w = h = d = 0
  251. # For multiline text, increase the line spacing when the text
  252. # net-height (excluding baseline) is larger than that of a "l"
  253. # (e.g., use of superscripts), which seems what TeX does.
  254. h = max(h, lp_h)
  255. d = max(d, lp_d)
  256. ws.append(w)
  257. hs.append(h)
  258. # Metrics of the last line that are needed later:
  259. baseline = (h - d) - thisy
  260. if i == 0:
  261. # position at baseline
  262. thisy = -(h - d)
  263. else:
  264. # put baseline a good distance from bottom of previous line
  265. thisy -= max(min_dy, (h - d) * self._linespacing)
  266. xs.append(thisx) # == 0.
  267. ys.append(thisy)
  268. thisy -= d
  269. # Metrics of the last line that are needed later:
  270. descent = d
  271. # Bounding box definition:
  272. width = max(ws)
  273. xmin = 0
  274. xmax = width
  275. ymax = 0
  276. ymin = ys[-1] - descent # baseline of last line minus its descent
  277. height = ymax - ymin
  278. # get the rotation matrix
  279. M = Affine2D().rotate_deg(self.get_rotation())
  280. # now offset the individual text lines within the box
  281. malign = self._get_multialignment()
  282. if malign == 'left':
  283. offset_layout = [(x, y) for x, y in zip(xs, ys)]
  284. elif malign == 'center':
  285. offset_layout = [(x + width / 2 - w / 2, y)
  286. for x, y, w in zip(xs, ys, ws)]
  287. elif malign == 'right':
  288. offset_layout = [(x + width - w, y)
  289. for x, y, w in zip(xs, ys, ws)]
  290. # the corners of the unrotated bounding box
  291. corners_horiz = np.array(
  292. [(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)])
  293. # now rotate the bbox
  294. corners_rotated = M.transform(corners_horiz)
  295. # compute the bounds of the rotated box
  296. xmin = corners_rotated[:, 0].min()
  297. xmax = corners_rotated[:, 0].max()
  298. ymin = corners_rotated[:, 1].min()
  299. ymax = corners_rotated[:, 1].max()
  300. width = xmax - xmin
  301. height = ymax - ymin
  302. # Now move the box to the target position offset the display
  303. # bbox by alignment
  304. halign = self._horizontalalignment
  305. valign = self._verticalalignment
  306. rotation_mode = self.get_rotation_mode()
  307. if rotation_mode != "anchor":
  308. # compute the text location in display coords and the offsets
  309. # necessary to align the bbox with that location
  310. if halign == 'center':
  311. offsetx = (xmin + xmax) / 2
  312. elif halign == 'right':
  313. offsetx = xmax
  314. else:
  315. offsetx = xmin
  316. if valign == 'center':
  317. offsety = (ymin + ymax) / 2
  318. elif valign == 'top':
  319. offsety = ymax
  320. elif valign == 'baseline':
  321. offsety = ymin + descent
  322. elif valign == 'center_baseline':
  323. offsety = ymin + height - baseline / 2.0
  324. else:
  325. offsety = ymin
  326. else:
  327. xmin1, ymin1 = corners_horiz[0]
  328. xmax1, ymax1 = corners_horiz[2]
  329. if halign == 'center':
  330. offsetx = (xmin1 + xmax1) / 2.0
  331. elif halign == 'right':
  332. offsetx = xmax1
  333. else:
  334. offsetx = xmin1
  335. if valign == 'center':
  336. offsety = (ymin1 + ymax1) / 2.0
  337. elif valign == 'top':
  338. offsety = ymax1
  339. elif valign == 'baseline':
  340. offsety = ymax1 - baseline
  341. elif valign == 'center_baseline':
  342. offsety = ymax1 - baseline / 2.0
  343. else:
  344. offsety = ymin1
  345. offsetx, offsety = M.transform((offsetx, offsety))
  346. xmin -= offsetx
  347. ymin -= offsety
  348. bbox = Bbox.from_bounds(xmin, ymin, width, height)
  349. # now rotate the positions around the first (x, y) position
  350. xys = M.transform(offset_layout) - (offsetx, offsety)
  351. ret = bbox, list(zip(lines, zip(ws, hs), *xys.T)), descent
  352. self._cached[key] = ret
  353. return ret
  354. def set_bbox(self, rectprops):
  355. """
  356. Draw a bounding box around self.
  357. Parameters
  358. ----------
  359. rectprops : dict with properties for `.patches.FancyBboxPatch`
  360. The default boxstyle is 'square'. The mutation
  361. scale of the `.patches.FancyBboxPatch` is set to the fontsize.
  362. Examples
  363. --------
  364. ::
  365. t.set_bbox(dict(facecolor='red', alpha=0.5))
  366. """
  367. if rectprops is not None:
  368. props = rectprops.copy()
  369. boxstyle = props.pop("boxstyle", None)
  370. pad = props.pop("pad", None)
  371. if boxstyle is None:
  372. boxstyle = "square"
  373. if pad is None:
  374. pad = 4 # points
  375. pad /= self.get_size() # to fraction of font size
  376. else:
  377. if pad is None:
  378. pad = 0.3
  379. # boxstyle could be a callable or a string
  380. if isinstance(boxstyle, str) and "pad" not in boxstyle:
  381. boxstyle += ",pad=%0.2f" % pad
  382. bbox_transmuter = props.pop("bbox_transmuter", None)
  383. self._bbox_patch = FancyBboxPatch(
  384. (0., 0.),
  385. 1., 1.,
  386. boxstyle=boxstyle,
  387. bbox_transmuter=bbox_transmuter,
  388. transform=IdentityTransform(),
  389. **props)
  390. else:
  391. self._bbox_patch = None
  392. self._update_clip_properties()
  393. def get_bbox_patch(self):
  394. """
  395. Return the bbox Patch, or None if the `.patches.FancyBboxPatch`
  396. is not made.
  397. """
  398. return self._bbox_patch
  399. def update_bbox_position_size(self, renderer):
  400. """
  401. Update the location and the size of the bbox.
  402. This method should be used when the position and size of the bbox needs
  403. to be updated before actually drawing the bbox.
  404. """
  405. if self._bbox_patch:
  406. trans = self.get_transform()
  407. # don't use self.get_unitless_position here, which refers to text
  408. # position in Text:
  409. posx = float(self.convert_xunits(self._x))
  410. posy = float(self.convert_yunits(self._y))
  411. posx, posy = trans.transform((posx, posy))
  412. x_box, y_box, w_box, h_box = _get_textbox(self, renderer)
  413. self._bbox_patch.set_bounds(0., 0., w_box, h_box)
  414. self._bbox_patch.set_transform(
  415. Affine2D()
  416. .rotate_deg(self.get_rotation())
  417. .translate(posx + x_box, posy + y_box))
  418. fontsize_in_pixel = renderer.points_to_pixels(self.get_size())
  419. self._bbox_patch.set_mutation_scale(fontsize_in_pixel)
  420. def _draw_bbox(self, renderer, posx, posy):
  421. """
  422. Update the location and size of the bbox (`.patches.FancyBboxPatch`),
  423. and draw.
  424. """
  425. x_box, y_box, w_box, h_box = _get_textbox(self, renderer)
  426. self._bbox_patch.set_bounds(0., 0., w_box, h_box)
  427. theta = np.deg2rad(self.get_rotation())
  428. tr = Affine2D().rotate(theta)
  429. tr = tr.translate(posx + x_box, posy + y_box)
  430. self._bbox_patch.set_transform(tr)
  431. fontsize_in_pixel = renderer.points_to_pixels(self.get_size())
  432. self._bbox_patch.set_mutation_scale(fontsize_in_pixel)
  433. self._bbox_patch.draw(renderer)
  434. def _update_clip_properties(self):
  435. clipprops = dict(clip_box=self.clipbox,
  436. clip_path=self._clippath,
  437. clip_on=self._clipon)
  438. if self._bbox_patch:
  439. self._bbox_patch.update(clipprops)
  440. def set_clip_box(self, clipbox):
  441. # docstring inherited.
  442. super().set_clip_box(clipbox)
  443. self._update_clip_properties()
  444. def set_clip_path(self, path, transform=None):
  445. # docstring inherited.
  446. super().set_clip_path(path, transform)
  447. self._update_clip_properties()
  448. def set_clip_on(self, b):
  449. # docstring inherited.
  450. super().set_clip_on(b)
  451. self._update_clip_properties()
  452. def get_wrap(self):
  453. """Return whether the text can be wrapped."""
  454. return self._wrap
  455. def set_wrap(self, wrap):
  456. """
  457. Set whether the text can be wrapped.
  458. Parameters
  459. ----------
  460. wrap : bool
  461. """
  462. self._wrap = wrap
  463. def _get_wrap_line_width(self):
  464. """
  465. Return the maximum line width for wrapping text based on the current
  466. orientation.
  467. """
  468. x0, y0 = self.get_transform().transform(self.get_position())
  469. figure_box = self.get_figure().get_window_extent()
  470. # Calculate available width based on text alignment
  471. alignment = self.get_horizontalalignment()
  472. self.set_rotation_mode('anchor')
  473. rotation = self.get_rotation()
  474. left = self._get_dist_to_box(rotation, x0, y0, figure_box)
  475. right = self._get_dist_to_box(
  476. (180 + rotation) % 360, x0, y0, figure_box)
  477. if alignment == 'left':
  478. line_width = left
  479. elif alignment == 'right':
  480. line_width = right
  481. else:
  482. line_width = 2 * min(left, right)
  483. return line_width
  484. def _get_dist_to_box(self, rotation, x0, y0, figure_box):
  485. """
  486. Return the distance from the given points to the boundaries of a
  487. rotated box, in pixels.
  488. """
  489. if rotation > 270:
  490. quad = rotation - 270
  491. h1 = y0 / math.cos(math.radians(quad))
  492. h2 = (figure_box.x1 - x0) / math.cos(math.radians(90 - quad))
  493. elif rotation > 180:
  494. quad = rotation - 180
  495. h1 = x0 / math.cos(math.radians(quad))
  496. h2 = y0 / math.cos(math.radians(90 - quad))
  497. elif rotation > 90:
  498. quad = rotation - 90
  499. h1 = (figure_box.y1 - y0) / math.cos(math.radians(quad))
  500. h2 = x0 / math.cos(math.radians(90 - quad))
  501. else:
  502. h1 = (figure_box.x1 - x0) / math.cos(math.radians(rotation))
  503. h2 = (figure_box.y1 - y0) / math.cos(math.radians(90 - rotation))
  504. return min(h1, h2)
  505. def _get_rendered_text_width(self, text):
  506. """
  507. Return the width of a given text string, in pixels.
  508. """
  509. w, h, d = self._renderer.get_text_width_height_descent(
  510. text,
  511. self.get_fontproperties(),
  512. False)
  513. return math.ceil(w)
  514. def _get_wrapped_text(self):
  515. """
  516. Return a copy of the text with new lines added, so that
  517. the text is wrapped relative to the parent figure.
  518. """
  519. # Not fit to handle breaking up latex syntax correctly, so
  520. # ignore latex for now.
  521. if self.get_usetex():
  522. return self.get_text()
  523. # Build the line incrementally, for a more accurate measure of length
  524. line_width = self._get_wrap_line_width()
  525. wrapped_lines = []
  526. # New lines in the user's text force a split
  527. unwrapped_lines = self.get_text().split('\n')
  528. # Now wrap each individual unwrapped line
  529. for unwrapped_line in unwrapped_lines:
  530. sub_words = unwrapped_line.split(' ')
  531. # Remove items from sub_words as we go, so stop when empty
  532. while len(sub_words) > 0:
  533. if len(sub_words) == 1:
  534. # Only one word, so just add it to the end
  535. wrapped_lines.append(sub_words.pop(0))
  536. continue
  537. for i in range(2, len(sub_words) + 1):
  538. # Get width of all words up to and including here
  539. line = ' '.join(sub_words[:i])
  540. current_width = self._get_rendered_text_width(line)
  541. # If all these words are too wide, append all not including
  542. # last word
  543. if current_width > line_width:
  544. wrapped_lines.append(' '.join(sub_words[:i - 1]))
  545. sub_words = sub_words[i - 1:]
  546. break
  547. # Otherwise if all words fit in the width, append them all
  548. elif i == len(sub_words):
  549. wrapped_lines.append(' '.join(sub_words[:i]))
  550. sub_words = []
  551. break
  552. return '\n'.join(wrapped_lines)
  553. @artist.allow_rasterization
  554. def draw(self, renderer):
  555. # docstring inherited
  556. if renderer is not None:
  557. self._renderer = renderer
  558. if not self.get_visible():
  559. return
  560. if self.get_text() == '':
  561. return
  562. renderer.open_group('text', self.get_gid())
  563. with _wrap_text(self) as textobj:
  564. bbox, info, descent = textobj._get_layout(renderer)
  565. trans = textobj.get_transform()
  566. # don't use textobj.get_position here, which refers to text
  567. # position in Text:
  568. posx = float(textobj.convert_xunits(textobj._x))
  569. posy = float(textobj.convert_yunits(textobj._y))
  570. posx, posy = trans.transform((posx, posy))
  571. if not np.isfinite(posx) or not np.isfinite(posy):
  572. _log.warning("posx and posy should be finite values")
  573. return
  574. canvasw, canvash = renderer.get_canvas_width_height()
  575. # draw the FancyBboxPatch
  576. if textobj._bbox_patch:
  577. textobj._draw_bbox(renderer, posx, posy)
  578. gc = renderer.new_gc()
  579. gc.set_foreground(textobj.get_color())
  580. gc.set_alpha(textobj.get_alpha())
  581. gc.set_url(textobj._url)
  582. textobj._set_gc_clip(gc)
  583. angle = textobj.get_rotation()
  584. for line, wh, x, y in info:
  585. mtext = textobj if len(info) == 1 else None
  586. x = x + posx
  587. y = y + posy
  588. if renderer.flipy():
  589. y = canvash - y
  590. clean_line, ismath = textobj._preprocess_math(line)
  591. if textobj.get_path_effects():
  592. from matplotlib.patheffects import PathEffectRenderer
  593. textrenderer = PathEffectRenderer(
  594. textobj.get_path_effects(), renderer)
  595. else:
  596. textrenderer = renderer
  597. if textobj.get_usetex():
  598. textrenderer.draw_tex(gc, x, y, clean_line,
  599. textobj._fontproperties, angle,
  600. mtext=mtext)
  601. else:
  602. textrenderer.draw_text(gc, x, y, clean_line,
  603. textobj._fontproperties, angle,
  604. ismath=ismath, mtext=mtext)
  605. gc.restore()
  606. renderer.close_group('text')
  607. self.stale = False
  608. def get_color(self):
  609. """Return the color of the text."""
  610. return self._color
  611. def get_fontproperties(self):
  612. """Return the `.font_manager.FontProperties`."""
  613. return self._fontproperties
  614. def get_fontfamily(self):
  615. """
  616. Return the list of font families used for font lookup.
  617. See Also
  618. --------
  619. .font_manager.FontProperties.get_family
  620. """
  621. return self._fontproperties.get_family()
  622. def get_fontname(self):
  623. """
  624. Return the font name as a string.
  625. See Also
  626. --------
  627. .font_manager.FontProperties.get_name
  628. """
  629. return self._fontproperties.get_name()
  630. def get_fontstyle(self):
  631. """
  632. Return the font style as a string.
  633. See Also
  634. --------
  635. .font_manager.FontProperties.get_style
  636. """
  637. return self._fontproperties.get_style()
  638. def get_fontsize(self):
  639. """
  640. Return the font size as an integer.
  641. See Also
  642. --------
  643. .font_manager.FontProperties.get_size_in_points
  644. """
  645. return self._fontproperties.get_size_in_points()
  646. def get_fontvariant(self):
  647. """
  648. Return the font variant as a string.
  649. See Also
  650. --------
  651. .font_manager.FontProperties.get_variant
  652. """
  653. return self._fontproperties.get_variant()
  654. def get_fontweight(self):
  655. """
  656. Return the font weight as a string or a number.
  657. See Also
  658. --------
  659. .font_manager.FontProperties.get_weight
  660. """
  661. return self._fontproperties.get_weight()
  662. def get_stretch(self):
  663. """
  664. Return the font stretch as a string or a number.
  665. See Also
  666. --------
  667. .font_manager.FontProperties.get_stretch
  668. """
  669. return self._fontproperties.get_stretch()
  670. def get_horizontalalignment(self):
  671. """
  672. Return the horizontal alignment as a string. Will be one of
  673. 'left', 'center' or 'right'.
  674. """
  675. return self._horizontalalignment
  676. def get_unitless_position(self):
  677. """Return the (x, y) unitless position of the text."""
  678. # This will get the position with all unit information stripped away.
  679. # This is here for convenience since it is done in several locations.
  680. x = float(self.convert_xunits(self._x))
  681. y = float(self.convert_yunits(self._y))
  682. return x, y
  683. def get_position(self):
  684. """Return the (x, y) position of the text."""
  685. # This should return the same data (possible unitized) as was
  686. # specified with 'set_x' and 'set_y'.
  687. return self._x, self._y
  688. def get_prop_tup(self, renderer=None):
  689. """
  690. Return a hashable tuple of properties.
  691. Not intended to be human readable, but useful for backends who
  692. want to cache derived information about text (e.g., layouts) and
  693. need to know if the text has changed.
  694. """
  695. x, y = self.get_unitless_position()
  696. renderer = renderer or self._renderer
  697. return (x, y, self.get_text(), self._color,
  698. self._verticalalignment, self._horizontalalignment,
  699. hash(self._fontproperties),
  700. self._rotation, self._rotation_mode,
  701. self.figure.dpi, weakref.ref(renderer),
  702. self._linespacing
  703. )
  704. def get_text(self):
  705. """Return the text string."""
  706. return self._text
  707. def get_verticalalignment(self):
  708. """
  709. Return the vertical alignment as a string. Will be one of
  710. 'top', 'center', 'bottom' or 'baseline'.
  711. """
  712. return self._verticalalignment
  713. def get_window_extent(self, renderer=None, dpi=None):
  714. """
  715. Return the `.Bbox` bounding the text, in display units.
  716. In addition to being used internally, this is useful for specifying
  717. clickable regions in a png file on a web page.
  718. Parameters
  719. ----------
  720. renderer : Renderer, optional
  721. A renderer is needed to compute the bounding box. If the artist
  722. has already been drawn, the renderer is cached; thus, it is only
  723. necessary to pass this argument when calling `get_window_extent`
  724. before the first `draw`. In practice, it is usually easier to
  725. trigger a draw first (e.g. by saving the figure).
  726. dpi : float, optional
  727. The dpi value for computing the bbox, defaults to
  728. ``self.figure.dpi`` (*not* the renderer dpi); should be set e.g. if
  729. to match regions with a figure saved with a custom dpi value.
  730. """
  731. #return _unit_box
  732. if not self.get_visible():
  733. return Bbox.unit()
  734. if dpi is None:
  735. dpi = self.figure.dpi
  736. if self.get_text() == '':
  737. with cbook._setattr_cm(self.figure, dpi=dpi):
  738. tx, ty = self._get_xy_display()
  739. return Bbox.from_bounds(tx, ty, 0, 0)
  740. if renderer is not None:
  741. self._renderer = renderer
  742. if self._renderer is None:
  743. self._renderer = self.figure._cachedRenderer
  744. if self._renderer is None:
  745. raise RuntimeError('Cannot get window extent w/o renderer')
  746. with cbook._setattr_cm(self.figure, dpi=dpi):
  747. bbox, info, descent = self._get_layout(self._renderer)
  748. x, y = self.get_unitless_position()
  749. x, y = self.get_transform().transform((x, y))
  750. bbox = bbox.translated(x, y)
  751. return bbox
  752. def set_backgroundcolor(self, color):
  753. """
  754. Set the background color of the text by updating the bbox.
  755. Parameters
  756. ----------
  757. color : color
  758. See Also
  759. --------
  760. .set_bbox : To change the position of the bounding box
  761. """
  762. if self._bbox_patch is None:
  763. self.set_bbox(dict(facecolor=color, edgecolor=color))
  764. else:
  765. self._bbox_patch.update(dict(facecolor=color))
  766. self._update_clip_properties()
  767. self.stale = True
  768. def set_color(self, color):
  769. """
  770. Set the foreground color of the text
  771. Parameters
  772. ----------
  773. color : color
  774. """
  775. # Make sure it is hashable, or get_prop_tup will fail.
  776. try:
  777. hash(color)
  778. except TypeError:
  779. color = tuple(color)
  780. self._color = color
  781. self.stale = True
  782. def set_horizontalalignment(self, align):
  783. """
  784. Set the horizontal alignment to one of
  785. Parameters
  786. ----------
  787. align : {'center', 'right', 'left'}
  788. """
  789. cbook._check_in_list(['center', 'right', 'left'], align=align)
  790. self._horizontalalignment = align
  791. self.stale = True
  792. def set_multialignment(self, align):
  793. """
  794. Set the text alignment for multiline texts.
  795. The layout of the bounding box of all the lines is determined by the
  796. horizontalalignment and verticalalignment properties. This property
  797. controls the alignment of the text lines within that box.
  798. Parameters
  799. ----------
  800. align : {'left', 'right', 'center'}
  801. """
  802. cbook._check_in_list(['center', 'right', 'left'], align=align)
  803. self._multialignment = align
  804. self.stale = True
  805. def set_linespacing(self, spacing):
  806. """
  807. Set the line spacing as a multiple of the font size.
  808. The default line spacing is 1.2.
  809. Parameters
  810. ----------
  811. spacing : float (multiple of font size)
  812. """
  813. self._linespacing = spacing
  814. self.stale = True
  815. def set_fontfamily(self, fontname):
  816. """
  817. Set the font family. May be either a single string, or a list of
  818. strings in decreasing priority. Each string may be either a real font
  819. name or a generic font class name. If the latter, the specific font
  820. names will be looked up in the corresponding rcParams.
  821. If a `Text` instance is constructed with ``fontfamily=None``, then the
  822. font is set to :rc:`font.family`, and the
  823. same is done when `set_fontfamily()` is called on an existing
  824. `Text` instance.
  825. Parameters
  826. ----------
  827. fontname : {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', \
  828. 'monospace'}
  829. See Also
  830. --------
  831. .font_manager.FontProperties.set_family
  832. """
  833. self._fontproperties.set_family(fontname)
  834. self.stale = True
  835. def set_fontvariant(self, variant):
  836. """
  837. Set the font variant.
  838. Parameters
  839. ----------
  840. variant : {'normal', 'small-caps'}
  841. See Also
  842. --------
  843. .font_manager.FontProperties.set_variant
  844. """
  845. self._fontproperties.set_variant(variant)
  846. self.stale = True
  847. def set_fontstyle(self, fontstyle):
  848. """
  849. Set the font style.
  850. Parameters
  851. ----------
  852. fontstyle : {'normal', 'italic', 'oblique'}
  853. See Also
  854. --------
  855. .font_manager.FontProperties.set_style
  856. """
  857. self._fontproperties.set_style(fontstyle)
  858. self.stale = True
  859. def set_fontsize(self, fontsize):
  860. """
  861. Set the font size.
  862. Parameters
  863. ----------
  864. fontsize : float or {'xx-small', 'x-small', 'small', 'medium', \
  865. 'large', 'x-large', 'xx-large'}
  866. If float, the fontsize in points. The string values denote sizes
  867. relative to the default font size.
  868. See Also
  869. --------
  870. .font_manager.FontProperties.set_size
  871. """
  872. self._fontproperties.set_size(fontsize)
  873. self.stale = True
  874. def set_fontweight(self, weight):
  875. """
  876. Set the font weight.
  877. Parameters
  878. ----------
  879. weight : {a numeric value in range 0-1000, 'ultralight', 'light', \
  880. 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', \
  881. 'demi', 'bold', 'heavy', 'extra bold', 'black'}
  882. See Also
  883. --------
  884. .font_manager.FontProperties.set_weight
  885. """
  886. self._fontproperties.set_weight(weight)
  887. self.stale = True
  888. def set_fontstretch(self, stretch):
  889. """
  890. Set the font stretch (horizontal condensation or expansion).
  891. Parameters
  892. ----------
  893. stretch : {a numeric value in range 0-1000, 'ultra-condensed', \
  894. 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', \
  895. 'expanded', 'extra-expanded', 'ultra-expanded'}
  896. See Also
  897. --------
  898. .font_manager.FontProperties.set_stretch
  899. """
  900. self._fontproperties.set_stretch(stretch)
  901. self.stale = True
  902. def set_position(self, xy):
  903. """
  904. Set the (*x*, *y*) position of the text.
  905. Parameters
  906. ----------
  907. xy : (float, float)
  908. """
  909. self.set_x(xy[0])
  910. self.set_y(xy[1])
  911. def set_x(self, x):
  912. """
  913. Set the *x* position of the text.
  914. Parameters
  915. ----------
  916. x : float
  917. """
  918. self._x = x
  919. self.stale = True
  920. def set_y(self, y):
  921. """
  922. Set the *y* position of the text.
  923. Parameters
  924. ----------
  925. y : float
  926. """
  927. self._y = y
  928. self.stale = True
  929. def set_rotation(self, s):
  930. """
  931. Set the rotation of the text.
  932. Parameters
  933. ----------
  934. s : float or {'vertical', 'horizontal'}
  935. The rotation angle in degrees in mathematically positive direction
  936. (counterclockwise). 'horizontal' equals 0, 'vertical' equals 90.
  937. """
  938. self._rotation = s
  939. self.stale = True
  940. def set_verticalalignment(self, align):
  941. """
  942. Set the vertical alignment.
  943. Parameters
  944. ----------
  945. align : {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
  946. """
  947. cbook._check_in_list(
  948. ['top', 'bottom', 'center', 'baseline', 'center_baseline'],
  949. align=align)
  950. self._verticalalignment = align
  951. self.stale = True
  952. def set_text(self, s):
  953. r"""
  954. Set the text string *s*.
  955. It may contain newlines (``\n``) or math in LaTeX syntax.
  956. Parameters
  957. ----------
  958. s : object
  959. Any object gets converted to its `str` representation, except for
  960. ``None`` which is converted to an empty string.
  961. """
  962. if s is None:
  963. s = ''
  964. if s != self._text:
  965. self._text = str(s)
  966. self.stale = True
  967. def _preprocess_math(self, s):
  968. """
  969. Return the string *s* after mathtext preprocessing, and the kind of
  970. mathtext support needed.
  971. - If *self* is configured to use TeX, return *s* unchanged except that
  972. a single space gets escaped, and the flag "TeX".
  973. - Otherwise, if *s* is mathtext (has an even number of unescaped dollar
  974. signs), return *s* and the flag True.
  975. - Otherwise, return *s* with dollar signs unescaped, and the flag
  976. False.
  977. """
  978. if self.get_usetex():
  979. if s == " ":
  980. s = r"\ "
  981. return s, "TeX"
  982. elif cbook.is_math_text(s):
  983. return s, True
  984. else:
  985. return s.replace(r"\$", "$"), False
  986. def set_fontproperties(self, fp):
  987. """
  988. Set the font properties that control the text.
  989. Parameters
  990. ----------
  991. fp : `.font_manager.FontProperties` or `str` or `pathlib.Path`
  992. If a `str`, it is interpreted as a fontconfig pattern parsed by
  993. `.FontProperties`. If a `pathlib.Path`, it is interpreted as the
  994. absolute path to a font file.
  995. """
  996. self._fontproperties = FontProperties._from_any(fp).copy()
  997. self.stale = True
  998. def set_usetex(self, usetex):
  999. """
  1000. Parameters
  1001. ----------
  1002. usetex : bool or None
  1003. Whether to render using TeX, ``None`` means to use
  1004. :rc:`text.usetex`.
  1005. """
  1006. if usetex is None:
  1007. self._usetex = rcParams['text.usetex']
  1008. else:
  1009. self._usetex = bool(usetex)
  1010. self.stale = True
  1011. def get_usetex(self):
  1012. """Return whether this `Text` object uses TeX for rendering."""
  1013. return self._usetex
  1014. def set_fontname(self, fontname):
  1015. """
  1016. Alias for `set_family`.
  1017. One-way alias only: the getter differs.
  1018. Parameters
  1019. ----------
  1020. fontname : {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', \
  1021. 'monospace'}
  1022. See Also
  1023. --------
  1024. .font_manager.FontProperties.set_family
  1025. """
  1026. return self.set_family(fontname)
  1027. docstring.interpd.update(Text=artist.kwdoc(Text))
  1028. docstring.dedent_interpd(Text.__init__)
  1029. class OffsetFrom:
  1030. """Callable helper class for working with `Annotation`."""
  1031. def __init__(self, artist, ref_coord, unit="points"):
  1032. """
  1033. Parameters
  1034. ----------
  1035. artist : `.Artist` or `.BboxBase` or `.Transform`
  1036. The object to compute the offset from.
  1037. ref_coord : (float, float)
  1038. If *artist* is an `.Artist` or `.BboxBase`, this values is
  1039. the location to of the offset origin in fractions of the
  1040. *artist* bounding box.
  1041. If *artist* is a transform, the offset origin is the
  1042. transform applied to this value.
  1043. unit : {'points, 'pixels'}, default: 'points'
  1044. The screen units to use (pixels or points) for the offset input.
  1045. """
  1046. self._artist = artist
  1047. self._ref_coord = ref_coord
  1048. self.set_unit(unit)
  1049. def set_unit(self, unit):
  1050. """
  1051. Set the unit for input to the transform used by ``__call__``.
  1052. Parameters
  1053. ----------
  1054. unit : {'points', 'pixels'}
  1055. """
  1056. cbook._check_in_list(["points", "pixels"], unit=unit)
  1057. self._unit = unit
  1058. def get_unit(self):
  1059. """Return the unit for input to the transform used by ``__call__``."""
  1060. return self._unit
  1061. def _get_scale(self, renderer):
  1062. unit = self.get_unit()
  1063. if unit == "pixels":
  1064. return 1.
  1065. else:
  1066. return renderer.points_to_pixels(1.)
  1067. def __call__(self, renderer):
  1068. """
  1069. Return the offset transform.
  1070. Parameters
  1071. ----------
  1072. renderer : `RendererBase`
  1073. The renderer to use to compute the offset
  1074. Returns
  1075. -------
  1076. `Transform`
  1077. Maps (x, y) in pixel or point units to screen units
  1078. relative to the given artist.
  1079. """
  1080. if isinstance(self._artist, Artist):
  1081. bbox = self._artist.get_window_extent(renderer)
  1082. xf, yf = self._ref_coord
  1083. x = bbox.x0 + bbox.width * xf
  1084. y = bbox.y0 + bbox.height * yf
  1085. elif isinstance(self._artist, BboxBase):
  1086. bbox = self._artist
  1087. xf, yf = self._ref_coord
  1088. x = bbox.x0 + bbox.width * xf
  1089. y = bbox.y0 + bbox.height * yf
  1090. elif isinstance(self._artist, Transform):
  1091. x, y = self._artist.transform(self._ref_coord)
  1092. else:
  1093. raise RuntimeError("unknown type")
  1094. sc = self._get_scale(renderer)
  1095. tr = Affine2D().scale(sc).translate(x, y)
  1096. return tr
  1097. class _AnnotationBase:
  1098. def __init__(self,
  1099. xy,
  1100. xycoords='data',
  1101. annotation_clip=None):
  1102. self.xy = xy
  1103. self.xycoords = xycoords
  1104. self.set_annotation_clip(annotation_clip)
  1105. self._draggable = None
  1106. def _get_xy(self, renderer, x, y, s):
  1107. if isinstance(s, tuple):
  1108. s1, s2 = s
  1109. else:
  1110. s1, s2 = s, s
  1111. if s1 == 'data':
  1112. x = float(self.convert_xunits(x))
  1113. if s2 == 'data':
  1114. y = float(self.convert_yunits(y))
  1115. return self._get_xy_transform(renderer, s).transform((x, y))
  1116. def _get_xy_transform(self, renderer, s):
  1117. if isinstance(s, tuple):
  1118. s1, s2 = s
  1119. from matplotlib.transforms import blended_transform_factory
  1120. tr1 = self._get_xy_transform(renderer, s1)
  1121. tr2 = self._get_xy_transform(renderer, s2)
  1122. tr = blended_transform_factory(tr1, tr2)
  1123. return tr
  1124. elif callable(s):
  1125. tr = s(renderer)
  1126. if isinstance(tr, BboxBase):
  1127. return BboxTransformTo(tr)
  1128. elif isinstance(tr, Transform):
  1129. return tr
  1130. else:
  1131. raise RuntimeError("unknown return type ...")
  1132. elif isinstance(s, Artist):
  1133. bbox = s.get_window_extent(renderer)
  1134. return BboxTransformTo(bbox)
  1135. elif isinstance(s, BboxBase):
  1136. return BboxTransformTo(s)
  1137. elif isinstance(s, Transform):
  1138. return s
  1139. elif not isinstance(s, str):
  1140. raise RuntimeError("unknown coordinate type : %s" % s)
  1141. if s == 'data':
  1142. return self.axes.transData
  1143. elif s == 'polar':
  1144. from matplotlib.projections import PolarAxes
  1145. tr = PolarAxes.PolarTransform()
  1146. trans = tr + self.axes.transData
  1147. return trans
  1148. s_ = s.split()
  1149. if len(s_) != 2:
  1150. raise ValueError("%s is not a recognized coordinate" % s)
  1151. bbox0, xy0 = None, None
  1152. bbox_name, unit = s_
  1153. # if unit is offset-like
  1154. if bbox_name == "figure":
  1155. bbox0 = self.figure.bbox
  1156. elif bbox_name == "axes":
  1157. bbox0 = self.axes.bbox
  1158. # elif bbox_name == "bbox":
  1159. # if bbox is None:
  1160. # raise RuntimeError("bbox is specified as a coordinate but "
  1161. # "never set")
  1162. # bbox0 = self._get_bbox(renderer, bbox)
  1163. if bbox0 is not None:
  1164. xy0 = bbox0.p0
  1165. elif bbox_name == "offset":
  1166. xy0 = self._get_ref_xy(renderer)
  1167. if xy0 is not None:
  1168. # reference x, y in display coordinate
  1169. ref_x, ref_y = xy0
  1170. from matplotlib.transforms import Affine2D
  1171. if unit == "points":
  1172. # dots per points
  1173. dpp = self.figure.get_dpi() / 72.
  1174. tr = Affine2D().scale(dpp)
  1175. elif unit == "pixels":
  1176. tr = Affine2D()
  1177. elif unit == "fontsize":
  1178. fontsize = self.get_size()
  1179. dpp = fontsize * self.figure.get_dpi() / 72.
  1180. tr = Affine2D().scale(dpp)
  1181. elif unit == "fraction":
  1182. w, h = bbox0.size
  1183. tr = Affine2D().scale(w, h)
  1184. else:
  1185. raise ValueError("%s is not a recognized coordinate" % s)
  1186. return tr.translate(ref_x, ref_y)
  1187. else:
  1188. raise ValueError("%s is not a recognized coordinate" % s)
  1189. def _get_ref_xy(self, renderer):
  1190. """
  1191. Return x, y (in display coordinates) that is to be used for a reference
  1192. of any offset coordinate.
  1193. """
  1194. return self._get_xy(renderer, *self.xy, self.xycoords)
  1195. # def _get_bbox(self, renderer):
  1196. # if hasattr(bbox, "bounds"):
  1197. # return bbox
  1198. # elif hasattr(bbox, "get_window_extent"):
  1199. # bbox = bbox.get_window_extent()
  1200. # return bbox
  1201. # else:
  1202. # raise ValueError("A bbox instance is expected but got %s" %
  1203. # str(bbox))
  1204. def set_annotation_clip(self, b):
  1205. """
  1206. Set the annotation's clipping behavior.
  1207. Parameters
  1208. ----------
  1209. b : bool or None
  1210. - True: the annotation will only be drawn when ``self.xy`` is
  1211. inside the axes.
  1212. - False: the annotation will always be drawn regardless of its
  1213. position.
  1214. - None: the ``self.xy`` will be checked only if *xycoords* is
  1215. "data".
  1216. """
  1217. self._annotation_clip = b
  1218. def get_annotation_clip(self):
  1219. """
  1220. Return the annotation's clipping behavior.
  1221. See `set_annotation_clip` for the meaning of return values.
  1222. """
  1223. return self._annotation_clip
  1224. def _get_position_xy(self, renderer):
  1225. """Return the pixel position of the annotated point."""
  1226. x, y = self.xy
  1227. return self._get_xy(renderer, x, y, self.xycoords)
  1228. def _check_xy(self, renderer):
  1229. """Check whether the annotation at *xy_pixel* should be drawn."""
  1230. b = self.get_annotation_clip()
  1231. if b or (b is None and self.xycoords == "data"):
  1232. # check if self.xy is inside the axes.
  1233. xy_pixel = self._get_position_xy(renderer)
  1234. return self.axes.contains_point(xy_pixel)
  1235. return True
  1236. def draggable(self, state=None, use_blit=False):
  1237. """
  1238. Set whether the annotation is draggable with the mouse.
  1239. Parameters
  1240. ----------
  1241. state : bool or None
  1242. - True or False: set the draggability.
  1243. - None: toggle the draggability.
  1244. Returns
  1245. -------
  1246. DraggableAnnotation or None
  1247. If the annotation is draggable, the corresponding
  1248. `.DraggableAnnotation` helper is returned.
  1249. """
  1250. from matplotlib.offsetbox import DraggableAnnotation
  1251. is_draggable = self._draggable is not None
  1252. # if state is None we'll toggle
  1253. if state is None:
  1254. state = not is_draggable
  1255. if state:
  1256. if self._draggable is None:
  1257. self._draggable = DraggableAnnotation(self, use_blit)
  1258. else:
  1259. if self._draggable is not None:
  1260. self._draggable.disconnect()
  1261. self._draggable = None
  1262. return self._draggable
  1263. class Annotation(Text, _AnnotationBase):
  1264. """
  1265. An `.Annotation` is a `.Text` that can refer to a specific position *xy*.
  1266. Optionally an arrow pointing from the text to *xy* can be drawn.
  1267. Attributes
  1268. ----------
  1269. xy
  1270. The annotated position.
  1271. xycoords
  1272. The coordinate system for *xy*.
  1273. arrow_patch
  1274. A `.FancyArrowPatch` to point from *xytext* to *xy*.
  1275. """
  1276. def __str__(self):
  1277. return "Annotation(%g, %g, %r)" % (self.xy[0], self.xy[1], self._text)
  1278. def __init__(self, text, xy,
  1279. xytext=None,
  1280. xycoords='data',
  1281. textcoords=None,
  1282. arrowprops=None,
  1283. annotation_clip=None,
  1284. **kwargs):
  1285. """
  1286. Annotate the point *xy* with text *text*.
  1287. In the simplest form, the text is placed at *xy*.
  1288. Optionally, the text can be displayed in another position *xytext*.
  1289. An arrow pointing from the text to the annotated point *xy* can then
  1290. be added by defining *arrowprops*.
  1291. Parameters
  1292. ----------
  1293. text : str
  1294. The text of the annotation. *s* is a deprecated synonym for this
  1295. parameter.
  1296. xy : (float, float)
  1297. The point *(x, y)* to annotate. The coordinate system is determined
  1298. by *xycoords*.
  1299. xytext : (float, float), default: *xy*
  1300. The position *(x, y)* to place the text at. The coordinate system
  1301. is determined by *textcoords*.
  1302. xycoords : str or `.Artist` or `.Transform` or callable or \
  1303. (float, float), default: 'data'
  1304. The coordinate system that *xy* is given in. The following types
  1305. of values are supported:
  1306. - One of the following strings:
  1307. ================= =============================================
  1308. Value Description
  1309. ================= =============================================
  1310. 'figure points' Points from the lower left of the figure
  1311. 'figure pixels' Pixels from the lower left of the figure
  1312. 'figure fraction' Fraction of figure from lower left
  1313. 'axes points' Points from lower left corner of axes
  1314. 'axes pixels' Pixels from lower left corner of axes
  1315. 'axes fraction' Fraction of axes from lower left
  1316. 'data' Use the coordinate system of the object being
  1317. annotated (default)
  1318. 'polar' *(theta, r)* if not native 'data' coordinates
  1319. ================= =============================================
  1320. - An `.Artist`: *xy* is interpreted as a fraction of the artist's
  1321. `~matplotlib.transforms.Bbox`. E.g. *(0, 0)* would be the lower
  1322. left corner of the bounding box and *(0.5, 1)* would be the
  1323. center top of the bounding box.
  1324. - A `.Transform` to transform *xy* to screen coordinates.
  1325. - A function with one of the following signatures::
  1326. def transform(renderer) -> Bbox
  1327. def transform(renderer) -> Transform
  1328. where *renderer* is a `.RendererBase` subclass.
  1329. The result of the function is interpreted like the `.Artist` and
  1330. `.Transform` cases above.
  1331. - A tuple *(xcoords, ycoords)* specifying separate coordinate
  1332. systems for *x* and *y*. *xcoords* and *ycoords* must each be
  1333. of one of the above described types.
  1334. See :ref:`plotting-guide-annotation` for more details.
  1335. textcoords : str or `.Artist` or `.Transform` or callable or \
  1336. (float, float), default: value of *xycoords*
  1337. The coordinate system that *xytext* is given in.
  1338. All *xycoords* values are valid as well as the following
  1339. strings:
  1340. ================= =========================================
  1341. Value Description
  1342. ================= =========================================
  1343. 'offset points' Offset (in points) from the *xy* value
  1344. 'offset pixels' Offset (in pixels) from the *xy* value
  1345. ================= =========================================
  1346. arrowprops : dict, optional
  1347. The properties used to draw a `.FancyArrowPatch` arrow between the
  1348. positions *xy* and *xytext*.
  1349. If *arrowprops* does not contain the key 'arrowstyle' the
  1350. allowed keys are:
  1351. ========== ======================================================
  1352. Key Description
  1353. ========== ======================================================
  1354. width The width of the arrow in points
  1355. headwidth The width of the base of the arrow head in points
  1356. headlength The length of the arrow head in points
  1357. shrink Fraction of total length to shrink from both ends
  1358. ? Any key to :class:`matplotlib.patches.FancyArrowPatch`
  1359. ========== ======================================================
  1360. If *arrowprops* contains the key 'arrowstyle' the
  1361. above keys are forbidden. The allowed values of
  1362. ``'arrowstyle'`` are:
  1363. ============ =============================================
  1364. Name Attrs
  1365. ============ =============================================
  1366. ``'-'`` None
  1367. ``'->'`` head_length=0.4,head_width=0.2
  1368. ``'-['`` widthB=1.0,lengthB=0.2,angleB=None
  1369. ``'|-|'`` widthA=1.0,widthB=1.0
  1370. ``'-|>'`` head_length=0.4,head_width=0.2
  1371. ``'<-'`` head_length=0.4,head_width=0.2
  1372. ``'<->'`` head_length=0.4,head_width=0.2
  1373. ``'<|-'`` head_length=0.4,head_width=0.2
  1374. ``'<|-|>'`` head_length=0.4,head_width=0.2
  1375. ``'fancy'`` head_length=0.4,head_width=0.4,tail_width=0.4
  1376. ``'simple'`` head_length=0.5,head_width=0.5,tail_width=0.2
  1377. ``'wedge'`` tail_width=0.3,shrink_factor=0.5
  1378. ============ =============================================
  1379. Valid keys for `~matplotlib.patches.FancyArrowPatch` are:
  1380. =============== ==================================================
  1381. Key Description
  1382. =============== ==================================================
  1383. arrowstyle the arrow style
  1384. connectionstyle the connection style
  1385. relpos default is (0.5, 0.5)
  1386. patchA default is bounding box of the text
  1387. patchB default is None
  1388. shrinkA default is 2 points
  1389. shrinkB default is 2 points
  1390. mutation_scale default is text size (in points)
  1391. mutation_aspect default is 1.
  1392. ? any key for :class:`matplotlib.patches.PathPatch`
  1393. =============== ==================================================
  1394. Defaults to None, i.e. no arrow is drawn.
  1395. annotation_clip : bool or None, default: None
  1396. Whether to draw the annotation when the annotation point *xy* is
  1397. outside the axes area.
  1398. - If *True*, the annotation will only be drawn when *xy* is
  1399. within the axes.
  1400. - If *False*, the annotation will always be drawn.
  1401. - If *None*, the annotation will only be drawn when *xy* is
  1402. within the axes and *xycoords* is 'data'.
  1403. **kwargs
  1404. Additional kwargs are passed to `~matplotlib.text.Text`.
  1405. Returns
  1406. -------
  1407. `.Annotation`
  1408. See Also
  1409. --------
  1410. :ref:`plotting-guide-annotation`
  1411. """
  1412. _AnnotationBase.__init__(self,
  1413. xy,
  1414. xycoords=xycoords,
  1415. annotation_clip=annotation_clip)
  1416. # warn about wonky input data
  1417. if (xytext is None and
  1418. textcoords is not None and
  1419. textcoords != xycoords):
  1420. cbook._warn_external("You have used the `textcoords` kwarg, but "
  1421. "not the `xytext` kwarg. This can lead to "
  1422. "surprising results.")
  1423. # clean up textcoords and assign default
  1424. if textcoords is None:
  1425. textcoords = self.xycoords
  1426. self._textcoords = textcoords
  1427. # cleanup xytext defaults
  1428. if xytext is None:
  1429. xytext = self.xy
  1430. x, y = xytext
  1431. self.arrowprops = arrowprops
  1432. if arrowprops is not None:
  1433. arrowprops = arrowprops.copy()
  1434. if "arrowstyle" in arrowprops:
  1435. self._arrow_relpos = arrowprops.pop("relpos", (0.5, 0.5))
  1436. else:
  1437. # modified YAArrow API to be used with FancyArrowPatch
  1438. for key in [
  1439. 'width', 'headwidth', 'headlength', 'shrink', 'frac']:
  1440. arrowprops.pop(key, None)
  1441. self.arrow_patch = FancyArrowPatch((0, 0), (1, 1), **arrowprops)
  1442. else:
  1443. self.arrow_patch = None
  1444. # Must come last, as some kwargs may be propagated to arrow_patch.
  1445. Text.__init__(self, x, y, text, **kwargs)
  1446. def contains(self, event):
  1447. inside, info = self._default_contains(event)
  1448. if inside is not None:
  1449. return inside, info
  1450. contains, tinfo = Text.contains(self, event)
  1451. if self.arrow_patch is not None:
  1452. in_patch, _ = self.arrow_patch.contains(event)
  1453. contains = contains or in_patch
  1454. return contains, tinfo
  1455. @property
  1456. def xycoords(self):
  1457. return self._xycoords
  1458. @xycoords.setter
  1459. def xycoords(self, xycoords):
  1460. def is_offset(s):
  1461. return isinstance(s, str) and s.startswith("offset")
  1462. if (isinstance(xycoords, tuple) and any(map(is_offset, xycoords))
  1463. or is_offset(xycoords)):
  1464. raise ValueError("xycoords cannot be an offset coordinate")
  1465. self._xycoords = xycoords
  1466. @property
  1467. def xyann(self):
  1468. """
  1469. The text position.
  1470. See also *xytext* in `.Annotation`.
  1471. """
  1472. return self.get_position()
  1473. @xyann.setter
  1474. def xyann(self, xytext):
  1475. self.set_position(xytext)
  1476. def get_anncoords(self):
  1477. """
  1478. Return the coordinate system to use for `.Annotation.xyann`.
  1479. See also *xycoords* in `.Annotation`.
  1480. """
  1481. return self._textcoords
  1482. def set_anncoords(self, coords):
  1483. """
  1484. Set the coordinate system to use for `.Annotation.xyann`.
  1485. See also *xycoords* in `.Annotation`.
  1486. """
  1487. self._textcoords = coords
  1488. anncoords = property(get_anncoords, set_anncoords, doc="""
  1489. The coordinate system to use for `.Annotation.xyann`.""")
  1490. def set_figure(self, fig):
  1491. # docstring inherited
  1492. if self.arrow_patch is not None:
  1493. self.arrow_patch.set_figure(fig)
  1494. Artist.set_figure(self, fig)
  1495. def update_positions(self, renderer):
  1496. """
  1497. Update the pixel positions of the annotation text and the arrow patch.
  1498. """
  1499. x1, y1 = self._get_position_xy(renderer) # Annotated position.
  1500. # generate transformation,
  1501. self.set_transform(self._get_xy_transform(renderer, self.anncoords))
  1502. if self.arrowprops is None:
  1503. return
  1504. bbox = Text.get_window_extent(self, renderer)
  1505. d = self.arrowprops.copy()
  1506. ms = d.pop("mutation_scale", self.get_size())
  1507. self.arrow_patch.set_mutation_scale(ms)
  1508. if "arrowstyle" not in d:
  1509. # Approximately simulate the YAArrow.
  1510. # Pop its kwargs:
  1511. shrink = d.pop('shrink', 0.0)
  1512. width = d.pop('width', 4)
  1513. headwidth = d.pop('headwidth', 12)
  1514. # Ignore frac--it is useless.
  1515. frac = d.pop('frac', None)
  1516. if frac is not None:
  1517. cbook._warn_external(
  1518. "'frac' option in 'arrowprops' is no longer supported;"
  1519. " use 'headlength' to set the head length in points.")
  1520. headlength = d.pop('headlength', 12)
  1521. # NB: ms is in pts
  1522. stylekw = dict(head_length=headlength / ms,
  1523. head_width=headwidth / ms,
  1524. tail_width=width / ms)
  1525. self.arrow_patch.set_arrowstyle('simple', **stylekw)
  1526. # using YAArrow style:
  1527. # pick the corner of the text bbox closest to annotated point.
  1528. xpos = [(bbox.x0, 0), ((bbox.x0 + bbox.x1) / 2, 0.5), (bbox.x1, 1)]
  1529. ypos = [(bbox.y0, 0), ((bbox.y0 + bbox.y1) / 2, 0.5), (bbox.y1, 1)]
  1530. x, relposx = min(xpos, key=lambda v: abs(v[0] - x1))
  1531. y, relposy = min(ypos, key=lambda v: abs(v[0] - y1))
  1532. self._arrow_relpos = (relposx, relposy)
  1533. r = np.hypot(y - y1, x - x1)
  1534. shrink_pts = shrink * r / renderer.points_to_pixels(1)
  1535. self.arrow_patch.shrinkA = self.arrow_patch.shrinkB = shrink_pts
  1536. # adjust the starting point of the arrow relative to the textbox.
  1537. # TODO : Rotation needs to be accounted.
  1538. relposx, relposy = self._arrow_relpos
  1539. x0 = bbox.x0 + bbox.width * relposx
  1540. y0 = bbox.y0 + bbox.height * relposy
  1541. # The arrow will be drawn from (x0, y0) to (x1, y1). It will be first
  1542. # clipped by patchA and patchB. Then it will be shrunk by shrinkA and
  1543. # shrinkB (in points). If patch A is not set, self.bbox_patch is used.
  1544. self.arrow_patch.set_positions((x0, y0), (x1, y1))
  1545. if "patchA" in d:
  1546. self.arrow_patch.set_patchA(d.pop("patchA"))
  1547. else:
  1548. if self._bbox_patch:
  1549. self.arrow_patch.set_patchA(self._bbox_patch)
  1550. else:
  1551. if self.get_text() == "":
  1552. self.arrow_patch.set_patchA(None)
  1553. return
  1554. pad = renderer.points_to_pixels(4)
  1555. r = Rectangle(xy=(bbox.x0 - pad / 2, bbox.y0 - pad / 2),
  1556. width=bbox.width + pad, height=bbox.height + pad,
  1557. transform=IdentityTransform(), clip_on=False)
  1558. self.arrow_patch.set_patchA(r)
  1559. @artist.allow_rasterization
  1560. def draw(self, renderer):
  1561. # docstring inherited
  1562. if renderer is not None:
  1563. self._renderer = renderer
  1564. if not self.get_visible() or not self._check_xy(renderer):
  1565. return
  1566. self.update_positions(renderer)
  1567. self.update_bbox_position_size(renderer)
  1568. if self.arrow_patch is not None: # FancyArrowPatch
  1569. if self.arrow_patch.figure is None and self.figure is not None:
  1570. self.arrow_patch.figure = self.figure
  1571. self.arrow_patch.draw(renderer)
  1572. # Draw text, including FancyBboxPatch, after FancyArrowPatch.
  1573. # Otherwise, a wedge arrowstyle can land partly on top of the Bbox.
  1574. Text.draw(self, renderer)
  1575. def get_window_extent(self, renderer=None):
  1576. """
  1577. Return the `.Bbox` bounding the text and arrow, in display units.
  1578. Parameters
  1579. ----------
  1580. renderer : Renderer, optional
  1581. A renderer is needed to compute the bounding box. If the artist
  1582. has already been drawn, the renderer is cached; thus, it is only
  1583. necessary to pass this argument when calling `get_window_extent`
  1584. before the first `draw`. In practice, it is usually easier to
  1585. trigger a draw first (e.g. by saving the figure).
  1586. """
  1587. # This block is the same as in Text.get_window_extent, but we need to
  1588. # set the renderer before calling update_positions().
  1589. if not self.get_visible():
  1590. return Bbox.unit()
  1591. if renderer is not None:
  1592. self._renderer = renderer
  1593. if self._renderer is None:
  1594. self._renderer = self.figure._cachedRenderer
  1595. if self._renderer is None:
  1596. raise RuntimeError('Cannot get window extent w/o renderer')
  1597. self.update_positions(self._renderer)
  1598. text_bbox = Text.get_window_extent(self)
  1599. bboxes = [text_bbox]
  1600. if self.arrow_patch is not None:
  1601. bboxes.append(self.arrow_patch.get_window_extent())
  1602. return Bbox.union(bboxes)
  1603. docstring.interpd.update(Annotation=Annotation.__init__.__doc__)