test_lines.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. """
  2. Tests specific to the lines module.
  3. """
  4. import itertools
  5. import platform
  6. import timeit
  7. from types import SimpleNamespace
  8. from cycler import cycler
  9. import numpy as np
  10. from numpy.testing import assert_array_equal
  11. import pytest
  12. import matplotlib
  13. import matplotlib as mpl
  14. from matplotlib import _path
  15. import matplotlib.lines as mlines
  16. from matplotlib.markers import MarkerStyle
  17. from matplotlib.path import Path
  18. import matplotlib.pyplot as plt
  19. import matplotlib.transforms as mtransforms
  20. from matplotlib.testing.decorators import image_comparison, check_figures_equal
  21. def test_segment_hits():
  22. """Test a problematic case."""
  23. cx, cy = 553, 902
  24. x, y = np.array([553., 553.]), np.array([95., 947.])
  25. radius = 6.94
  26. assert_array_equal(mlines.segment_hits(cx, cy, x, y, radius), [0])
  27. # Runtimes on a loaded system are inherently flaky. Not so much that a rerun
  28. # won't help, hopefully.
  29. @pytest.mark.flaky(reruns=3)
  30. def test_invisible_Line_rendering():
  31. """
  32. GitHub issue #1256 identified a bug in Line.draw method
  33. Despite visibility attribute set to False, the draw method was not
  34. returning early enough and some pre-rendering code was executed
  35. though not necessary.
  36. Consequence was an excessive draw time for invisible Line instances
  37. holding a large number of points (Npts> 10**6)
  38. """
  39. # Creates big x and y data:
  40. N = 10**7
  41. x = np.linspace(0, 1, N)
  42. y = np.random.normal(size=N)
  43. # Create a plot figure:
  44. fig = plt.figure()
  45. ax = plt.subplot()
  46. # Create a "big" Line instance:
  47. l = mlines.Line2D(x, y)
  48. l.set_visible(False)
  49. # but don't add it to the Axis instance `ax`
  50. # [here Interactive panning and zooming is pretty responsive]
  51. # Time the canvas drawing:
  52. t_no_line = min(timeit.repeat(fig.canvas.draw, number=1, repeat=3))
  53. # (gives about 25 ms)
  54. # Add the big invisible Line:
  55. ax.add_line(l)
  56. # [Now interactive panning and zooming is very slow]
  57. # Time the canvas drawing:
  58. t_invisible_line = min(timeit.repeat(fig.canvas.draw, number=1, repeat=3))
  59. # gives about 290 ms for N = 10**7 pts
  60. slowdown_factor = t_invisible_line / t_no_line
  61. slowdown_threshold = 2 # trying to avoid false positive failures
  62. assert slowdown_factor < slowdown_threshold
  63. def test_set_line_coll_dash():
  64. fig, ax = plt.subplots()
  65. np.random.seed(0)
  66. # Testing setting linestyles for line collections.
  67. # This should not produce an error.
  68. ax.contour(np.random.randn(20, 30), linestyles=[(0, (3, 3))])
  69. def test_invalid_line_data():
  70. with pytest.raises(RuntimeError, match='xdata must be'):
  71. mlines.Line2D(0, [])
  72. with pytest.raises(RuntimeError, match='ydata must be'):
  73. mlines.Line2D([], 1)
  74. line = mlines.Line2D([], [])
  75. # when deprecation cycle is completed
  76. # with pytest.raises(RuntimeError, match='x must be'):
  77. with pytest.warns(mpl.MatplotlibDeprecationWarning):
  78. line.set_xdata(0)
  79. # with pytest.raises(RuntimeError, match='y must be'):
  80. with pytest.warns(mpl.MatplotlibDeprecationWarning):
  81. line.set_ydata(0)
  82. @image_comparison(['line_dashes'], remove_text=True, tol=0.002)
  83. def test_line_dashes():
  84. # Tolerance introduced after reordering of floating-point operations
  85. # Remove when regenerating the images
  86. fig, ax = plt.subplots()
  87. ax.plot(range(10), linestyle=(0, (3, 3)), lw=5)
  88. def test_line_colors():
  89. fig, ax = plt.subplots()
  90. ax.plot(range(10), color='none')
  91. ax.plot(range(10), color='r')
  92. ax.plot(range(10), color='.3')
  93. ax.plot(range(10), color=(1, 0, 0, 1))
  94. ax.plot(range(10), color=(1, 0, 0))
  95. fig.canvas.draw()
  96. def test_valid_colors():
  97. line = mlines.Line2D([], [])
  98. with pytest.raises(ValueError):
  99. line.set_color("foobar")
  100. def test_linestyle_variants():
  101. fig, ax = plt.subplots()
  102. for ls in ["-", "solid", "--", "dashed",
  103. "-.", "dashdot", ":", "dotted",
  104. (0, None), (0, ()), (0, []), # gh-22930
  105. ]:
  106. ax.plot(range(10), linestyle=ls)
  107. fig.canvas.draw()
  108. def test_valid_linestyles():
  109. line = mlines.Line2D([], [])
  110. with pytest.raises(ValueError):
  111. line.set_linestyle('aardvark')
  112. @image_comparison(['drawstyle_variants.png'], remove_text=True)
  113. def test_drawstyle_variants():
  114. fig, axs = plt.subplots(6)
  115. dss = ["default", "steps-mid", "steps-pre", "steps-post", "steps", None]
  116. # We want to check that drawstyles are properly handled even for very long
  117. # lines (for which the subslice optimization is on); however, we need
  118. # to zoom in so that the difference between the drawstyles is actually
  119. # visible.
  120. for ax, ds in zip(axs.flat, dss):
  121. ax.plot(range(2000), drawstyle=ds)
  122. ax.set(xlim=(0, 2), ylim=(0, 2))
  123. @check_figures_equal(extensions=('png',))
  124. def test_no_subslice_with_transform(fig_ref, fig_test):
  125. ax = fig_ref.add_subplot()
  126. x = np.arange(2000)
  127. ax.plot(x + 2000, x)
  128. ax = fig_test.add_subplot()
  129. t = mtransforms.Affine2D().translate(2000.0, 0.0)
  130. ax.plot(x, x, transform=t+ax.transData)
  131. def test_valid_drawstyles():
  132. line = mlines.Line2D([], [])
  133. with pytest.raises(ValueError):
  134. line.set_drawstyle('foobar')
  135. def test_set_drawstyle():
  136. x = np.linspace(0, 2*np.pi, 10)
  137. y = np.sin(x)
  138. fig, ax = plt.subplots()
  139. line, = ax.plot(x, y)
  140. line.set_drawstyle("steps-pre")
  141. assert len(line.get_path().vertices) == 2*len(x)-1
  142. line.set_drawstyle("default")
  143. assert len(line.get_path().vertices) == len(x)
  144. @image_comparison(
  145. ['line_collection_dashes'], remove_text=True, style='mpl20',
  146. tol=0.65 if platform.machine() in ('aarch64', 'ppc64le', 's390x') else 0)
  147. def test_set_line_coll_dash_image():
  148. fig, ax = plt.subplots()
  149. np.random.seed(0)
  150. ax.contour(np.random.randn(20, 30), linestyles=[(0, (3, 3))])
  151. @image_comparison(['marker_fill_styles.png'], remove_text=True)
  152. def test_marker_fill_styles():
  153. colors = itertools.cycle([[0, 0, 1], 'g', '#ff0000', 'c', 'm', 'y',
  154. np.array([0, 0, 0])])
  155. altcolor = 'lightgreen'
  156. y = np.array([1, 1])
  157. x = np.array([0, 9])
  158. fig, ax = plt.subplots()
  159. # This hard-coded list of markers correspond to an earlier iteration of
  160. # MarkerStyle.filled_markers; the value of that attribute has changed but
  161. # we kept the old value here to not regenerate the baseline image.
  162. # Replace with mlines.Line2D.filled_markers when the image is regenerated.
  163. for j, marker in enumerate("ov^<>8sp*hHDdPX"):
  164. for i, fs in enumerate(mlines.Line2D.fillStyles):
  165. color = next(colors)
  166. ax.plot(j * 10 + x, y + i + .5 * (j % 2),
  167. marker=marker,
  168. markersize=20,
  169. markerfacecoloralt=altcolor,
  170. fillstyle=fs,
  171. label=fs,
  172. linewidth=5,
  173. color=color,
  174. markeredgecolor=color,
  175. markeredgewidth=2)
  176. ax.set_ylim([0, 7.5])
  177. ax.set_xlim([-5, 155])
  178. def test_markerfacecolor_fillstyle():
  179. """Test that markerfacecolor does not override fillstyle='none'."""
  180. l, = plt.plot([1, 3, 2], marker=MarkerStyle('o', fillstyle='none'),
  181. markerfacecolor='red')
  182. assert l.get_fillstyle() == 'none'
  183. assert l.get_markerfacecolor() == 'none'
  184. @image_comparison(['scaled_lines'], style='default')
  185. def test_lw_scaling():
  186. th = np.linspace(0, 32)
  187. fig, ax = plt.subplots()
  188. lins_styles = ['dashed', 'dotted', 'dashdot']
  189. cy = cycler(matplotlib.rcParams['axes.prop_cycle'])
  190. for j, (ls, sty) in enumerate(zip(lins_styles, cy)):
  191. for lw in np.linspace(.5, 10, 10):
  192. ax.plot(th, j*np.ones(50) + .1 * lw, linestyle=ls, lw=lw, **sty)
  193. def test_is_sorted_and_has_non_nan():
  194. assert _path.is_sorted_and_has_non_nan(np.array([1, 2, 3]))
  195. assert _path.is_sorted_and_has_non_nan(np.array([1, np.nan, 3]))
  196. assert not _path.is_sorted_and_has_non_nan([3, 5] + [np.nan] * 100 + [0, 2])
  197. n = 2 * mlines.Line2D._subslice_optim_min_size
  198. plt.plot([np.nan] * n, range(n))
  199. @check_figures_equal()
  200. def test_step_markers(fig_test, fig_ref):
  201. fig_test.subplots().step([0, 1], "-o")
  202. fig_ref.subplots().plot([0, 0, 1], [0, 1, 1], "-o", markevery=[0, 2])
  203. @pytest.mark.parametrize("parent", ["figure", "axes"])
  204. @check_figures_equal(extensions=('png',))
  205. def test_markevery(fig_test, fig_ref, parent):
  206. np.random.seed(42)
  207. x = np.linspace(0, 1, 14)
  208. y = np.random.rand(len(x))
  209. cases_test = [None, 4, (2, 5), [1, 5, 11],
  210. [0, -1], slice(5, 10, 2),
  211. np.arange(len(x))[y > 0.5],
  212. 0.3, (0.3, 0.4)]
  213. cases_ref = ["11111111111111", "10001000100010", "00100001000010",
  214. "01000100000100", "10000000000001", "00000101010000",
  215. "01110001110110", "11011011011110", "01010011011101"]
  216. if parent == "figure":
  217. # float markevery ("relative to axes size") is not supported.
  218. cases_test = cases_test[:-2]
  219. cases_ref = cases_ref[:-2]
  220. def add_test(x, y, *, markevery):
  221. fig_test.add_artist(
  222. mlines.Line2D(x, y, marker="o", markevery=markevery))
  223. def add_ref(x, y, *, markevery):
  224. fig_ref.add_artist(
  225. mlines.Line2D(x, y, marker="o", markevery=markevery))
  226. elif parent == "axes":
  227. axs_test = iter(fig_test.subplots(3, 3).flat)
  228. axs_ref = iter(fig_ref.subplots(3, 3).flat)
  229. def add_test(x, y, *, markevery):
  230. next(axs_test).plot(x, y, "-gD", markevery=markevery)
  231. def add_ref(x, y, *, markevery):
  232. next(axs_ref).plot(x, y, "-gD", markevery=markevery)
  233. for case in cases_test:
  234. add_test(x, y, markevery=case)
  235. for case in cases_ref:
  236. me = np.array(list(case)).astype(int).astype(bool)
  237. add_ref(x, y, markevery=me)
  238. def test_markevery_figure_line_unsupported_relsize():
  239. fig = plt.figure()
  240. fig.add_artist(mlines.Line2D([0, 1], [0, 1], marker="o", markevery=.5))
  241. with pytest.raises(ValueError):
  242. fig.canvas.draw()
  243. def test_marker_as_markerstyle():
  244. fig, ax = plt.subplots()
  245. line, = ax.plot([2, 4, 3], marker=MarkerStyle("D"))
  246. fig.canvas.draw()
  247. assert line.get_marker() == "D"
  248. # continue with smoke tests:
  249. line.set_marker("s")
  250. fig.canvas.draw()
  251. line.set_marker(MarkerStyle("o"))
  252. fig.canvas.draw()
  253. # test Path roundtrip
  254. triangle1 = Path._create_closed([[-1, -1], [1, -1], [0, 2]])
  255. line2, = ax.plot([1, 3, 2], marker=MarkerStyle(triangle1), ms=22)
  256. line3, = ax.plot([0, 2, 1], marker=triangle1, ms=22)
  257. assert_array_equal(line2.get_marker().vertices, triangle1.vertices)
  258. assert_array_equal(line3.get_marker().vertices, triangle1.vertices)
  259. @image_comparison(['striped_line.png'], remove_text=True, style='mpl20')
  260. def test_striped_lines():
  261. rng = np.random.default_rng(19680801)
  262. _, ax = plt.subplots()
  263. ax.plot(rng.uniform(size=12), color='orange', gapcolor='blue',
  264. linestyle='--', lw=5, label=' ')
  265. ax.plot(rng.uniform(size=12), color='red', gapcolor='black',
  266. linestyle=(0, (2, 5, 4, 2)), lw=5, label=' ', alpha=0.5)
  267. ax.legend(handlelength=5)
  268. @check_figures_equal()
  269. def test_odd_dashes(fig_test, fig_ref):
  270. fig_test.add_subplot().plot([1, 2], dashes=[1, 2, 3])
  271. fig_ref.add_subplot().plot([1, 2], dashes=[1, 2, 3, 1, 2, 3])
  272. def test_picking():
  273. fig, ax = plt.subplots()
  274. mouse_event = SimpleNamespace(x=fig.bbox.width // 2,
  275. y=fig.bbox.height // 2 + 15)
  276. # Default pickradius is 5, so event should not pick this line.
  277. l0, = ax.plot([0, 1], [0, 1], picker=True)
  278. found, indices = l0.contains(mouse_event)
  279. assert not found
  280. # But with a larger pickradius, this should be picked.
  281. l1, = ax.plot([0, 1], [0, 1], picker=True, pickradius=20)
  282. found, indices = l1.contains(mouse_event)
  283. assert found
  284. assert_array_equal(indices['ind'], [0])
  285. # And if we modify the pickradius after creation, it should work as well.
  286. l2, = ax.plot([0, 1], [0, 1], picker=True)
  287. found, indices = l2.contains(mouse_event)
  288. assert not found
  289. l2.set_pickradius(20)
  290. found, indices = l2.contains(mouse_event)
  291. assert found
  292. assert_array_equal(indices['ind'], [0])
  293. @check_figures_equal()
  294. def test_input_copy(fig_test, fig_ref):
  295. t = np.arange(0, 6, 2)
  296. l, = fig_test.add_subplot().plot(t, t, ".-")
  297. t[:] = range(3)
  298. # Trigger cache invalidation
  299. l.set_drawstyle("steps")
  300. fig_ref.add_subplot().plot([0, 2, 4], [0, 2, 4], ".-", drawstyle="steps")
  301. @check_figures_equal(extensions=["png"])
  302. def test_markevery_prop_cycle(fig_test, fig_ref):
  303. """Test that we can set markevery prop_cycle."""
  304. cases = [None, 8, (30, 8), [16, 24, 30], [0, -1],
  305. slice(100, 200, 3), 0.1, 0.3, 1.5,
  306. (0.0, 0.1), (0.45, 0.1)]
  307. cmap = mpl.colormaps['jet']
  308. colors = cmap(np.linspace(0.2, 0.8, len(cases)))
  309. x = np.linspace(-1, 1)
  310. y = 5 * x**2
  311. axs = fig_ref.add_subplot()
  312. for i, markevery in enumerate(cases):
  313. axs.plot(y - i, 'o-', markevery=markevery, color=colors[i])
  314. matplotlib.rcParams['axes.prop_cycle'] = cycler(markevery=cases,
  315. color=colors)
  316. ax = fig_test.add_subplot()
  317. for i, _ in enumerate(cases):
  318. ax.plot(y - i, 'o-')
  319. def test_axline_setters():
  320. fig, ax = plt.subplots()
  321. line1 = ax.axline((.1, .1), slope=0.6)
  322. line2 = ax.axline((.1, .1), (.8, .4))
  323. # Testing xy1, xy2 and slope setters.
  324. # This should not produce an error.
  325. line1.set_xy1(.2, .3)
  326. line1.set_slope(2.4)
  327. line2.set_xy1(.3, .2)
  328. line2.set_xy2(.6, .8)
  329. # Testing xy1, xy2 and slope getters.
  330. # Should return the modified values.
  331. assert line1.get_xy1() == (.2, .3)
  332. assert line1.get_slope() == 2.4
  333. assert line2.get_xy1() == (.3, .2)
  334. assert line2.get_xy2() == (.6, .8)
  335. # Testing setting xy2 and slope together.
  336. # These test should raise a ValueError
  337. with pytest.raises(ValueError,
  338. match="Cannot set an 'xy2' value while 'slope' is set"):
  339. line1.set_xy2(.2, .3)
  340. with pytest.raises(ValueError,
  341. match="Cannot set a 'slope' value while 'xy2' is set"):
  342. line2.set_slope(3)