test_lines.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. """
  2. Tests specific to the lines module.
  3. """
  4. import itertools
  5. import timeit
  6. from cycler import cycler
  7. import numpy as np
  8. from numpy.testing import assert_array_equal
  9. import pytest
  10. import matplotlib
  11. import matplotlib.lines as mlines
  12. from matplotlib.markers import MarkerStyle
  13. from matplotlib.path import Path
  14. import matplotlib.pyplot as plt
  15. from matplotlib.testing.decorators import image_comparison, check_figures_equal
  16. def test_segment_hits():
  17. """Test a problematic case."""
  18. cx, cy = 553, 902
  19. x, y = np.array([553., 553.]), np.array([95., 947.])
  20. radius = 6.94
  21. assert_array_equal(mlines.segment_hits(cx, cy, x, y, radius), [0])
  22. # Runtimes on a loaded system are inherently flaky. Not so much that a rerun
  23. # won't help, hopefully.
  24. @pytest.mark.flaky(reruns=3)
  25. def test_invisible_Line_rendering():
  26. """
  27. GitHub issue #1256 identified a bug in Line.draw method
  28. Despite visibility attribute set to False, the draw method was not
  29. returning early enough and some pre-rendering code was executed
  30. though not necessary.
  31. Consequence was an excessive draw time for invisible Line instances
  32. holding a large number of points (Npts> 10**6)
  33. """
  34. # Creates big x and y data:
  35. N = 10**7
  36. x = np.linspace(0, 1, N)
  37. y = np.random.normal(size=N)
  38. # Create a plot figure:
  39. fig = plt.figure()
  40. ax = plt.subplot(111)
  41. # Create a "big" Line instance:
  42. l = mlines.Line2D(x, y)
  43. l.set_visible(False)
  44. # but don't add it to the Axis instance `ax`
  45. # [here Interactive panning and zooming is pretty responsive]
  46. # Time the canvas drawing:
  47. t_no_line = min(timeit.repeat(fig.canvas.draw, number=1, repeat=3))
  48. # (gives about 25 ms)
  49. # Add the big invisible Line:
  50. ax.add_line(l)
  51. # [Now interactive panning and zooming is very slow]
  52. # Time the canvas drawing:
  53. t_invisible_line = min(timeit.repeat(fig.canvas.draw, number=1, repeat=3))
  54. # gives about 290 ms for N = 10**7 pts
  55. slowdown_factor = t_invisible_line / t_no_line
  56. slowdown_threshold = 2 # trying to avoid false positive failures
  57. assert slowdown_factor < slowdown_threshold
  58. def test_set_line_coll_dash():
  59. fig = plt.figure()
  60. ax = fig.add_subplot(1, 1, 1)
  61. np.random.seed(0)
  62. # Testing setting linestyles for line collections.
  63. # This should not produce an error.
  64. ax.contour(np.random.randn(20, 30), linestyles=[(0, (3, 3))])
  65. @image_comparison(['line_dashes'], remove_text=True)
  66. def test_line_dashes():
  67. fig = plt.figure()
  68. ax = fig.add_subplot(1, 1, 1)
  69. ax.plot(range(10), linestyle=(0, (3, 3)), lw=5)
  70. def test_line_colors():
  71. fig = plt.figure()
  72. ax = fig.add_subplot(1, 1, 1)
  73. ax.plot(range(10), color='none')
  74. ax.plot(range(10), color='r')
  75. ax.plot(range(10), color='.3')
  76. ax.plot(range(10), color=(1, 0, 0, 1))
  77. ax.plot(range(10), color=(1, 0, 0))
  78. fig.canvas.draw()
  79. def test_linestyle_variants():
  80. fig = plt.figure()
  81. ax = fig.add_subplot(1, 1, 1)
  82. for ls in ["-", "solid", "--", "dashed",
  83. "-.", "dashdot", ":", "dotted"]:
  84. ax.plot(range(10), linestyle=ls)
  85. fig.canvas.draw()
  86. def test_valid_linestyles():
  87. line = mlines.Line2D([], [])
  88. with pytest.raises(ValueError):
  89. line.set_linestyle('aardvark')
  90. @image_comparison(['drawstyle_variants.png'], remove_text=True)
  91. def test_drawstyle_variants():
  92. fig, axs = plt.subplots(6)
  93. dss = ["default", "steps-mid", "steps-pre", "steps-post", "steps", None]
  94. # We want to check that drawstyles are properly handled even for very long
  95. # lines (for which the subslice optimization is on); however, we need
  96. # to zoom in so that the difference between the drawstyles is actually
  97. # visible.
  98. for ax, ds in zip(axs.flat, dss):
  99. ax.plot(range(2000), drawstyle=ds)
  100. ax.set(xlim=(0, 2), ylim=(0, 2))
  101. def test_valid_drawstyles():
  102. line = mlines.Line2D([], [])
  103. with pytest.raises(ValueError):
  104. line.set_drawstyle('foobar')
  105. def test_set_drawstyle():
  106. x = np.linspace(0, 2*np.pi, 10)
  107. y = np.sin(x)
  108. fig, ax = plt.subplots()
  109. line, = ax.plot(x, y)
  110. line.set_drawstyle("steps-pre")
  111. assert len(line.get_path().vertices) == 2*len(x)-1
  112. line.set_drawstyle("default")
  113. assert len(line.get_path().vertices) == len(x)
  114. @image_comparison(['line_collection_dashes'], remove_text=True, style='mpl20')
  115. def test_set_line_coll_dash_image():
  116. fig = plt.figure()
  117. ax = fig.add_subplot(1, 1, 1)
  118. np.random.seed(0)
  119. ax.contour(np.random.randn(20, 30), linestyles=[(0, (3, 3))])
  120. @image_comparison(['marker_fill_styles.png'], remove_text=True)
  121. def test_marker_fill_styles():
  122. colors = itertools.cycle([[0, 0, 1], 'g', '#ff0000', 'c', 'm', 'y',
  123. np.array([0, 0, 0])])
  124. altcolor = 'lightgreen'
  125. y = np.array([1, 1])
  126. x = np.array([0, 9])
  127. fig, ax = plt.subplots()
  128. for j, marker in enumerate(mlines.Line2D.filled_markers):
  129. for i, fs in enumerate(mlines.Line2D.fillStyles):
  130. color = next(colors)
  131. ax.plot(j * 10 + x, y + i + .5 * (j % 2),
  132. marker=marker,
  133. markersize=20,
  134. markerfacecoloralt=altcolor,
  135. fillstyle=fs,
  136. label=fs,
  137. linewidth=5,
  138. color=color,
  139. markeredgecolor=color,
  140. markeredgewidth=2)
  141. ax.set_ylim([0, 7.5])
  142. ax.set_xlim([-5, 155])
  143. def test_markerfacecolor_fillstyle():
  144. """Test that markerfacecolor does not override fillstyle='none'."""
  145. l, = plt.plot([1, 3, 2], marker=MarkerStyle('o', fillstyle='none'),
  146. markerfacecolor='red')
  147. assert l.get_fillstyle() == 'none'
  148. assert l.get_markerfacecolor() == 'none'
  149. @image_comparison(['scaled_lines'], style='default')
  150. def test_lw_scaling():
  151. th = np.linspace(0, 32)
  152. fig, ax = plt.subplots()
  153. lins_styles = ['dashed', 'dotted', 'dashdot']
  154. cy = cycler(matplotlib.rcParams['axes.prop_cycle'])
  155. for j, (ls, sty) in enumerate(zip(lins_styles, cy)):
  156. for lw in np.linspace(.5, 10, 10):
  157. ax.plot(th, j*np.ones(50) + .1 * lw, linestyle=ls, lw=lw, **sty)
  158. def test_nan_is_sorted():
  159. line = mlines.Line2D([], [])
  160. assert line._is_sorted(np.array([1, 2, 3]))
  161. assert line._is_sorted(np.array([1, np.nan, 3]))
  162. assert not line._is_sorted([3, 5] + [np.nan] * 100 + [0, 2])
  163. @check_figures_equal()
  164. def test_step_markers(fig_test, fig_ref):
  165. fig_test.subplots().step([0, 1], "-o")
  166. fig_ref.subplots().plot([0, 0, 1], [0, 1, 1], "-o", markevery=[0, 2])
  167. @check_figures_equal(extensions=('png',))
  168. def test_markevery(fig_test, fig_ref):
  169. np.random.seed(42)
  170. t = np.linspace(0, 3, 14)
  171. y = np.random.rand(len(t))
  172. casesA = [None, 4, (2, 5), [1, 5, 11],
  173. [0, -1], slice(5, 10, 2), 0.3, (0.3, 0.4),
  174. np.arange(len(t))[y > 0.5]]
  175. casesB = ["11111111111111", "10001000100010", "00100001000010",
  176. "01000100000100", "10000000000001", "00000101010000",
  177. "11011011011110", "01010011011101", "01110001110110"]
  178. axsA = fig_ref.subplots(3, 3)
  179. axsB = fig_test.subplots(3, 3)
  180. for ax, case in zip(axsA.flat, casesA):
  181. ax.plot(t, y, "-gD", markevery=case)
  182. for ax, case in zip(axsB.flat, casesB):
  183. me = np.array(list(case)).astype(int).astype(bool)
  184. ax.plot(t, y, "-gD", markevery=me)
  185. def test_marker_as_markerstyle():
  186. fig, ax = plt.subplots()
  187. line, = ax.plot([2, 4, 3], marker=MarkerStyle("D"))
  188. fig.canvas.draw()
  189. assert line.get_marker() == "D"
  190. # continue with smoke tests:
  191. line.set_marker("s")
  192. fig.canvas.draw()
  193. line.set_marker(MarkerStyle("o"))
  194. fig.canvas.draw()
  195. # test Path roundtrip
  196. triangle1 = Path([[-1., -1.], [1., -1.], [0., 2.], [0., 0.]], closed=True)
  197. line2, = ax.plot([1, 3, 2], marker=MarkerStyle(triangle1), ms=22)
  198. line3, = ax.plot([0, 2, 1], marker=triangle1, ms=22)
  199. assert_array_equal(line2.get_marker().vertices, triangle1.vertices)
  200. assert_array_equal(line3.get_marker().vertices, triangle1.vertices)
  201. @check_figures_equal()
  202. def test_odd_dashes(fig_test, fig_ref):
  203. fig_test.add_subplot().plot([1, 2], dashes=[1, 2, 3])
  204. fig_ref.add_subplot().plot([1, 2], dashes=[1, 2, 3, 1, 2, 3])