test_backend_svg.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. import datetime
  2. from io import BytesIO
  3. from pathlib import Path
  4. import xml.etree.ElementTree
  5. import xml.parsers.expat
  6. import pytest
  7. import numpy as np
  8. import matplotlib as mpl
  9. from matplotlib.figure import Figure
  10. from matplotlib.patches import Circle
  11. from matplotlib.text import Text
  12. import matplotlib.pyplot as plt
  13. from matplotlib.testing.decorators import check_figures_equal, image_comparison
  14. from matplotlib.testing._markers import needs_usetex
  15. from matplotlib import font_manager as fm
  16. from matplotlib.offsetbox import (OffsetImage, AnnotationBbox)
  17. def test_visibility():
  18. fig, ax = plt.subplots()
  19. x = np.linspace(0, 4 * np.pi, 50)
  20. y = np.sin(x)
  21. yerr = np.ones_like(y)
  22. a, b, c = ax.errorbar(x, y, yerr=yerr, fmt='ko')
  23. for artist in b:
  24. artist.set_visible(False)
  25. with BytesIO() as fd:
  26. fig.savefig(fd, format='svg')
  27. buf = fd.getvalue()
  28. parser = xml.parsers.expat.ParserCreate()
  29. parser.Parse(buf) # this will raise ExpatError if the svg is invalid
  30. @image_comparison(['fill_black_with_alpha.svg'], remove_text=True)
  31. def test_fill_black_with_alpha():
  32. fig, ax = plt.subplots()
  33. ax.scatter(x=[0, 0.1, 1], y=[0, 0, 0], c='k', alpha=0.1, s=10000)
  34. @image_comparison(['noscale'], remove_text=True)
  35. def test_noscale():
  36. X, Y = np.meshgrid(np.arange(-5, 5, 1), np.arange(-5, 5, 1))
  37. Z = np.sin(Y ** 2)
  38. fig, ax = plt.subplots()
  39. ax.imshow(Z, cmap='gray', interpolation='none')
  40. def test_text_urls():
  41. fig = plt.figure()
  42. test_url = "http://test_text_urls.matplotlib.org"
  43. fig.suptitle("test_text_urls", url=test_url)
  44. with BytesIO() as fd:
  45. fig.savefig(fd, format='svg')
  46. buf = fd.getvalue().decode()
  47. expected = f'<a xlink:href="{test_url}">'
  48. assert expected in buf
  49. @image_comparison(['bold_font_output.svg'])
  50. def test_bold_font_output():
  51. fig, ax = plt.subplots()
  52. ax.plot(np.arange(10), np.arange(10))
  53. ax.set_xlabel('nonbold-xlabel')
  54. ax.set_ylabel('bold-ylabel', fontweight='bold')
  55. ax.set_title('bold-title', fontweight='bold')
  56. @image_comparison(['bold_font_output_with_none_fonttype.svg'])
  57. def test_bold_font_output_with_none_fonttype():
  58. plt.rcParams['svg.fonttype'] = 'none'
  59. fig, ax = plt.subplots()
  60. ax.plot(np.arange(10), np.arange(10))
  61. ax.set_xlabel('nonbold-xlabel')
  62. ax.set_ylabel('bold-ylabel', fontweight='bold')
  63. ax.set_title('bold-title', fontweight='bold')
  64. @check_figures_equal(tol=20)
  65. def test_rasterized(fig_test, fig_ref):
  66. t = np.arange(0, 100) * (2.3)
  67. x = np.cos(t)
  68. y = np.sin(t)
  69. ax_ref = fig_ref.subplots()
  70. ax_ref.plot(x, y, "-", c="r", lw=10)
  71. ax_ref.plot(x+1, y, "-", c="b", lw=10)
  72. ax_test = fig_test.subplots()
  73. ax_test.plot(x, y, "-", c="r", lw=10, rasterized=True)
  74. ax_test.plot(x+1, y, "-", c="b", lw=10, rasterized=True)
  75. @check_figures_equal(extensions=['svg'])
  76. def test_rasterized_ordering(fig_test, fig_ref):
  77. t = np.arange(0, 100) * (2.3)
  78. x = np.cos(t)
  79. y = np.sin(t)
  80. ax_ref = fig_ref.subplots()
  81. ax_ref.set_xlim(0, 3)
  82. ax_ref.set_ylim(-1.1, 1.1)
  83. ax_ref.plot(x, y, "-", c="r", lw=10, rasterized=True)
  84. ax_ref.plot(x+1, y, "-", c="b", lw=10, rasterized=False)
  85. ax_ref.plot(x+2, y, "-", c="g", lw=10, rasterized=True)
  86. ax_ref.plot(x+3, y, "-", c="m", lw=10, rasterized=True)
  87. ax_test = fig_test.subplots()
  88. ax_test.set_xlim(0, 3)
  89. ax_test.set_ylim(-1.1, 1.1)
  90. ax_test.plot(x, y, "-", c="r", lw=10, rasterized=True, zorder=1.1)
  91. ax_test.plot(x+2, y, "-", c="g", lw=10, rasterized=True, zorder=1.3)
  92. ax_test.plot(x+3, y, "-", c="m", lw=10, rasterized=True, zorder=1.4)
  93. ax_test.plot(x+1, y, "-", c="b", lw=10, rasterized=False, zorder=1.2)
  94. @check_figures_equal(tol=5, extensions=['svg', 'pdf'])
  95. def test_prevent_rasterization(fig_test, fig_ref):
  96. loc = [0.05, 0.05]
  97. ax_ref = fig_ref.subplots()
  98. ax_ref.plot([loc[0]], [loc[1]], marker="x", c="black", zorder=2)
  99. b = mpl.offsetbox.TextArea("X")
  100. abox = mpl.offsetbox.AnnotationBbox(b, loc, zorder=2.1)
  101. ax_ref.add_artist(abox)
  102. ax_test = fig_test.subplots()
  103. ax_test.plot([loc[0]], [loc[1]], marker="x", c="black", zorder=2,
  104. rasterized=True)
  105. b = mpl.offsetbox.TextArea("X")
  106. abox = mpl.offsetbox.AnnotationBbox(b, loc, zorder=2.1)
  107. ax_test.add_artist(abox)
  108. def test_count_bitmaps():
  109. def count_tag(fig, tag):
  110. with BytesIO() as fd:
  111. fig.savefig(fd, format='svg')
  112. buf = fd.getvalue().decode()
  113. return buf.count(f"<{tag}")
  114. # No rasterized elements
  115. fig1 = plt.figure()
  116. ax1 = fig1.add_subplot(1, 1, 1)
  117. ax1.set_axis_off()
  118. for n in range(5):
  119. ax1.plot([0, 20], [0, n], "b-", rasterized=False)
  120. assert count_tag(fig1, "image") == 0
  121. assert count_tag(fig1, "path") == 6 # axis patch plus lines
  122. # rasterized can be merged
  123. fig2 = plt.figure()
  124. ax2 = fig2.add_subplot(1, 1, 1)
  125. ax2.set_axis_off()
  126. for n in range(5):
  127. ax2.plot([0, 20], [0, n], "b-", rasterized=True)
  128. assert count_tag(fig2, "image") == 1
  129. assert count_tag(fig2, "path") == 1 # axis patch
  130. # rasterized can't be merged without affecting draw order
  131. fig3 = plt.figure()
  132. ax3 = fig3.add_subplot(1, 1, 1)
  133. ax3.set_axis_off()
  134. for n in range(5):
  135. ax3.plot([0, 20], [n, 0], "b-", rasterized=False)
  136. ax3.plot([0, 20], [0, n], "b-", rasterized=True)
  137. assert count_tag(fig3, "image") == 5
  138. assert count_tag(fig3, "path") == 6
  139. # rasterized whole axes
  140. fig4 = plt.figure()
  141. ax4 = fig4.add_subplot(1, 1, 1)
  142. ax4.set_axis_off()
  143. ax4.set_rasterized(True)
  144. for n in range(5):
  145. ax4.plot([0, 20], [n, 0], "b-", rasterized=False)
  146. ax4.plot([0, 20], [0, n], "b-", rasterized=True)
  147. assert count_tag(fig4, "image") == 1
  148. assert count_tag(fig4, "path") == 1
  149. # rasterized can be merged, but inhibited by suppressComposite
  150. fig5 = plt.figure()
  151. fig5.suppressComposite = True
  152. ax5 = fig5.add_subplot(1, 1, 1)
  153. ax5.set_axis_off()
  154. for n in range(5):
  155. ax5.plot([0, 20], [0, n], "b-", rasterized=True)
  156. assert count_tag(fig5, "image") == 5
  157. assert count_tag(fig5, "path") == 1 # axis patch
  158. # Use Computer Modern Sans Serif, not Helvetica (which has no \textwon).
  159. @mpl.style.context('default')
  160. @needs_usetex
  161. def test_unicode_won():
  162. fig = Figure()
  163. fig.text(.5, .5, r'\textwon', usetex=True)
  164. with BytesIO() as fd:
  165. fig.savefig(fd, format='svg')
  166. buf = fd.getvalue()
  167. tree = xml.etree.ElementTree.fromstring(buf)
  168. ns = 'http://www.w3.org/2000/svg'
  169. won_id = 'SFSS3583-8e'
  170. assert len(tree.findall(f'.//{{{ns}}}path[@d][@id="{won_id}"]')) == 1
  171. assert f'#{won_id}' in tree.find(f'.//{{{ns}}}use').attrib.values()
  172. def test_svgnone_with_data_coordinates():
  173. plt.rcParams.update({'svg.fonttype': 'none', 'font.stretch': 'condensed'})
  174. expected = 'Unlikely to appear by chance'
  175. fig, ax = plt.subplots()
  176. ax.text(np.datetime64('2019-06-30'), 1, expected)
  177. ax.set_xlim(np.datetime64('2019-01-01'), np.datetime64('2019-12-31'))
  178. ax.set_ylim(0, 2)
  179. with BytesIO() as fd:
  180. fig.savefig(fd, format='svg')
  181. fd.seek(0)
  182. buf = fd.read().decode()
  183. assert expected in buf and "condensed" in buf
  184. def test_gid():
  185. """Test that object gid appears in output svg."""
  186. from matplotlib.offsetbox import OffsetBox
  187. from matplotlib.axis import Tick
  188. fig = plt.figure()
  189. ax1 = fig.add_subplot(131)
  190. ax1.imshow([[1., 2.], [2., 3.]], aspect="auto")
  191. ax1.scatter([1, 2, 3], [1, 2, 3], label="myscatter")
  192. ax1.plot([2, 3, 1], label="myplot")
  193. ax1.legend()
  194. ax1a = ax1.twinx()
  195. ax1a.bar([1, 2, 3], [1, 2, 3])
  196. ax2 = fig.add_subplot(132, projection="polar")
  197. ax2.plot([0, 1.5, 3], [1, 2, 3])
  198. ax3 = fig.add_subplot(133, projection="3d")
  199. ax3.plot([1, 2], [1, 2], [1, 2])
  200. fig.canvas.draw()
  201. gdic = {}
  202. for idx, obj in enumerate(fig.findobj(include_self=True)):
  203. if obj.get_visible():
  204. gid = f"test123{obj.__class__.__name__}_{idx}"
  205. gdic[gid] = obj
  206. obj.set_gid(gid)
  207. with BytesIO() as fd:
  208. fig.savefig(fd, format='svg')
  209. buf = fd.getvalue().decode()
  210. def include(gid, obj):
  211. # we need to exclude certain objects which will not appear in the svg
  212. if isinstance(obj, OffsetBox):
  213. return False
  214. if isinstance(obj, Text):
  215. if obj.get_text() == "":
  216. return False
  217. elif obj.axes is None:
  218. return False
  219. if isinstance(obj, plt.Line2D):
  220. xdata, ydata = obj.get_data()
  221. if len(xdata) == len(ydata) == 1:
  222. return False
  223. elif not hasattr(obj, "axes") or obj.axes is None:
  224. return False
  225. if isinstance(obj, Tick):
  226. loc = obj.get_loc()
  227. if loc == 0:
  228. return False
  229. vi = obj.get_view_interval()
  230. if loc < min(vi) or loc > max(vi):
  231. return False
  232. return True
  233. for gid, obj in gdic.items():
  234. if include(gid, obj):
  235. assert gid in buf
  236. def test_clip_path_ids_reuse():
  237. fig, circle = Figure(), Circle((0, 0), radius=10)
  238. for i in range(5):
  239. ax = fig.add_subplot()
  240. aimg = ax.imshow([[i]])
  241. aimg.set_clip_path(circle)
  242. inner_circle = Circle((0, 0), radius=1)
  243. ax = fig.add_subplot()
  244. aimg = ax.imshow([[0]])
  245. aimg.set_clip_path(inner_circle)
  246. with BytesIO() as fd:
  247. fig.savefig(fd, format='svg')
  248. buf = fd.getvalue()
  249. tree = xml.etree.ElementTree.fromstring(buf)
  250. ns = 'http://www.w3.org/2000/svg'
  251. clip_path_ids = set()
  252. for node in tree.findall(f'.//{{{ns}}}clipPath[@id]'):
  253. node_id = node.attrib['id']
  254. assert node_id not in clip_path_ids # assert ID uniqueness
  255. clip_path_ids.add(node_id)
  256. assert len(clip_path_ids) == 2 # only two clipPaths despite reuse in multiple axes
  257. def test_savefig_tight():
  258. # Check that the draw-disabled renderer correctly disables open/close_group
  259. # as well.
  260. plt.savefig(BytesIO(), format="svgz", bbox_inches="tight")
  261. def test_url():
  262. # Test that object url appears in output svg.
  263. fig, ax = plt.subplots()
  264. # collections
  265. s = ax.scatter([1, 2, 3], [4, 5, 6])
  266. s.set_urls(['https://example.com/foo', 'https://example.com/bar', None])
  267. # Line2D
  268. p, = plt.plot([2, 3, 4], [4, 5, 6])
  269. p.set_url('https://example.com/baz')
  270. # Line2D markers-only
  271. p, = plt.plot([3, 4, 5], [4, 5, 6], linestyle='none', marker='x')
  272. p.set_url('https://example.com/quux')
  273. b = BytesIO()
  274. fig.savefig(b, format='svg')
  275. b = b.getvalue()
  276. for v in [b'foo', b'bar', b'baz', b'quux']:
  277. assert b'https://example.com/' + v in b
  278. def test_url_tick(monkeypatch):
  279. monkeypatch.setenv('SOURCE_DATE_EPOCH', '19680801')
  280. fig1, ax = plt.subplots()
  281. ax.scatter([1, 2, 3], [4, 5, 6])
  282. for i, tick in enumerate(ax.yaxis.get_major_ticks()):
  283. tick.set_url(f'https://example.com/{i}')
  284. fig2, ax = plt.subplots()
  285. ax.scatter([1, 2, 3], [4, 5, 6])
  286. for i, tick in enumerate(ax.yaxis.get_major_ticks()):
  287. tick.label1.set_url(f'https://example.com/{i}')
  288. tick.label2.set_url(f'https://example.com/{i}')
  289. b1 = BytesIO()
  290. fig1.savefig(b1, format='svg')
  291. b1 = b1.getvalue()
  292. b2 = BytesIO()
  293. fig2.savefig(b2, format='svg')
  294. b2 = b2.getvalue()
  295. for i in range(len(ax.yaxis.get_major_ticks())):
  296. assert f'https://example.com/{i}'.encode('ascii') in b1
  297. assert b1 == b2
  298. def test_svg_default_metadata(monkeypatch):
  299. # Values have been predefined for 'Creator', 'Date', 'Format', and 'Type'.
  300. monkeypatch.setenv('SOURCE_DATE_EPOCH', '19680801')
  301. fig, ax = plt.subplots()
  302. with BytesIO() as fd:
  303. fig.savefig(fd, format='svg')
  304. buf = fd.getvalue().decode()
  305. # Creator
  306. assert mpl.__version__ in buf
  307. # Date
  308. assert '1970-08-16' in buf
  309. # Format
  310. assert 'image/svg+xml' in buf
  311. # Type
  312. assert 'StillImage' in buf
  313. # Now make sure all the default metadata can be cleared.
  314. with BytesIO() as fd:
  315. fig.savefig(fd, format='svg', metadata={'Date': None, 'Creator': None,
  316. 'Format': None, 'Type': None})
  317. buf = fd.getvalue().decode()
  318. # Creator
  319. assert mpl.__version__ not in buf
  320. # Date
  321. assert '1970-08-16' not in buf
  322. # Format
  323. assert 'image/svg+xml' not in buf
  324. # Type
  325. assert 'StillImage' not in buf
  326. def test_svg_clear_default_metadata(monkeypatch):
  327. # Makes sure that setting a default metadata to `None`
  328. # removes the corresponding tag from the metadata.
  329. monkeypatch.setenv('SOURCE_DATE_EPOCH', '19680801')
  330. metadata_contains = {'creator': mpl.__version__, 'date': '1970-08-16',
  331. 'format': 'image/svg+xml', 'type': 'StillImage'}
  332. SVGNS = '{http://www.w3.org/2000/svg}'
  333. RDFNS = '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}'
  334. CCNS = '{http://creativecommons.org/ns#}'
  335. DCNS = '{http://purl.org/dc/elements/1.1/}'
  336. fig, ax = plt.subplots()
  337. for name in metadata_contains:
  338. with BytesIO() as fd:
  339. fig.savefig(fd, format='svg', metadata={name.title(): None})
  340. buf = fd.getvalue().decode()
  341. root = xml.etree.ElementTree.fromstring(buf)
  342. work, = root.findall(f'./{SVGNS}metadata/{RDFNS}RDF/{CCNS}Work')
  343. for key in metadata_contains:
  344. data = work.findall(f'./{DCNS}{key}')
  345. if key == name:
  346. # The one we cleared is not there
  347. assert not data
  348. continue
  349. # Everything else should be there
  350. data, = data
  351. xmlstr = xml.etree.ElementTree.tostring(data, encoding="unicode")
  352. assert metadata_contains[key] in xmlstr
  353. def test_svg_clear_all_metadata():
  354. # Makes sure that setting all default metadata to `None`
  355. # removes the metadata tag from the output.
  356. fig, ax = plt.subplots()
  357. with BytesIO() as fd:
  358. fig.savefig(fd, format='svg', metadata={'Date': None, 'Creator': None,
  359. 'Format': None, 'Type': None})
  360. buf = fd.getvalue().decode()
  361. SVGNS = '{http://www.w3.org/2000/svg}'
  362. root = xml.etree.ElementTree.fromstring(buf)
  363. assert not root.findall(f'./{SVGNS}metadata')
  364. def test_svg_metadata():
  365. single_value = ['Coverage', 'Identifier', 'Language', 'Relation', 'Source',
  366. 'Title', 'Type']
  367. multi_value = ['Contributor', 'Creator', 'Keywords', 'Publisher', 'Rights']
  368. metadata = {
  369. 'Date': [datetime.date(1968, 8, 1),
  370. datetime.datetime(1968, 8, 2, 1, 2, 3)],
  371. 'Description': 'description\ntext',
  372. **{k: f'{k} foo' for k in single_value},
  373. **{k: [f'{k} bar', f'{k} baz'] for k in multi_value},
  374. }
  375. fig = plt.figure()
  376. with BytesIO() as fd:
  377. fig.savefig(fd, format='svg', metadata=metadata)
  378. buf = fd.getvalue().decode()
  379. SVGNS = '{http://www.w3.org/2000/svg}'
  380. RDFNS = '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}'
  381. CCNS = '{http://creativecommons.org/ns#}'
  382. DCNS = '{http://purl.org/dc/elements/1.1/}'
  383. root = xml.etree.ElementTree.fromstring(buf)
  384. rdf, = root.findall(f'./{SVGNS}metadata/{RDFNS}RDF')
  385. # Check things that are single entries.
  386. titles = [node.text for node in root.findall(f'./{SVGNS}title')]
  387. assert titles == [metadata['Title']]
  388. types = [node.attrib[f'{RDFNS}resource']
  389. for node in rdf.findall(f'./{CCNS}Work/{DCNS}type')]
  390. assert types == [metadata['Type']]
  391. for k in ['Description', *single_value]:
  392. if k == 'Type':
  393. continue
  394. values = [node.text
  395. for node in rdf.findall(f'./{CCNS}Work/{DCNS}{k.lower()}')]
  396. assert values == [metadata[k]]
  397. # Check things that are multi-value entries.
  398. for k in multi_value:
  399. if k == 'Keywords':
  400. continue
  401. values = [
  402. node.text
  403. for node in rdf.findall(
  404. f'./{CCNS}Work/{DCNS}{k.lower()}/{CCNS}Agent/{DCNS}title')]
  405. assert values == metadata[k]
  406. # Check special things.
  407. dates = [node.text for node in rdf.findall(f'./{CCNS}Work/{DCNS}date')]
  408. assert dates == ['1968-08-01/1968-08-02T01:02:03']
  409. values = [node.text for node in
  410. rdf.findall(f'./{CCNS}Work/{DCNS}subject/{RDFNS}Bag/{RDFNS}li')]
  411. assert values == metadata['Keywords']
  412. @image_comparison(["multi_font_aspath.svg"], tol=1.8)
  413. def test_multi_font_type3():
  414. fp = fm.FontProperties(family=["WenQuanYi Zen Hei"])
  415. if Path(fm.findfont(fp)).name != "wqy-zenhei.ttc":
  416. pytest.skip("Font may be missing")
  417. plt.rc('font', family=['DejaVu Sans', 'WenQuanYi Zen Hei'], size=27)
  418. plt.rc('svg', fonttype='path')
  419. fig = plt.figure()
  420. fig.text(0.15, 0.475, "There are 几个汉字 in between!")
  421. @image_comparison(["multi_font_astext.svg"])
  422. def test_multi_font_type42():
  423. fp = fm.FontProperties(family=["WenQuanYi Zen Hei"])
  424. if Path(fm.findfont(fp)).name != "wqy-zenhei.ttc":
  425. pytest.skip("Font may be missing")
  426. fig = plt.figure()
  427. plt.rc('svg', fonttype='none')
  428. plt.rc('font', family=['DejaVu Sans', 'WenQuanYi Zen Hei'], size=27)
  429. fig.text(0.15, 0.475, "There are 几个汉字 in between!")
  430. @pytest.mark.parametrize('metadata,error,message', [
  431. ({'Date': 1}, TypeError, "Invalid type for Date metadata. Expected str"),
  432. ({'Date': [1]}, TypeError,
  433. "Invalid type for Date metadata. Expected iterable"),
  434. ({'Keywords': 1}, TypeError,
  435. "Invalid type for Keywords metadata. Expected str"),
  436. ({'Keywords': [1]}, TypeError,
  437. "Invalid type for Keywords metadata. Expected iterable"),
  438. ({'Creator': 1}, TypeError,
  439. "Invalid type for Creator metadata. Expected str"),
  440. ({'Creator': [1]}, TypeError,
  441. "Invalid type for Creator metadata. Expected iterable"),
  442. ({'Title': 1}, TypeError,
  443. "Invalid type for Title metadata. Expected str"),
  444. ({'Format': 1}, TypeError,
  445. "Invalid type for Format metadata. Expected str"),
  446. ({'Foo': 'Bar'}, ValueError, "Unknown metadata key"),
  447. ])
  448. def test_svg_incorrect_metadata(metadata, error, message):
  449. with pytest.raises(error, match=message), BytesIO() as fd:
  450. fig = plt.figure()
  451. fig.savefig(fd, format='svg', metadata=metadata)
  452. def test_svg_escape():
  453. fig = plt.figure()
  454. fig.text(0.5, 0.5, "<\'\"&>", gid="<\'\"&>")
  455. with BytesIO() as fd:
  456. fig.savefig(fd, format='svg')
  457. buf = fd.getvalue().decode()
  458. assert '&lt;&apos;&quot;&amp;&gt;"' in buf
  459. @pytest.mark.parametrize("font_str", [
  460. "'DejaVu Sans', 'WenQuanYi Zen Hei', 'Arial', sans-serif",
  461. "'DejaVu Serif', 'WenQuanYi Zen Hei', 'Times New Roman', serif",
  462. "'Arial', 'WenQuanYi Zen Hei', cursive",
  463. "'Impact', 'WenQuanYi Zen Hei', fantasy",
  464. "'DejaVu Sans Mono', 'WenQuanYi Zen Hei', 'Courier New', monospace",
  465. # These do not work because the logic to get the font metrics will not find
  466. # WenQuanYi as the fallback logic stops with the first fallback font:
  467. # "'DejaVu Sans Mono', 'Courier New', 'WenQuanYi Zen Hei', monospace",
  468. # "'DejaVu Sans', 'Arial', 'WenQuanYi Zen Hei', sans-serif",
  469. # "'DejaVu Serif', 'Times New Roman', 'WenQuanYi Zen Hei', serif",
  470. ])
  471. @pytest.mark.parametrize("include_generic", [True, False])
  472. def test_svg_font_string(font_str, include_generic):
  473. fp = fm.FontProperties(family=["WenQuanYi Zen Hei"])
  474. if Path(fm.findfont(fp)).name != "wqy-zenhei.ttc":
  475. pytest.skip("Font may be missing")
  476. explicit, *rest, generic = map(
  477. lambda x: x.strip("'"), font_str.split(", ")
  478. )
  479. size = len(generic)
  480. if include_generic:
  481. rest = rest + [generic]
  482. plt.rcParams[f"font.{generic}"] = rest
  483. plt.rcParams["font.size"] = size
  484. plt.rcParams["svg.fonttype"] = "none"
  485. fig, ax = plt.subplots()
  486. if generic == "sans-serif":
  487. generic_options = ["sans", "sans-serif", "sans serif"]
  488. else:
  489. generic_options = [generic]
  490. for generic_name in generic_options:
  491. # test that fallback works
  492. ax.text(0.5, 0.5, "There are 几个汉字 in between!",
  493. family=[explicit, generic_name], ha="center")
  494. # test deduplication works
  495. ax.text(0.5, 0.1, "There are 几个汉字 in between!",
  496. family=[explicit, *rest, generic_name], ha="center")
  497. ax.axis("off")
  498. with BytesIO() as fd:
  499. fig.savefig(fd, format="svg")
  500. buf = fd.getvalue()
  501. tree = xml.etree.ElementTree.fromstring(buf)
  502. ns = "http://www.w3.org/2000/svg"
  503. text_count = 0
  504. for text_element in tree.findall(f".//{{{ns}}}text"):
  505. text_count += 1
  506. font_style = dict(
  507. map(lambda x: x.strip(), _.strip().split(":"))
  508. for _ in dict(text_element.items())["style"].split(";")
  509. )
  510. assert font_style["font-size"] == f"{size}px"
  511. assert font_style["font-family"] == font_str
  512. assert text_count == len(ax.texts)
  513. def test_annotationbbox_gid():
  514. # Test that object gid appears in the AnnotationBbox
  515. # in output svg.
  516. fig = plt.figure()
  517. ax = fig.add_subplot()
  518. arr_img = np.ones((32, 32))
  519. xy = (0.3, 0.55)
  520. imagebox = OffsetImage(arr_img, zoom=0.1)
  521. imagebox.image.axes = ax
  522. ab = AnnotationBbox(imagebox, xy,
  523. xybox=(120., -80.),
  524. xycoords='data',
  525. boxcoords="offset points",
  526. pad=0.5,
  527. arrowprops=dict(
  528. arrowstyle="->",
  529. connectionstyle="angle,angleA=0,angleB=90,rad=3")
  530. )
  531. ab.set_gid("a test for issue 20044")
  532. ax.add_artist(ab)
  533. with BytesIO() as fd:
  534. fig.savefig(fd, format='svg')
  535. buf = fd.getvalue().decode('utf-8')
  536. expected = '<g id="a test for issue 20044">'
  537. assert expected in buf
  538. def test_svgid():
  539. """Test that `svg.id` rcparam appears in output svg if not None."""
  540. fig, ax = plt.subplots()
  541. ax.plot([1, 2, 3], [3, 2, 1])
  542. fig.canvas.draw()
  543. # Default: svg.id = None
  544. with BytesIO() as fd:
  545. fig.savefig(fd, format='svg')
  546. buf = fd.getvalue().decode()
  547. tree = xml.etree.ElementTree.fromstring(buf)
  548. assert plt.rcParams['svg.id'] is None
  549. assert not tree.findall('.[@id]')
  550. # String: svg.id = str
  551. svg_id = 'a test for issue 28535'
  552. plt.rc('svg', id=svg_id)
  553. with BytesIO() as fd:
  554. fig.savefig(fd, format='svg')
  555. buf = fd.getvalue().decode()
  556. tree = xml.etree.ElementTree.fromstring(buf)
  557. assert plt.rcParams['svg.id'] == svg_id
  558. assert tree.findall(f'.[@id="{svg_id}"]')