test_text.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  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. import pytest
  7. import matplotlib
  8. from matplotlib.backend_bases import MouseEvent
  9. import matplotlib.patches as mpatches
  10. import matplotlib.pyplot as plt
  11. from matplotlib.testing.decorators import check_figures_equal, image_comparison
  12. needs_usetex = pytest.mark.skipif(
  13. not matplotlib.checkdep_usetex(True),
  14. reason="This test needs a TeX installation")
  15. @image_comparison(['font_styles'])
  16. def test_font_styles():
  17. def find_matplotlib_font(**kw):
  18. prop = FontProperties(**kw)
  19. path = findfont(prop, directory=matplotlib.get_data_path())
  20. return FontProperties(fname=path)
  21. from matplotlib.font_manager import FontProperties, findfont
  22. warnings.filterwarnings(
  23. 'ignore',
  24. r"findfont: Font family \[u?'Foo'\] not found. Falling back to .",
  25. UserWarning,
  26. module='matplotlib.font_manager')
  27. plt.figure()
  28. ax = plt.subplot(1, 1, 1)
  29. normalFont = find_matplotlib_font(
  30. family="sans-serif",
  31. style="normal",
  32. variant="normal",
  33. size=14)
  34. ax.annotate(
  35. "Normal Font",
  36. (0.1, 0.1),
  37. xycoords='axes fraction',
  38. fontproperties=normalFont)
  39. boldFont = find_matplotlib_font(
  40. family="Foo",
  41. style="normal",
  42. variant="normal",
  43. weight="bold",
  44. stretch=500,
  45. size=14)
  46. ax.annotate(
  47. "Bold Font",
  48. (0.1, 0.2),
  49. xycoords='axes fraction',
  50. fontproperties=boldFont)
  51. boldItemFont = find_matplotlib_font(
  52. family="sans serif",
  53. style="italic",
  54. variant="normal",
  55. weight=750,
  56. stretch=500,
  57. size=14)
  58. ax.annotate(
  59. "Bold Italic Font",
  60. (0.1, 0.3),
  61. xycoords='axes fraction',
  62. fontproperties=boldItemFont)
  63. lightFont = find_matplotlib_font(
  64. family="sans-serif",
  65. style="normal",
  66. variant="normal",
  67. weight=200,
  68. stretch=500,
  69. size=14)
  70. ax.annotate(
  71. "Light Font",
  72. (0.1, 0.4),
  73. xycoords='axes fraction',
  74. fontproperties=lightFont)
  75. condensedFont = find_matplotlib_font(
  76. family="sans-serif",
  77. style="normal",
  78. variant="normal",
  79. weight=500,
  80. stretch=100,
  81. size=14)
  82. ax.annotate(
  83. "Condensed Font",
  84. (0.1, 0.5),
  85. xycoords='axes fraction',
  86. fontproperties=condensedFont)
  87. ax.set_xticks([])
  88. ax.set_yticks([])
  89. @image_comparison(['multiline'])
  90. def test_multiline():
  91. plt.figure()
  92. ax = plt.subplot(1, 1, 1)
  93. ax.set_title("multiline\ntext alignment")
  94. plt.text(
  95. 0.2, 0.5, "TpTpTp\n$M$\nTpTpTp", size=20, ha="center", va="top")
  96. plt.text(
  97. 0.5, 0.5, "TpTpTp\n$M^{M^{M^{M}}}$\nTpTpTp", size=20,
  98. ha="center", va="top")
  99. plt.text(
  100. 0.8, 0.5, "TpTpTp\n$M_{q_{q_{q}}}$\nTpTpTp", size=20,
  101. ha="center", va="top")
  102. plt.xlim(0, 1)
  103. plt.ylim(0, 0.8)
  104. ax.set_xticks([])
  105. ax.set_yticks([])
  106. @image_comparison(['multiline2'], style='mpl20')
  107. def test_multiline2():
  108. # Remove this line when this test image is regenerated.
  109. plt.rcParams['text.kerning_factor'] = 6
  110. fig, ax = plt.subplots()
  111. ax.set_xlim([0, 1.4])
  112. ax.set_ylim([0, 2])
  113. ax.axhline(0.5, color='C2', linewidth=0.3)
  114. sts = ['Line', '2 Lineg\n 2 Lg', '$\\sum_i x $', 'hi $\\sum_i x $\ntest',
  115. 'test\n $\\sum_i x $', '$\\sum_i x $\n $\\sum_i x $']
  116. renderer = fig.canvas.get_renderer()
  117. def draw_box(ax, tt):
  118. bb = tt.get_window_extent(renderer)
  119. bbt = bb.inverse_transformed(ax.transAxes)
  120. r = mpatches.Rectangle((0, 0), 1, 1, clip_on=False,
  121. transform=ax.transAxes)
  122. r.set_bounds(bbt.bounds)
  123. ax.add_patch(r)
  124. horal = 'left'
  125. for nn, st in enumerate(sts):
  126. tt = ax.text(0.2 * nn + 0.1, 0.5, st, horizontalalignment=horal,
  127. verticalalignment='bottom')
  128. draw_box(ax, tt)
  129. ax.text(1.2, 0.5, 'Bottom align', color='C2')
  130. ax.axhline(1.3, color='C2', linewidth=0.3)
  131. for nn, st in enumerate(sts):
  132. tt = ax.text(0.2 * nn + 0.1, 1.3, st, horizontalalignment=horal,
  133. verticalalignment='top')
  134. draw_box(ax, tt)
  135. ax.text(1.2, 1.3, 'Top align', color='C2')
  136. ax.axhline(1.8, color='C2', linewidth=0.3)
  137. for nn, st in enumerate(sts):
  138. tt = ax.text(0.2 * nn + 0.1, 1.8, st, horizontalalignment=horal,
  139. verticalalignment='baseline')
  140. draw_box(ax, tt)
  141. ax.text(1.2, 1.8, 'Baseline align', color='C2')
  142. ax.axhline(0.1, color='C2', linewidth=0.3)
  143. for nn, st in enumerate(sts):
  144. tt = ax.text(0.2 * nn + 0.1, 0.1, st, horizontalalignment=horal,
  145. verticalalignment='bottom', rotation=20)
  146. draw_box(ax, tt)
  147. ax.text(1.2, 0.1, 'Bot align, rot20', color='C2')
  148. @image_comparison(['antialiased.png'])
  149. def test_antialiasing():
  150. matplotlib.rcParams['text.antialiased'] = True
  151. fig = plt.figure(figsize=(5.25, 0.75))
  152. fig.text(0.5, 0.75, "antialiased", horizontalalignment='center',
  153. verticalalignment='center')
  154. fig.text(0.5, 0.25, r"$\sqrt{x}$", horizontalalignment='center',
  155. verticalalignment='center')
  156. # NOTE: We don't need to restore the rcParams here, because the
  157. # test cleanup will do it for us. In fact, if we do it here, it
  158. # will turn antialiasing back off before the images are actually
  159. # rendered.
  160. def test_afm_kerning():
  161. from matplotlib.afm import AFM
  162. from matplotlib.font_manager import findfont
  163. fn = findfont("Helvetica", fontext="afm")
  164. with open(fn, 'rb') as fh:
  165. afm = AFM(fh)
  166. assert afm.string_width_height('VAVAVAVAVAVA') == (7174.0, 718)
  167. @image_comparison(['text_contains.png'])
  168. def test_contains():
  169. fig = plt.figure()
  170. ax = plt.axes()
  171. mevent = MouseEvent('button_press_event', fig.canvas, 0.5, 0.5, 1, None)
  172. xs = np.linspace(0.25, 0.75, 30)
  173. ys = np.linspace(0.25, 0.75, 30)
  174. xs, ys = np.meshgrid(xs, ys)
  175. txt = plt.text(
  176. 0.5, 0.4, 'hello world', ha='center', fontsize=30, rotation=30)
  177. # uncomment to draw the text's bounding box
  178. # txt.set_bbox(dict(edgecolor='black', facecolor='none'))
  179. # draw the text. This is important, as the contains method can only work
  180. # when a renderer exists.
  181. fig.canvas.draw()
  182. for x, y in zip(xs.flat, ys.flat):
  183. mevent.x, mevent.y = plt.gca().transAxes.transform([x, y])
  184. contains, _ = txt.contains(mevent)
  185. color = 'yellow' if contains else 'red'
  186. # capture the viewLim, plot a point, and reset the viewLim
  187. vl = ax.viewLim.frozen()
  188. ax.plot(x, y, 'o', color=color)
  189. ax.viewLim.set(vl)
  190. def test_annotation_contains():
  191. # Check that Annotation.contains looks at the bboxes of the text and the
  192. # arrow separately, not at the joint bbox.
  193. fig, ax = plt.subplots()
  194. ann = ax.annotate(
  195. "hello", xy=(.4, .4), xytext=(.6, .6), arrowprops={"arrowstyle": "->"})
  196. fig.canvas.draw() # Needed for the same reason as in test_contains.
  197. event = MouseEvent(
  198. "button_press_event", fig.canvas, *ax.transData.transform((.5, .6)))
  199. assert ann.contains(event) == (False, {})
  200. @image_comparison(['titles'])
  201. def test_titles():
  202. # left and right side titles
  203. plt.figure()
  204. ax = plt.subplot(1, 1, 1)
  205. ax.set_title("left title", loc="left")
  206. ax.set_title("right title", loc="right")
  207. ax.set_xticks([])
  208. ax.set_yticks([])
  209. @image_comparison(['text_alignment'], style='mpl20')
  210. def test_alignment():
  211. plt.figure()
  212. ax = plt.subplot(1, 1, 1)
  213. x = 0.1
  214. for rotation in (0, 30):
  215. for alignment in ('top', 'bottom', 'baseline', 'center'):
  216. ax.text(
  217. x, 0.5, alignment + " Tj", va=alignment, rotation=rotation,
  218. bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
  219. ax.text(
  220. x, 1.0, r'$\sum_{i=0}^{j}$', va=alignment, rotation=rotation)
  221. x += 0.1
  222. ax.plot([0, 1], [0.5, 0.5])
  223. ax.plot([0, 1], [1.0, 1.0])
  224. ax.set_xlim([0, 1])
  225. ax.set_ylim([0, 1.5])
  226. ax.set_xticks([])
  227. ax.set_yticks([])
  228. @image_comparison(['axes_titles.png'])
  229. def test_axes_titles():
  230. # Related to issue #3327
  231. plt.figure()
  232. ax = plt.subplot(1, 1, 1)
  233. ax.set_title('center', loc='center', fontsize=20, fontweight=700)
  234. ax.set_title('left', loc='left', fontsize=12, fontweight=400)
  235. ax.set_title('right', loc='right', fontsize=12, fontweight=400)
  236. def test_set_position():
  237. fig, ax = plt.subplots()
  238. # test set_position
  239. ann = ax.annotate(
  240. 'test', (0, 0), xytext=(0, 0), textcoords='figure pixels')
  241. fig.canvas.draw()
  242. init_pos = ann.get_window_extent(fig.canvas.renderer)
  243. shift_val = 15
  244. ann.set_position((shift_val, shift_val))
  245. fig.canvas.draw()
  246. post_pos = ann.get_window_extent(fig.canvas.renderer)
  247. for a, b in zip(init_pos.min, post_pos.min):
  248. assert a + shift_val == b
  249. # test xyann
  250. ann = ax.annotate(
  251. 'test', (0, 0), xytext=(0, 0), textcoords='figure pixels')
  252. fig.canvas.draw()
  253. init_pos = ann.get_window_extent(fig.canvas.renderer)
  254. shift_val = 15
  255. ann.xyann = (shift_val, shift_val)
  256. fig.canvas.draw()
  257. post_pos = ann.get_window_extent(fig.canvas.renderer)
  258. for a, b in zip(init_pos.min, post_pos.min):
  259. assert a + shift_val == b
  260. def test_get_rotation_string():
  261. from matplotlib import text
  262. assert text.get_rotation('horizontal') == 0.
  263. assert text.get_rotation('vertical') == 90.
  264. assert text.get_rotation('15.') == 15.
  265. def test_get_rotation_float():
  266. from matplotlib import text
  267. for i in [15., 16.70, 77.4]:
  268. assert text.get_rotation(i) == i
  269. def test_get_rotation_int():
  270. from matplotlib import text
  271. for i in [67, 16, 41]:
  272. assert text.get_rotation(i) == float(i)
  273. def test_get_rotation_raises():
  274. from matplotlib import text
  275. with pytest.raises(ValueError):
  276. text.get_rotation('hozirontal')
  277. def test_get_rotation_none():
  278. from matplotlib import text
  279. assert text.get_rotation(None) == 0.0
  280. def test_get_rotation_mod360():
  281. from matplotlib import text
  282. for i, j in zip([360., 377., 720+177.2], [0., 17., 177.2]):
  283. assert_almost_equal(text.get_rotation(i), j)
  284. @pytest.mark.parametrize("ha", ["center", "right", "left"])
  285. @pytest.mark.parametrize("va", ["center", "top", "bottom",
  286. "baseline", "center_baseline"])
  287. def test_null_rotation_with_rotation_mode(ha, va):
  288. fig, ax = plt.subplots()
  289. kw = dict(rotation=0, va=va, ha=ha)
  290. t0 = ax.text(.5, .5, 'test', rotation_mode='anchor', **kw)
  291. t1 = ax.text(.5, .5, 'test', rotation_mode='default', **kw)
  292. fig.canvas.draw()
  293. assert_almost_equal(t0.get_window_extent(fig.canvas.renderer).get_points(),
  294. t1.get_window_extent(fig.canvas.renderer).get_points())
  295. @image_comparison(['text_bboxclip'])
  296. def test_bbox_clipping():
  297. plt.text(0.9, 0.2, 'Is bbox clipped?', backgroundcolor='r', clip_on=True)
  298. t = plt.text(0.9, 0.5, 'Is fancy bbox clipped?', clip_on=True)
  299. t.set_bbox({"boxstyle": "round, pad=0.1"})
  300. @image_comparison(['annotation_negative_ax_coords.png'])
  301. def test_annotation_negative_ax_coords():
  302. fig, ax = plt.subplots()
  303. ax.annotate('+ pts',
  304. xytext=[30, 20], textcoords='axes points',
  305. xy=[30, 20], xycoords='axes points', fontsize=32)
  306. ax.annotate('- pts',
  307. xytext=[30, -20], textcoords='axes points',
  308. xy=[30, -20], xycoords='axes points', fontsize=32,
  309. va='top')
  310. ax.annotate('+ frac',
  311. xytext=[0.75, 0.05], textcoords='axes fraction',
  312. xy=[0.75, 0.05], xycoords='axes fraction', fontsize=32)
  313. ax.annotate('- frac',
  314. xytext=[0.75, -0.05], textcoords='axes fraction',
  315. xy=[0.75, -0.05], xycoords='axes fraction', fontsize=32,
  316. va='top')
  317. ax.annotate('+ pixels',
  318. xytext=[160, 25], textcoords='axes pixels',
  319. xy=[160, 25], xycoords='axes pixels', fontsize=32)
  320. ax.annotate('- pixels',
  321. xytext=[160, -25], textcoords='axes pixels',
  322. xy=[160, -25], xycoords='axes pixels', fontsize=32,
  323. va='top')
  324. @image_comparison(['annotation_negative_fig_coords.png'])
  325. def test_annotation_negative_fig_coords():
  326. fig, ax = plt.subplots()
  327. ax.annotate('+ pts',
  328. xytext=[10, 120], textcoords='figure points',
  329. xy=[10, 120], xycoords='figure points', fontsize=32)
  330. ax.annotate('- pts',
  331. xytext=[-10, 180], textcoords='figure points',
  332. xy=[-10, 180], xycoords='figure points', fontsize=32,
  333. va='top')
  334. ax.annotate('+ frac',
  335. xytext=[0.05, 0.55], textcoords='figure fraction',
  336. xy=[0.05, 0.55], xycoords='figure fraction', fontsize=32)
  337. ax.annotate('- frac',
  338. xytext=[-0.05, 0.5], textcoords='figure fraction',
  339. xy=[-0.05, 0.5], xycoords='figure fraction', fontsize=32,
  340. va='top')
  341. ax.annotate('+ pixels',
  342. xytext=[50, 50], textcoords='figure pixels',
  343. xy=[50, 50], xycoords='figure pixels', fontsize=32)
  344. ax.annotate('- pixels',
  345. xytext=[-50, 100], textcoords='figure pixels',
  346. xy=[-50, 100], xycoords='figure pixels', fontsize=32,
  347. va='top')
  348. def test_text_stale():
  349. fig, (ax1, ax2) = plt.subplots(1, 2)
  350. plt.draw_all()
  351. assert not ax1.stale
  352. assert not ax2.stale
  353. assert not fig.stale
  354. txt1 = ax1.text(.5, .5, 'aardvark')
  355. assert ax1.stale
  356. assert txt1.stale
  357. assert fig.stale
  358. ann1 = ax2.annotate('aardvark', xy=[.5, .5])
  359. assert ax2.stale
  360. assert ann1.stale
  361. assert fig.stale
  362. plt.draw_all()
  363. assert not ax1.stale
  364. assert not ax2.stale
  365. assert not fig.stale
  366. @image_comparison(['agg_text_clip.png'])
  367. def test_agg_text_clip():
  368. np.random.seed(1)
  369. fig, (ax1, ax2) = plt.subplots(2)
  370. for x, y in np.random.rand(10, 2):
  371. ax1.text(x, y, "foo", clip_on=True)
  372. ax2.text(x, y, "foo")
  373. def test_text_size_binding():
  374. from matplotlib.font_manager import FontProperties
  375. matplotlib.rcParams['font.size'] = 10
  376. fp = FontProperties(size='large')
  377. sz1 = fp.get_size_in_points()
  378. matplotlib.rcParams['font.size'] = 100
  379. assert sz1 == fp.get_size_in_points()
  380. @image_comparison(['font_scaling.pdf'])
  381. def test_font_scaling():
  382. matplotlib.rcParams['pdf.fonttype'] = 42
  383. fig, ax = plt.subplots(figsize=(6.4, 12.4))
  384. ax.xaxis.set_major_locator(plt.NullLocator())
  385. ax.yaxis.set_major_locator(plt.NullLocator())
  386. ax.set_ylim(-10, 600)
  387. for i, fs in enumerate(range(4, 43, 2)):
  388. ax.text(0.1, i*30, "{fs} pt font size".format(fs=fs), fontsize=fs)
  389. @pytest.mark.parametrize('spacing1, spacing2', [(0.4, 2), (2, 0.4), (2, 2)])
  390. def test_two_2line_texts(spacing1, spacing2):
  391. text_string = 'line1\nline2'
  392. fig = plt.figure()
  393. renderer = fig.canvas.get_renderer()
  394. text1 = plt.text(0.25, 0.5, text_string, linespacing=spacing1)
  395. text2 = plt.text(0.25, 0.5, text_string, linespacing=spacing2)
  396. fig.canvas.draw()
  397. box1 = text1.get_window_extent(renderer=renderer)
  398. box2 = text2.get_window_extent(renderer=renderer)
  399. # line spacing only affects height
  400. assert box1.width == box2.width
  401. if spacing1 == spacing2:
  402. assert box1.height == box2.height
  403. else:
  404. assert box1.height != box2.height
  405. def test_nonfinite_pos():
  406. fig, ax = plt.subplots()
  407. ax.text(0, np.nan, 'nan')
  408. ax.text(np.inf, 0, 'inf')
  409. fig.canvas.draw()
  410. def test_hinting_factor_backends():
  411. plt.rcParams['text.hinting_factor'] = 1
  412. fig = plt.figure()
  413. t = fig.text(0.5, 0.5, 'some text')
  414. fig.savefig(io.BytesIO(), format='svg')
  415. expected = t.get_window_extent().intervalx
  416. fig.savefig(io.BytesIO(), format='png')
  417. # Backends should apply hinting_factor consistently (within 10%).
  418. np.testing.assert_allclose(t.get_window_extent().intervalx, expected,
  419. rtol=0.1)
  420. @needs_usetex
  421. def test_single_artist_usetex():
  422. # Check that a single artist marked with usetex does not get passed through
  423. # the mathtext parser at all (for the Agg backend) (the mathtext parser
  424. # currently fails to parse \frac12, requiring \frac{1}{2} instead).
  425. fig, ax = plt.subplots()
  426. ax.text(.5, .5, r"$\frac12$", usetex=True)
  427. fig.canvas.draw()
  428. @image_comparison(['text_as_path_opacity.svg'])
  429. def test_text_as_path_opacity():
  430. plt.figure()
  431. plt.gca().set_axis_off()
  432. plt.text(0.25, 0.25, 'c', color=(0, 0, 0, 0.5))
  433. plt.text(0.25, 0.5, 'a', alpha=0.5)
  434. plt.text(0.25, 0.75, 'x', alpha=0.5, color=(0, 0, 0, 1))
  435. @image_comparison(['text_as_text_opacity.svg'])
  436. def test_text_as_text_opacity():
  437. matplotlib.rcParams['svg.fonttype'] = 'none'
  438. plt.figure()
  439. plt.gca().set_axis_off()
  440. plt.text(0.25, 0.25, '50% using `color`', color=(0, 0, 0, 0.5))
  441. plt.text(0.25, 0.5, '50% using `alpha`', alpha=0.5)
  442. plt.text(0.25, 0.75, '50% using `alpha` and 100% `color`', alpha=0.5,
  443. color=(0, 0, 0, 1))
  444. def test_text_repr():
  445. # smoketest to make sure text repr doesn't error for category
  446. plt.plot(['A', 'B'], [1, 2])
  447. txt = plt.text(['A'], 0.5, 'Boo')
  448. print(txt)
  449. def test_annotation_update():
  450. fig, ax = plt.subplots(1, 1)
  451. an = ax.annotate('annotation', xy=(0.5, 0.5))
  452. extent1 = an.get_window_extent(fig.canvas.get_renderer())
  453. fig.tight_layout()
  454. extent2 = an.get_window_extent(fig.canvas.get_renderer())
  455. assert not np.allclose(extent1.get_points(), extent2.get_points(),
  456. rtol=1e-6)
  457. @check_figures_equal(extensions=["png"])
  458. def test_annotation_units(fig_test, fig_ref):
  459. ax = fig_test.add_subplot()
  460. ax.plot(datetime.now(), 1, "o") # Implicitly set axes extents.
  461. ax.annotate("x", (datetime.now(), 0.5), xycoords=("data", "axes fraction"),
  462. # This used to crash before.
  463. xytext=(0, 0), textcoords="offset points")
  464. ax = fig_ref.add_subplot()
  465. ax.plot(datetime.now(), 1, "o")
  466. ax.annotate("x", (datetime.now(), 0.5), xycoords=("data", "axes fraction"))
  467. @image_comparison(['large_subscript_title.png'], style='mpl20')
  468. def test_large_subscript_title():
  469. # Remove this line when this test image is regenerated.
  470. plt.rcParams['text.kerning_factor'] = 6
  471. fig, axs = plt.subplots(1, 2, figsize=(9, 2.5), constrained_layout=True)
  472. ax = axs[0]
  473. ax.set_title(r'$\sum_{i} x_i$')
  474. ax.set_title('New way', loc='left')
  475. ax.set_xticklabels('')
  476. ax = axs[1]
  477. tt = ax.set_title(r'$\sum_{i} x_i$')
  478. x, y = tt.get_position()
  479. tt.set_position((x, 1.01))
  480. ax.set_title('Old Way', loc='left')
  481. ax.set_xticklabels('')
  482. def test_wrap():
  483. fig = plt.figure(figsize=(6, 4))
  484. s = 'This is a very long text that should be wrapped multiple times.'
  485. text = fig.text(0.7, 0.5, s, wrap=True)
  486. fig.canvas.draw()
  487. assert text._get_wrapped_text() == ('This is a very long\n'
  488. 'text that should be\n'
  489. 'wrapped multiple\n'
  490. 'times.')
  491. def test_long_word_wrap():
  492. fig = plt.figure(figsize=(6, 4))
  493. text = fig.text(9.5, 8, 'Alonglineoftexttowrap', wrap=True)
  494. fig.canvas.draw()
  495. assert text._get_wrapped_text() == 'Alonglineoftexttowrap'
  496. def test_wrap_no_wrap():
  497. fig = plt.figure(figsize=(6, 4))
  498. text = fig.text(0, 0, 'non wrapped text', wrap=True)
  499. fig.canvas.draw()
  500. assert text._get_wrapped_text() == 'non wrapped text'
  501. @check_figures_equal(extensions=["png"])
  502. def test_buffer_size(fig_test, fig_ref):
  503. # On old versions of the Agg renderer, large non-ascii single-character
  504. # strings (here, "€") would be rendered clipped because the rendering
  505. # buffer would be set by the physical size of the smaller "a" character.
  506. ax = fig_test.add_subplot()
  507. ax.set_yticks([0, 1])
  508. ax.set_yticklabels(["€", "a"])
  509. ax.yaxis.majorTicks[1].label1.set_color("w")
  510. ax = fig_ref.add_subplot()
  511. ax.set_yticks([0, 1])
  512. ax.set_yticklabels(["€", ""])