test_text.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  1. from datetime import datetime
  2. import io
  3. import warnings
  4. import numpy as np
  5. from numpy.testing import assert_almost_equal
  6. from packaging.version import parse as parse_version
  7. import pyparsing
  8. import pytest
  9. import matplotlib as mpl
  10. from matplotlib.backend_bases import MouseEvent
  11. from matplotlib.font_manager import FontProperties
  12. import matplotlib.patches as mpatches
  13. import matplotlib.pyplot as plt
  14. import matplotlib.transforms as mtransforms
  15. from matplotlib.testing.decorators import check_figures_equal, image_comparison
  16. from matplotlib.testing._markers import needs_usetex
  17. from matplotlib.text import Text, Annotation, OffsetFrom
  18. pyparsing_version = parse_version(pyparsing.__version__)
  19. @image_comparison(['font_styles'])
  20. def test_font_styles():
  21. def find_matplotlib_font(**kw):
  22. prop = FontProperties(**kw)
  23. path = findfont(prop, directory=mpl.get_data_path())
  24. return FontProperties(fname=path)
  25. from matplotlib.font_manager import FontProperties, findfont
  26. warnings.filterwarnings(
  27. 'ignore',
  28. r"findfont: Font family \[u?'Foo'\] not found. Falling back to .",
  29. UserWarning,
  30. module='matplotlib.font_manager')
  31. fig, ax = plt.subplots()
  32. normal_font = find_matplotlib_font(
  33. family="sans-serif",
  34. style="normal",
  35. variant="normal",
  36. size=14)
  37. a = ax.annotate(
  38. "Normal Font",
  39. (0.1, 0.1),
  40. xycoords='axes fraction',
  41. fontproperties=normal_font)
  42. assert a.get_fontname() == 'DejaVu Sans'
  43. assert a.get_fontstyle() == 'normal'
  44. assert a.get_fontvariant() == 'normal'
  45. assert a.get_weight() == 'normal'
  46. assert a.get_stretch() == 'normal'
  47. bold_font = find_matplotlib_font(
  48. family="Foo",
  49. style="normal",
  50. variant="normal",
  51. weight="bold",
  52. stretch=500,
  53. size=14)
  54. ax.annotate(
  55. "Bold Font",
  56. (0.1, 0.2),
  57. xycoords='axes fraction',
  58. fontproperties=bold_font)
  59. bold_italic_font = find_matplotlib_font(
  60. family="sans serif",
  61. style="italic",
  62. variant="normal",
  63. weight=750,
  64. stretch=500,
  65. size=14)
  66. ax.annotate(
  67. "Bold Italic Font",
  68. (0.1, 0.3),
  69. xycoords='axes fraction',
  70. fontproperties=bold_italic_font)
  71. light_font = find_matplotlib_font(
  72. family="sans-serif",
  73. style="normal",
  74. variant="normal",
  75. weight=200,
  76. stretch=500,
  77. size=14)
  78. ax.annotate(
  79. "Light Font",
  80. (0.1, 0.4),
  81. xycoords='axes fraction',
  82. fontproperties=light_font)
  83. condensed_font = find_matplotlib_font(
  84. family="sans-serif",
  85. style="normal",
  86. variant="normal",
  87. weight=500,
  88. stretch=100,
  89. size=14)
  90. ax.annotate(
  91. "Condensed Font",
  92. (0.1, 0.5),
  93. xycoords='axes fraction',
  94. fontproperties=condensed_font)
  95. ax.set_xticks([])
  96. ax.set_yticks([])
  97. @image_comparison(['multiline'])
  98. def test_multiline():
  99. plt.figure()
  100. ax = plt.subplot(1, 1, 1)
  101. ax.set_title("multiline\ntext alignment")
  102. plt.text(
  103. 0.2, 0.5, "TpTpTp\n$M$\nTpTpTp", size=20, ha="center", va="top")
  104. plt.text(
  105. 0.5, 0.5, "TpTpTp\n$M^{M^{M^{M}}}$\nTpTpTp", size=20,
  106. ha="center", va="top")
  107. plt.text(
  108. 0.8, 0.5, "TpTpTp\n$M_{q_{q_{q}}}$\nTpTpTp", size=20,
  109. ha="center", va="top")
  110. plt.xlim(0, 1)
  111. plt.ylim(0, 0.8)
  112. ax.set_xticks([])
  113. ax.set_yticks([])
  114. @image_comparison(['multiline2'], style='mpl20')
  115. def test_multiline2():
  116. # Remove this line when this test image is regenerated.
  117. plt.rcParams['text.kerning_factor'] = 6
  118. fig, ax = plt.subplots()
  119. ax.set_xlim([0, 1.4])
  120. ax.set_ylim([0, 2])
  121. ax.axhline(0.5, color='C2', linewidth=0.3)
  122. sts = ['Line', '2 Lineg\n 2 Lg', '$\\sum_i x $', 'hi $\\sum_i x $\ntest',
  123. 'test\n $\\sum_i x $', '$\\sum_i x $\n $\\sum_i x $']
  124. renderer = fig.canvas.get_renderer()
  125. def draw_box(ax, tt):
  126. r = mpatches.Rectangle((0, 0), 1, 1, clip_on=False,
  127. transform=ax.transAxes)
  128. r.set_bounds(
  129. tt.get_window_extent(renderer)
  130. .transformed(ax.transAxes.inverted())
  131. .bounds)
  132. ax.add_patch(r)
  133. horal = 'left'
  134. for nn, st in enumerate(sts):
  135. tt = ax.text(0.2 * nn + 0.1, 0.5, st, horizontalalignment=horal,
  136. verticalalignment='bottom')
  137. draw_box(ax, tt)
  138. ax.text(1.2, 0.5, 'Bottom align', color='C2')
  139. ax.axhline(1.3, color='C2', linewidth=0.3)
  140. for nn, st in enumerate(sts):
  141. tt = ax.text(0.2 * nn + 0.1, 1.3, st, horizontalalignment=horal,
  142. verticalalignment='top')
  143. draw_box(ax, tt)
  144. ax.text(1.2, 1.3, 'Top align', color='C2')
  145. ax.axhline(1.8, color='C2', linewidth=0.3)
  146. for nn, st in enumerate(sts):
  147. tt = ax.text(0.2 * nn + 0.1, 1.8, st, horizontalalignment=horal,
  148. verticalalignment='baseline')
  149. draw_box(ax, tt)
  150. ax.text(1.2, 1.8, 'Baseline align', color='C2')
  151. ax.axhline(0.1, color='C2', linewidth=0.3)
  152. for nn, st in enumerate(sts):
  153. tt = ax.text(0.2 * nn + 0.1, 0.1, st, horizontalalignment=horal,
  154. verticalalignment='bottom', rotation=20)
  155. draw_box(ax, tt)
  156. ax.text(1.2, 0.1, 'Bot align, rot20', color='C2')
  157. @image_comparison(['antialiased.png'], style='mpl20')
  158. def test_antialiasing():
  159. mpl.rcParams['text.antialiased'] = False # Passed arguments should override.
  160. fig = plt.figure(figsize=(5.25, 0.75))
  161. fig.text(0.3, 0.75, "antialiased", horizontalalignment='center',
  162. verticalalignment='center', antialiased=True)
  163. fig.text(0.3, 0.25, r"$\sqrt{x}$", horizontalalignment='center',
  164. verticalalignment='center', antialiased=True)
  165. mpl.rcParams['text.antialiased'] = True # Passed arguments should override.
  166. fig.text(0.7, 0.75, "not antialiased", horizontalalignment='center',
  167. verticalalignment='center', antialiased=False)
  168. fig.text(0.7, 0.25, r"$\sqrt{x}$", horizontalalignment='center',
  169. verticalalignment='center', antialiased=False)
  170. mpl.rcParams['text.antialiased'] = False # Should not affect existing text.
  171. def test_afm_kerning():
  172. fn = mpl.font_manager.findfont("Helvetica", fontext="afm")
  173. with open(fn, 'rb') as fh:
  174. afm = mpl._afm.AFM(fh)
  175. assert afm.string_width_height('VAVAVAVAVAVA') == (7174.0, 718)
  176. @image_comparison(['text_contains.png'])
  177. def test_contains():
  178. fig = plt.figure()
  179. ax = plt.axes()
  180. mevent = MouseEvent('button_press_event', fig.canvas, 0.5, 0.5, 1, None)
  181. xs = np.linspace(0.25, 0.75, 30)
  182. ys = np.linspace(0.25, 0.75, 30)
  183. xs, ys = np.meshgrid(xs, ys)
  184. txt = plt.text(
  185. 0.5, 0.4, 'hello world', ha='center', fontsize=30, rotation=30)
  186. # uncomment to draw the text's bounding box
  187. # txt.set_bbox(dict(edgecolor='black', facecolor='none'))
  188. # draw the text. This is important, as the contains method can only work
  189. # when a renderer exists.
  190. fig.canvas.draw()
  191. for x, y in zip(xs.flat, ys.flat):
  192. mevent.x, mevent.y = plt.gca().transAxes.transform([x, y])
  193. contains, _ = txt.contains(mevent)
  194. color = 'yellow' if contains else 'red'
  195. # capture the viewLim, plot a point, and reset the viewLim
  196. vl = ax.viewLim.frozen()
  197. ax.plot(x, y, 'o', color=color)
  198. ax.viewLim.set(vl)
  199. def test_annotation_contains():
  200. # Check that Annotation.contains looks at the bboxes of the text and the
  201. # arrow separately, not at the joint bbox.
  202. fig, ax = plt.subplots()
  203. ann = ax.annotate(
  204. "hello", xy=(.4, .4), xytext=(.6, .6), arrowprops={"arrowstyle": "->"})
  205. fig.canvas.draw() # Needed for the same reason as in test_contains.
  206. event = MouseEvent(
  207. "button_press_event", fig.canvas, *ax.transData.transform((.5, .6)))
  208. assert ann.contains(event) == (False, {})
  209. @pytest.mark.parametrize('err, xycoords, match', (
  210. (TypeError, print, "xycoords callable must return a BboxBase or Transform, not a"),
  211. (TypeError, [0, 0], r"'xycoords' must be an instance of str, tuple"),
  212. (ValueError, "foo", "'foo' is not a valid coordinate"),
  213. (ValueError, "foo bar", "'foo bar' is not a valid coordinate"),
  214. (ValueError, "offset foo", "xycoords cannot be an offset coordinate"),
  215. (ValueError, "axes foo", "'foo' is not a recognized unit"),
  216. ))
  217. def test_annotate_errors(err, xycoords, match):
  218. fig, ax = plt.subplots()
  219. with pytest.raises(err, match=match):
  220. ax.annotate('xy', (0, 0), xytext=(0.5, 0.5), xycoords=xycoords)
  221. fig.canvas.draw()
  222. @image_comparison(['titles'])
  223. def test_titles():
  224. # left and right side titles
  225. plt.figure()
  226. ax = plt.subplot(1, 1, 1)
  227. ax.set_title("left title", loc="left")
  228. ax.set_title("right title", loc="right")
  229. ax.set_xticks([])
  230. ax.set_yticks([])
  231. @image_comparison(['text_alignment'], style='mpl20')
  232. def test_alignment():
  233. plt.figure()
  234. ax = plt.subplot(1, 1, 1)
  235. x = 0.1
  236. for rotation in (0, 30):
  237. for alignment in ('top', 'bottom', 'baseline', 'center'):
  238. ax.text(
  239. x, 0.5, alignment + " Tj", va=alignment, rotation=rotation,
  240. bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
  241. ax.text(
  242. x, 1.0, r'$\sum_{i=0}^{j}$', va=alignment, rotation=rotation)
  243. x += 0.1
  244. ax.plot([0, 1], [0.5, 0.5])
  245. ax.plot([0, 1], [1.0, 1.0])
  246. ax.set_xlim(0, 1)
  247. ax.set_ylim(0, 1.5)
  248. ax.set_xticks([])
  249. ax.set_yticks([])
  250. @image_comparison(['axes_titles.png'])
  251. def test_axes_titles():
  252. # Related to issue #3327
  253. plt.figure()
  254. ax = plt.subplot(1, 1, 1)
  255. ax.set_title('center', loc='center', fontsize=20, fontweight=700)
  256. ax.set_title('left', loc='left', fontsize=12, fontweight=400)
  257. ax.set_title('right', loc='right', fontsize=12, fontweight=400)
  258. def test_set_position():
  259. fig, ax = plt.subplots()
  260. # test set_position
  261. ann = ax.annotate(
  262. 'test', (0, 0), xytext=(0, 0), textcoords='figure pixels')
  263. fig.canvas.draw()
  264. init_pos = ann.get_window_extent(fig.canvas.renderer)
  265. shift_val = 15
  266. ann.set_position((shift_val, shift_val))
  267. fig.canvas.draw()
  268. post_pos = ann.get_window_extent(fig.canvas.renderer)
  269. for a, b in zip(init_pos.min, post_pos.min):
  270. assert a + shift_val == b
  271. # test xyann
  272. ann = ax.annotate(
  273. 'test', (0, 0), xytext=(0, 0), textcoords='figure pixels')
  274. fig.canvas.draw()
  275. init_pos = ann.get_window_extent(fig.canvas.renderer)
  276. shift_val = 15
  277. ann.xyann = (shift_val, shift_val)
  278. fig.canvas.draw()
  279. post_pos = ann.get_window_extent(fig.canvas.renderer)
  280. for a, b in zip(init_pos.min, post_pos.min):
  281. assert a + shift_val == b
  282. def test_char_index_at():
  283. fig = plt.figure()
  284. text = fig.text(0.1, 0.9, "")
  285. text.set_text("i")
  286. bbox = text.get_window_extent()
  287. size_i = bbox.x1 - bbox.x0
  288. text.set_text("m")
  289. bbox = text.get_window_extent()
  290. size_m = bbox.x1 - bbox.x0
  291. text.set_text("iiiimmmm")
  292. bbox = text.get_window_extent()
  293. origin = bbox.x0
  294. assert text._char_index_at(origin - size_i) == 0 # left of first char
  295. assert text._char_index_at(origin) == 0
  296. assert text._char_index_at(origin + 0.499*size_i) == 0
  297. assert text._char_index_at(origin + 0.501*size_i) == 1
  298. assert text._char_index_at(origin + size_i*3) == 3
  299. assert text._char_index_at(origin + size_i*4 + size_m*3) == 7
  300. assert text._char_index_at(origin + size_i*4 + size_m*4) == 8
  301. assert text._char_index_at(origin + size_i*4 + size_m*10) == 8
  302. @pytest.mark.parametrize('text', ['', 'O'], ids=['empty', 'non-empty'])
  303. def test_non_default_dpi(text):
  304. fig, ax = plt.subplots()
  305. t1 = ax.text(0.5, 0.5, text, ha='left', va='bottom')
  306. fig.canvas.draw()
  307. dpi = fig.dpi
  308. bbox1 = t1.get_window_extent()
  309. bbox2 = t1.get_window_extent(dpi=dpi * 10)
  310. np.testing.assert_allclose(bbox2.get_points(), bbox1.get_points() * 10,
  311. rtol=5e-2)
  312. # Text.get_window_extent should not permanently change dpi.
  313. assert fig.dpi == dpi
  314. def test_get_rotation_string():
  315. assert Text(rotation='horizontal').get_rotation() == 0.
  316. assert Text(rotation='vertical').get_rotation() == 90.
  317. def test_get_rotation_float():
  318. for i in [15., 16.70, 77.4]:
  319. assert Text(rotation=i).get_rotation() == i
  320. def test_get_rotation_int():
  321. for i in [67, 16, 41]:
  322. assert Text(rotation=i).get_rotation() == float(i)
  323. def test_get_rotation_raises():
  324. with pytest.raises(ValueError):
  325. Text(rotation='hozirontal')
  326. def test_get_rotation_none():
  327. assert Text(rotation=None).get_rotation() == 0.0
  328. def test_get_rotation_mod360():
  329. for i, j in zip([360., 377., 720+177.2], [0., 17., 177.2]):
  330. assert_almost_equal(Text(rotation=i).get_rotation(), j)
  331. @pytest.mark.parametrize("ha", ["center", "right", "left"])
  332. @pytest.mark.parametrize("va", ["center", "top", "bottom",
  333. "baseline", "center_baseline"])
  334. def test_null_rotation_with_rotation_mode(ha, va):
  335. fig, ax = plt.subplots()
  336. kw = dict(rotation=0, va=va, ha=ha)
  337. t0 = ax.text(.5, .5, 'test', rotation_mode='anchor', **kw)
  338. t1 = ax.text(.5, .5, 'test', rotation_mode='default', **kw)
  339. fig.canvas.draw()
  340. assert_almost_equal(t0.get_window_extent(fig.canvas.renderer).get_points(),
  341. t1.get_window_extent(fig.canvas.renderer).get_points())
  342. @image_comparison(['text_bboxclip'])
  343. def test_bbox_clipping():
  344. plt.text(0.9, 0.2, 'Is bbox clipped?', backgroundcolor='r', clip_on=True)
  345. t = plt.text(0.9, 0.5, 'Is fancy bbox clipped?', clip_on=True)
  346. t.set_bbox({"boxstyle": "round, pad=0.1"})
  347. @image_comparison(['annotation_negative_ax_coords.png'])
  348. def test_annotation_negative_ax_coords():
  349. fig, ax = plt.subplots()
  350. ax.annotate('+ pts',
  351. xytext=[30, 20], textcoords='axes points',
  352. xy=[30, 20], xycoords='axes points', fontsize=32)
  353. ax.annotate('- pts',
  354. xytext=[30, -20], textcoords='axes points',
  355. xy=[30, -20], xycoords='axes points', fontsize=32,
  356. va='top')
  357. ax.annotate('+ frac',
  358. xytext=[0.75, 0.05], textcoords='axes fraction',
  359. xy=[0.75, 0.05], xycoords='axes fraction', fontsize=32)
  360. ax.annotate('- frac',
  361. xytext=[0.75, -0.05], textcoords='axes fraction',
  362. xy=[0.75, -0.05], xycoords='axes fraction', fontsize=32,
  363. va='top')
  364. ax.annotate('+ pixels',
  365. xytext=[160, 25], textcoords='axes pixels',
  366. xy=[160, 25], xycoords='axes pixels', fontsize=32)
  367. ax.annotate('- pixels',
  368. xytext=[160, -25], textcoords='axes pixels',
  369. xy=[160, -25], xycoords='axes pixels', fontsize=32,
  370. va='top')
  371. @image_comparison(['annotation_negative_fig_coords.png'])
  372. def test_annotation_negative_fig_coords():
  373. fig, ax = plt.subplots()
  374. ax.annotate('+ pts',
  375. xytext=[10, 120], textcoords='figure points',
  376. xy=[10, 120], xycoords='figure points', fontsize=32)
  377. ax.annotate('- pts',
  378. xytext=[-10, 180], textcoords='figure points',
  379. xy=[-10, 180], xycoords='figure points', fontsize=32,
  380. va='top')
  381. ax.annotate('+ frac',
  382. xytext=[0.05, 0.55], textcoords='figure fraction',
  383. xy=[0.05, 0.55], xycoords='figure fraction', fontsize=32)
  384. ax.annotate('- frac',
  385. xytext=[-0.05, 0.5], textcoords='figure fraction',
  386. xy=[-0.05, 0.5], xycoords='figure fraction', fontsize=32,
  387. va='top')
  388. ax.annotate('+ pixels',
  389. xytext=[50, 50], textcoords='figure pixels',
  390. xy=[50, 50], xycoords='figure pixels', fontsize=32)
  391. ax.annotate('- pixels',
  392. xytext=[-50, 100], textcoords='figure pixels',
  393. xy=[-50, 100], xycoords='figure pixels', fontsize=32,
  394. va='top')
  395. def test_text_stale():
  396. fig, (ax1, ax2) = plt.subplots(1, 2)
  397. plt.draw_all()
  398. assert not ax1.stale
  399. assert not ax2.stale
  400. assert not fig.stale
  401. txt1 = ax1.text(.5, .5, 'aardvark')
  402. assert ax1.stale
  403. assert txt1.stale
  404. assert fig.stale
  405. ann1 = ax2.annotate('aardvark', xy=[.5, .5])
  406. assert ax2.stale
  407. assert ann1.stale
  408. assert fig.stale
  409. plt.draw_all()
  410. assert not ax1.stale
  411. assert not ax2.stale
  412. assert not fig.stale
  413. @image_comparison(['agg_text_clip.png'])
  414. def test_agg_text_clip():
  415. np.random.seed(1)
  416. fig, (ax1, ax2) = plt.subplots(2)
  417. for x, y in np.random.rand(10, 2):
  418. ax1.text(x, y, "foo", clip_on=True)
  419. ax2.text(x, y, "foo")
  420. def test_text_size_binding():
  421. mpl.rcParams['font.size'] = 10
  422. fp = mpl.font_manager.FontProperties(size='large')
  423. sz1 = fp.get_size_in_points()
  424. mpl.rcParams['font.size'] = 100
  425. assert sz1 == fp.get_size_in_points()
  426. @image_comparison(['font_scaling.pdf'])
  427. def test_font_scaling():
  428. mpl.rcParams['pdf.fonttype'] = 42
  429. fig, ax = plt.subplots(figsize=(6.4, 12.4))
  430. ax.xaxis.set_major_locator(plt.NullLocator())
  431. ax.yaxis.set_major_locator(plt.NullLocator())
  432. ax.set_ylim(-10, 600)
  433. for i, fs in enumerate(range(4, 43, 2)):
  434. ax.text(0.1, i*30, f"{fs} pt font size", fontsize=fs)
  435. @pytest.mark.parametrize('spacing1, spacing2', [(0.4, 2), (2, 0.4), (2, 2)])
  436. def test_two_2line_texts(spacing1, spacing2):
  437. text_string = 'line1\nline2'
  438. fig = plt.figure()
  439. renderer = fig.canvas.get_renderer()
  440. text1 = fig.text(0.25, 0.5, text_string, linespacing=spacing1)
  441. text2 = fig.text(0.25, 0.5, text_string, linespacing=spacing2)
  442. fig.canvas.draw()
  443. box1 = text1.get_window_extent(renderer=renderer)
  444. box2 = text2.get_window_extent(renderer=renderer)
  445. # line spacing only affects height
  446. assert box1.width == box2.width
  447. if spacing1 == spacing2:
  448. assert box1.height == box2.height
  449. else:
  450. assert box1.height != box2.height
  451. def test_validate_linespacing():
  452. with pytest.raises(TypeError):
  453. plt.text(.25, .5, "foo", linespacing="abc")
  454. def test_nonfinite_pos():
  455. fig, ax = plt.subplots()
  456. ax.text(0, np.nan, 'nan')
  457. ax.text(np.inf, 0, 'inf')
  458. fig.canvas.draw()
  459. def test_hinting_factor_backends():
  460. plt.rcParams['text.hinting_factor'] = 1
  461. fig = plt.figure()
  462. t = fig.text(0.5, 0.5, 'some text')
  463. fig.savefig(io.BytesIO(), format='svg')
  464. expected = t.get_window_extent().intervalx
  465. fig.savefig(io.BytesIO(), format='png')
  466. # Backends should apply hinting_factor consistently (within 10%).
  467. np.testing.assert_allclose(t.get_window_extent().intervalx, expected,
  468. rtol=0.1)
  469. @needs_usetex
  470. def test_usetex_is_copied():
  471. # Indirectly tests that update_from (which is used to copy tick label
  472. # properties) copies usetex state.
  473. fig = plt.figure()
  474. plt.rcParams["text.usetex"] = False
  475. ax1 = fig.add_subplot(121)
  476. plt.rcParams["text.usetex"] = True
  477. ax2 = fig.add_subplot(122)
  478. fig.canvas.draw()
  479. for ax, usetex in [(ax1, False), (ax2, True)]:
  480. for t in ax.xaxis.majorTicks:
  481. assert t.label1.get_usetex() == usetex
  482. @needs_usetex
  483. def test_single_artist_usetex():
  484. # Check that a single artist marked with usetex does not get passed through
  485. # the mathtext parser at all (for the Agg backend) (the mathtext parser
  486. # currently fails to parse \frac12, requiring \frac{1}{2} instead).
  487. fig = plt.figure()
  488. fig.text(.5, .5, r"$\frac12$", usetex=True)
  489. fig.canvas.draw()
  490. @pytest.mark.parametrize("fmt", ["png", "pdf", "svg"])
  491. def test_single_artist_usenotex(fmt):
  492. # Check that a single artist can be marked as not-usetex even though the
  493. # rcParam is on ("2_2_2" fails if passed to TeX). This currently skips
  494. # postscript output as the ps renderer doesn't support mixing usetex and
  495. # non-usetex.
  496. plt.rcParams["text.usetex"] = True
  497. fig = plt.figure()
  498. fig.text(.5, .5, "2_2_2", usetex=False)
  499. fig.savefig(io.BytesIO(), format=fmt)
  500. @image_comparison(['text_as_path_opacity.svg'])
  501. def test_text_as_path_opacity():
  502. plt.figure()
  503. plt.gca().set_axis_off()
  504. plt.text(0.25, 0.25, 'c', color=(0, 0, 0, 0.5))
  505. plt.text(0.25, 0.5, 'a', alpha=0.5)
  506. plt.text(0.25, 0.75, 'x', alpha=0.5, color=(0, 0, 0, 1))
  507. @image_comparison(['text_as_text_opacity.svg'])
  508. def test_text_as_text_opacity():
  509. mpl.rcParams['svg.fonttype'] = 'none'
  510. plt.figure()
  511. plt.gca().set_axis_off()
  512. plt.text(0.25, 0.25, '50% using `color`', color=(0, 0, 0, 0.5))
  513. plt.text(0.25, 0.5, '50% using `alpha`', alpha=0.5)
  514. plt.text(0.25, 0.75, '50% using `alpha` and 100% `color`', alpha=0.5,
  515. color=(0, 0, 0, 1))
  516. def test_text_repr():
  517. # smoketest to make sure text repr doesn't error for category
  518. plt.plot(['A', 'B'], [1, 2])
  519. repr(plt.text(['A'], 0.5, 'Boo'))
  520. def test_annotation_update():
  521. fig, ax = plt.subplots(1, 1)
  522. an = ax.annotate('annotation', xy=(0.5, 0.5))
  523. extent1 = an.get_window_extent(fig.canvas.get_renderer())
  524. fig.tight_layout()
  525. extent2 = an.get_window_extent(fig.canvas.get_renderer())
  526. assert not np.allclose(extent1.get_points(), extent2.get_points(),
  527. rtol=1e-6)
  528. @check_figures_equal(extensions=["png"])
  529. def test_annotation_units(fig_test, fig_ref):
  530. ax = fig_test.add_subplot()
  531. ax.plot(datetime.now(), 1, "o") # Implicitly set axes extents.
  532. ax.annotate("x", (datetime.now(), 0.5), xycoords=("data", "axes fraction"),
  533. # This used to crash before.
  534. xytext=(0, 0), textcoords="offset points")
  535. ax = fig_ref.add_subplot()
  536. ax.plot(datetime.now(), 1, "o")
  537. ax.annotate("x", (datetime.now(), 0.5), xycoords=("data", "axes fraction"))
  538. @image_comparison(['large_subscript_title.png'], style='mpl20')
  539. def test_large_subscript_title():
  540. # Remove this line when this test image is regenerated.
  541. plt.rcParams['text.kerning_factor'] = 6
  542. plt.rcParams['axes.titley'] = None
  543. fig, axs = plt.subplots(1, 2, figsize=(9, 2.5), constrained_layout=True)
  544. ax = axs[0]
  545. ax.set_title(r'$\sum_{i} x_i$')
  546. ax.set_title('New way', loc='left')
  547. ax.set_xticklabels([])
  548. ax = axs[1]
  549. ax.set_title(r'$\sum_{i} x_i$', y=1.01)
  550. ax.set_title('Old Way', loc='left')
  551. ax.set_xticklabels([])
  552. @pytest.mark.parametrize(
  553. "x, rotation, halign",
  554. [(0.7, 0, 'left'),
  555. (0.5, 95, 'left'),
  556. (0.3, 0, 'right'),
  557. (0.3, 185, 'left')])
  558. def test_wrap(x, rotation, halign):
  559. fig = plt.figure(figsize=(6, 6))
  560. s = 'This is a very long text that should be wrapped multiple times.'
  561. text = fig.text(x, 0.7, s, wrap=True, rotation=rotation, ha=halign)
  562. fig.canvas.draw()
  563. assert text._get_wrapped_text() == ('This is a very long\n'
  564. 'text that should be\n'
  565. 'wrapped multiple\n'
  566. 'times.')
  567. def test_mathwrap():
  568. fig = plt.figure(figsize=(6, 4))
  569. s = r'This is a very $\overline{\mathrm{long}}$ line of Mathtext.'
  570. text = fig.text(0, 0.5, s, size=40, wrap=True)
  571. fig.canvas.draw()
  572. assert text._get_wrapped_text() == ('This is a very $\\overline{\\mathrm{long}}$\n'
  573. 'line of Mathtext.')
  574. def test_get_window_extent_wrapped():
  575. # Test that a long title that wraps to two lines has the same vertical
  576. # extent as an explicit two line title.
  577. fig1 = plt.figure(figsize=(3, 3))
  578. fig1.suptitle("suptitle that is clearly too long in this case", wrap=True)
  579. window_extent_test = fig1._suptitle.get_window_extent()
  580. fig2 = plt.figure(figsize=(3, 3))
  581. fig2.suptitle("suptitle that is clearly\ntoo long in this case")
  582. window_extent_ref = fig2._suptitle.get_window_extent()
  583. assert window_extent_test.y0 == window_extent_ref.y0
  584. assert window_extent_test.y1 == window_extent_ref.y1
  585. def test_long_word_wrap():
  586. fig = plt.figure(figsize=(6, 4))
  587. text = fig.text(9.5, 8, 'Alonglineoftexttowrap', wrap=True)
  588. fig.canvas.draw()
  589. assert text._get_wrapped_text() == 'Alonglineoftexttowrap'
  590. def test_wrap_no_wrap():
  591. fig = plt.figure(figsize=(6, 4))
  592. text = fig.text(0, 0, 'non wrapped text', wrap=True)
  593. fig.canvas.draw()
  594. assert text._get_wrapped_text() == 'non wrapped text'
  595. @check_figures_equal(extensions=["png"])
  596. def test_buffer_size(fig_test, fig_ref):
  597. # On old versions of the Agg renderer, large non-ascii single-character
  598. # strings (here, "€") would be rendered clipped because the rendering
  599. # buffer would be set by the physical size of the smaller "a" character.
  600. ax = fig_test.add_subplot()
  601. ax.set_yticks([0, 1])
  602. ax.set_yticklabels(["€", "a"])
  603. ax.yaxis.majorTicks[1].label1.set_color("w")
  604. ax = fig_ref.add_subplot()
  605. ax.set_yticks([0, 1])
  606. ax.set_yticklabels(["€", ""])
  607. def test_fontproperties_kwarg_precedence():
  608. """Test that kwargs take precedence over fontproperties defaults."""
  609. plt.figure()
  610. text1 = plt.xlabel("value", fontproperties='Times New Roman', size=40.0)
  611. text2 = plt.ylabel("counts", size=40.0, fontproperties='Times New Roman')
  612. assert text1.get_size() == 40.0
  613. assert text2.get_size() == 40.0
  614. def test_transform_rotates_text():
  615. ax = plt.gca()
  616. transform = mtransforms.Affine2D().rotate_deg(30)
  617. text = ax.text(0, 0, 'test', transform=transform,
  618. transform_rotates_text=True)
  619. result = text.get_rotation()
  620. assert_almost_equal(result, 30)
  621. def test_update_mutate_input():
  622. inp = dict(fontproperties=FontProperties(weight="bold"),
  623. bbox=None)
  624. cache = dict(inp)
  625. t = Text()
  626. t.update(inp)
  627. assert inp['fontproperties'] == cache['fontproperties']
  628. assert inp['bbox'] == cache['bbox']
  629. @pytest.mark.parametrize('rotation', ['invalid string', [90]])
  630. def test_invalid_rotation_values(rotation):
  631. with pytest.raises(
  632. ValueError,
  633. match=("rotation must be 'vertical', 'horizontal' or a number")):
  634. Text(0, 0, 'foo', rotation=rotation)
  635. def test_invalid_color():
  636. with pytest.raises(ValueError):
  637. plt.figtext(.5, .5, "foo", c="foobar")
  638. @image_comparison(['text_pdf_kerning.pdf'], style='mpl20')
  639. def test_pdf_kerning():
  640. plt.figure()
  641. plt.figtext(0.1, 0.5, "ATATATATATATATATATA", size=30)
  642. def test_unsupported_script(recwarn):
  643. fig = plt.figure()
  644. fig.text(.5, .5, "\N{BENGALI DIGIT ZERO}")
  645. fig.canvas.draw()
  646. assert all(isinstance(warn.message, UserWarning) for warn in recwarn)
  647. assert (
  648. [warn.message.args for warn in recwarn] ==
  649. [(r"Glyph 2534 (\N{BENGALI DIGIT ZERO}) missing from current font.",),
  650. (r"Matplotlib currently does not support Bengali natively.",)])
  651. # See gh-26152 for more information on this xfail
  652. @pytest.mark.xfail(pyparsing_version.release == (3, 1, 0),
  653. reason="Error messages are incorrect with pyparsing 3.1.0")
  654. def test_parse_math():
  655. fig, ax = plt.subplots()
  656. ax.text(0, 0, r"$ \wrong{math} $", parse_math=False)
  657. fig.canvas.draw()
  658. ax.text(0, 0, r"$ \wrong{math} $", parse_math=True)
  659. with pytest.raises(ValueError, match='Unknown symbol'):
  660. fig.canvas.draw()
  661. # See gh-26152 for more information on this xfail
  662. @pytest.mark.xfail(pyparsing_version.release == (3, 1, 0),
  663. reason="Error messages are incorrect with pyparsing 3.1.0")
  664. def test_parse_math_rcparams():
  665. # Default is True
  666. fig, ax = plt.subplots()
  667. ax.text(0, 0, r"$ \wrong{math} $")
  668. with pytest.raises(ValueError, match='Unknown symbol'):
  669. fig.canvas.draw()
  670. # Setting rcParams to False
  671. with mpl.rc_context({'text.parse_math': False}):
  672. fig, ax = plt.subplots()
  673. ax.text(0, 0, r"$ \wrong{math} $")
  674. fig.canvas.draw()
  675. @image_comparison(['text_pdf_font42_kerning.pdf'], style='mpl20')
  676. def test_pdf_font42_kerning():
  677. plt.rcParams['pdf.fonttype'] = 42
  678. plt.figure()
  679. plt.figtext(0.1, 0.5, "ATAVATAVATAVATAVATA", size=30)
  680. @image_comparison(['text_pdf_chars_beyond_bmp.pdf'], style='mpl20')
  681. def test_pdf_chars_beyond_bmp():
  682. plt.rcParams['pdf.fonttype'] = 42
  683. plt.rcParams['mathtext.fontset'] = 'stixsans'
  684. plt.figure()
  685. plt.figtext(0.1, 0.5, "Mass $m$ \U00010308", size=30)
  686. @needs_usetex
  687. def test_metrics_cache():
  688. mpl.text._get_text_metrics_with_cache_impl.cache_clear()
  689. fig = plt.figure()
  690. fig.text(.3, .5, "foo\nbar")
  691. fig.text(.3, .5, "foo\nbar", usetex=True)
  692. fig.text(.5, .5, "foo\nbar", usetex=True)
  693. fig.canvas.draw()
  694. renderer = fig._get_renderer()
  695. ys = {} # mapping of strings to where they were drawn in y with draw_tex.
  696. def call(*args, **kwargs):
  697. renderer, x, y, s, *_ = args
  698. ys.setdefault(s, set()).add(y)
  699. renderer.draw_tex = call
  700. fig.canvas.draw()
  701. assert [*ys] == ["foo", "bar"]
  702. # Check that both TeX strings were drawn with the same y-position for both
  703. # single-line substrings. Previously, there used to be an incorrect cache
  704. # collision with the non-TeX string (drawn first here) whose metrics would
  705. # get incorrectly reused by the first TeX string.
  706. assert len(ys["foo"]) == len(ys["bar"]) == 1
  707. info = mpl.text._get_text_metrics_with_cache_impl.cache_info()
  708. # Every string gets a miss for the first layouting (extents), then a hit
  709. # when drawing, but "foo\nbar" gets two hits as it's drawn twice.
  710. assert info.hits > info.misses
  711. def test_annotate_offset_fontsize():
  712. # Test that offset_fontsize parameter works and uses accurate values
  713. fig, ax = plt.subplots()
  714. text_coords = ['offset points', 'offset fontsize']
  715. # 10 points should be equal to 1 fontsize unit at fontsize=10
  716. xy_text = [(10, 10), (1, 1)]
  717. anns = [ax.annotate('test', xy=(0.5, 0.5),
  718. xytext=xy_text[i],
  719. fontsize='10',
  720. xycoords='data',
  721. textcoords=text_coords[i]) for i in range(2)]
  722. points_coords, fontsize_coords = [ann.get_window_extent() for ann in anns]
  723. fig.canvas.draw()
  724. assert str(points_coords) == str(fontsize_coords)
  725. def test_get_set_antialiased():
  726. txt = Text(.5, .5, "foo\nbar")
  727. assert txt._antialiased == mpl.rcParams['text.antialiased']
  728. assert txt.get_antialiased() == mpl.rcParams['text.antialiased']
  729. txt.set_antialiased(True)
  730. assert txt._antialiased is True
  731. assert txt.get_antialiased() == txt._antialiased
  732. txt.set_antialiased(False)
  733. assert txt._antialiased is False
  734. assert txt.get_antialiased() == txt._antialiased
  735. def test_annotation_antialiased():
  736. annot = Annotation("foo\nbar", (.5, .5), antialiased=True)
  737. assert annot._antialiased is True
  738. assert annot.get_antialiased() == annot._antialiased
  739. annot2 = Annotation("foo\nbar", (.5, .5), antialiased=False)
  740. assert annot2._antialiased is False
  741. assert annot2.get_antialiased() == annot2._antialiased
  742. annot3 = Annotation("foo\nbar", (.5, .5), antialiased=False)
  743. annot3.set_antialiased(True)
  744. assert annot3.get_antialiased() is True
  745. assert annot3._antialiased is True
  746. annot4 = Annotation("foo\nbar", (.5, .5))
  747. assert annot4._antialiased == mpl.rcParams['text.antialiased']
  748. @check_figures_equal(extensions=["png"])
  749. def test_annotate_and_offsetfrom_copy_input(fig_test, fig_ref):
  750. # Both approaches place the text (10, 0) pixels away from the center of the line.
  751. ax = fig_test.add_subplot()
  752. l, = ax.plot([0, 2], [0, 2])
  753. of_xy = np.array([.5, .5])
  754. ax.annotate("foo", textcoords=OffsetFrom(l, of_xy), xytext=(10, 0),
  755. xy=(0, 0)) # xy is unused.
  756. of_xy[:] = 1
  757. ax = fig_ref.add_subplot()
  758. l, = ax.plot([0, 2], [0, 2])
  759. an_xy = np.array([.5, .5])
  760. ax.annotate("foo", xy=an_xy, xycoords=l, xytext=(10, 0), textcoords="offset points")
  761. an_xy[:] = 2