1
0

test_backend_svg.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. import numpy as np
  2. from io import BytesIO
  3. import re
  4. import tempfile
  5. import xml.parsers.expat
  6. import pytest
  7. import matplotlib as mpl
  8. from matplotlib import dviread
  9. from matplotlib.figure import Figure
  10. import matplotlib.pyplot as plt
  11. from matplotlib.testing.decorators import image_comparison
  12. needs_usetex = pytest.mark.skipif(
  13. not mpl.checkdep_usetex(True),
  14. reason="This test needs a TeX installation")
  15. def test_visibility():
  16. fig, ax = plt.subplots()
  17. x = np.linspace(0, 4 * np.pi, 50)
  18. y = np.sin(x)
  19. yerr = np.ones_like(y)
  20. a, b, c = ax.errorbar(x, y, yerr=yerr, fmt='ko')
  21. for artist in b:
  22. artist.set_visible(False)
  23. fd = BytesIO()
  24. fig.savefig(fd, format='svg')
  25. fd.seek(0)
  26. buf = fd.read()
  27. fd.close()
  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 = plt.figure()
  33. ax = fig.add_subplot(1, 1, 1)
  34. ax.scatter(x=[0, 0.1, 1], y=[0, 0, 0], c='k', alpha=0.1, s=10000)
  35. @image_comparison(['noscale'], remove_text=True)
  36. def test_noscale():
  37. X, Y = np.meshgrid(np.arange(-5, 5, 1), np.arange(-5, 5, 1))
  38. Z = np.sin(Y ** 2)
  39. fig = plt.figure()
  40. ax = fig.add_subplot(1, 1, 1)
  41. ax.imshow(Z, cmap='gray', interpolation='none')
  42. def test_text_urls():
  43. fig = plt.figure()
  44. test_url = "http://test_text_urls.matplotlib.org"
  45. fig.suptitle("test_text_urls", url=test_url)
  46. fd = BytesIO()
  47. fig.savefig(fd, format='svg')
  48. fd.seek(0)
  49. buf = fd.read().decode()
  50. fd.close()
  51. expected = '<a xlink:href="{0}">'.format(test_url)
  52. assert expected in buf
  53. @image_comparison(['bold_font_output.svg'])
  54. def test_bold_font_output():
  55. fig = plt.figure()
  56. ax = fig.add_subplot(1, 1, 1)
  57. ax.plot(np.arange(10), np.arange(10))
  58. ax.set_xlabel('nonbold-xlabel')
  59. ax.set_ylabel('bold-ylabel', fontweight='bold')
  60. ax.set_title('bold-title', fontweight='bold')
  61. @image_comparison(['bold_font_output_with_none_fonttype.svg'])
  62. def test_bold_font_output_with_none_fonttype():
  63. plt.rcParams['svg.fonttype'] = 'none'
  64. fig = plt.figure()
  65. ax = fig.add_subplot(1, 1, 1)
  66. ax.plot(np.arange(10), np.arange(10))
  67. ax.set_xlabel('nonbold-xlabel')
  68. ax.set_ylabel('bold-ylabel', fontweight='bold')
  69. ax.set_title('bold-title', fontweight='bold')
  70. @needs_usetex
  71. def test_missing_psfont(monkeypatch):
  72. """An error is raised if a TeX font lacks a Type-1 equivalent"""
  73. def psfont(*args, **kwargs):
  74. return dviread.PsFont(texname='texfont', psname='Some Font',
  75. effects=None, encoding=None, filename=None)
  76. monkeypatch.setattr(dviread.PsfontsMap, '__getitem__', psfont)
  77. mpl.rc('text', usetex=True)
  78. fig, ax = plt.subplots()
  79. ax.text(0.5, 0.5, 'hello')
  80. with tempfile.TemporaryFile() as tmpfile, pytest.raises(ValueError):
  81. fig.savefig(tmpfile, format='svg')
  82. # Use Computer Modern Sans Serif, not Helvetica (which has no \textwon).
  83. @pytest.mark.style('default')
  84. @needs_usetex
  85. def test_unicode_won():
  86. fig = Figure()
  87. fig.text(.5, .5, r'\textwon', usetex=True)
  88. with BytesIO() as fd:
  89. fig.savefig(fd, format='svg')
  90. buf = fd.getvalue().decode('ascii')
  91. won_id = 'Computer_Modern_Sans_Serif-142'
  92. assert re.search(r'<path d=(.|\s)*?id="{0}"/>'.format(won_id), buf)
  93. assert re.search(r'<use[^/>]*? xlink:href="#{0}"/>'.format(won_id), buf)
  94. def test_svgnone_with_data_coordinates():
  95. plt.rcParams['svg.fonttype'] = 'none'
  96. expected = 'Unlikely to appear by chance'
  97. fig, ax = plt.subplots()
  98. ax.text(np.datetime64('2019-06-30'), 1, expected)
  99. ax.set_xlim(np.datetime64('2019-01-01'), np.datetime64('2019-12-31'))
  100. ax.set_ylim(0, 2)
  101. with BytesIO() as fd:
  102. fig.savefig(fd, format='svg')
  103. fd.seek(0)
  104. buf = fd.read().decode()
  105. assert expected in buf
  106. def test_gid():
  107. """Test that object gid appears in output svg."""
  108. from matplotlib.offsetbox import OffsetBox
  109. from matplotlib.axis import Tick
  110. fig = plt.figure()
  111. ax1 = fig.add_subplot(131)
  112. ax1.imshow([[1., 2.], [2., 3.]], aspect="auto")
  113. ax1.scatter([1, 2, 3], [1, 2, 3], label="myscatter")
  114. ax1.plot([2, 3, 1], label="myplot")
  115. ax1.legend()
  116. ax1a = ax1.twinx()
  117. ax1a.bar([1, 2, 3], [1, 2, 3])
  118. ax2 = fig.add_subplot(132, projection="polar")
  119. ax2.plot([0, 1.5, 3], [1, 2, 3])
  120. ax3 = fig.add_subplot(133, projection="3d")
  121. ax3.plot([1, 2], [1, 2], [1, 2])
  122. fig.canvas.draw()
  123. gdic = {}
  124. for idx, obj in enumerate(fig.findobj(include_self=True)):
  125. if obj.get_visible():
  126. gid = f"test123{obj.__class__.__name__}_{idx}"
  127. gdic[gid] = obj
  128. obj.set_gid(gid)
  129. fd = BytesIO()
  130. fig.savefig(fd, format='svg')
  131. fd.seek(0)
  132. buf = fd.read().decode()
  133. fd.close()
  134. def include(gid, obj):
  135. # we need to exclude certain objects which will not appear in the svg
  136. if isinstance(obj, OffsetBox):
  137. return False
  138. if isinstance(obj, plt.Text):
  139. if obj.get_text() == "":
  140. return False
  141. elif obj.axes is None:
  142. return False
  143. if isinstance(obj, plt.Line2D):
  144. if np.array(obj.get_data()).shape == (2, 1):
  145. return False
  146. elif not hasattr(obj, "axes") or obj.axes is None:
  147. return False
  148. if isinstance(obj, Tick):
  149. loc = obj.get_loc()
  150. if loc == 0:
  151. return False
  152. vi = obj.get_view_interval()
  153. if loc < min(vi) or loc > max(vi):
  154. return False
  155. return True
  156. for gid, obj in gdic.items():
  157. if include(gid, obj):
  158. assert gid in buf