test_lines.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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. import pytest
  9. import matplotlib
  10. import matplotlib.lines as mlines
  11. import matplotlib.pyplot as plt
  12. from matplotlib.testing.decorators import image_comparison, check_figures_equal
  13. # Runtimes on a loaded system are inherently flaky. Not so much that a rerun
  14. # won't help, hopefully.
  15. @pytest.mark.flaky(reruns=3)
  16. def test_invisible_Line_rendering():
  17. """
  18. GitHub issue #1256 identified a bug in Line.draw method
  19. Despite visibility attribute set to False, the draw method was not
  20. returning early enough and some pre-rendering code was executed
  21. though not necessary.
  22. Consequence was an excessive draw time for invisible Line instances
  23. holding a large number of points (Npts> 10**6)
  24. """
  25. # Creates big x and y data:
  26. N = 10**7
  27. x = np.linspace(0, 1, N)
  28. y = np.random.normal(size=N)
  29. # Create a plot figure:
  30. fig = plt.figure()
  31. ax = plt.subplot(111)
  32. # Create a "big" Line instance:
  33. l = mlines.Line2D(x, y)
  34. l.set_visible(False)
  35. # but don't add it to the Axis instance `ax`
  36. # [here Interactive panning and zooming is pretty responsive]
  37. # Time the canvas drawing:
  38. t_no_line = min(timeit.repeat(fig.canvas.draw, number=1, repeat=3))
  39. # (gives about 25 ms)
  40. # Add the big invisible Line:
  41. ax.add_line(l)
  42. # [Now interactive panning and zooming is very slow]
  43. # Time the canvas drawing:
  44. t_invisible_line = min(timeit.repeat(fig.canvas.draw, number=1, repeat=3))
  45. # gives about 290 ms for N = 10**7 pts
  46. slowdown_factor = t_invisible_line / t_no_line
  47. slowdown_threshold = 2 # trying to avoid false positive failures
  48. assert slowdown_factor < slowdown_threshold
  49. def test_set_line_coll_dash():
  50. fig = plt.figure()
  51. ax = fig.add_subplot(1, 1, 1)
  52. np.random.seed(0)
  53. # Testing setting linestyles for line collections.
  54. # This should not produce an error.
  55. ax.contour(np.random.randn(20, 30), linestyles=[(0, (3, 3))])
  56. @image_comparison(['line_dashes'], remove_text=True)
  57. def test_line_dashes():
  58. fig = plt.figure()
  59. ax = fig.add_subplot(1, 1, 1)
  60. ax.plot(range(10), linestyle=(0, (3, 3)), lw=5)
  61. def test_line_colors():
  62. fig = plt.figure()
  63. ax = fig.add_subplot(1, 1, 1)
  64. ax.plot(range(10), color='none')
  65. ax.plot(range(10), color='r')
  66. ax.plot(range(10), color='.3')
  67. ax.plot(range(10), color=(1, 0, 0, 1))
  68. ax.plot(range(10), color=(1, 0, 0))
  69. fig.canvas.draw()
  70. def test_linestyle_variants():
  71. fig = plt.figure()
  72. ax = fig.add_subplot(1, 1, 1)
  73. for ls in ["-", "solid", "--", "dashed",
  74. "-.", "dashdot", ":", "dotted"]:
  75. ax.plot(range(10), linestyle=ls)
  76. fig.canvas.draw()
  77. def test_valid_linestyles():
  78. line = mlines.Line2D([], [])
  79. with pytest.raises(ValueError):
  80. line.set_linestyle('aardvark')
  81. @image_comparison(['drawstyle_variants.png'], remove_text=True)
  82. def test_drawstyle_variants():
  83. fig, axs = plt.subplots(6)
  84. dss = ["default", "steps-mid", "steps-pre", "steps-post", "steps", None]
  85. # We want to check that drawstyles are properly handled even for very long
  86. # lines (for which the subslice optimization is on); however, we need
  87. # to zoom in so that the difference between the drawstyles is actually
  88. # visible.
  89. for ax, ds in zip(axs.flat, dss):
  90. ax.plot(range(2000), drawstyle=ds)
  91. ax.set(xlim=(0, 2), ylim=(0, 2))
  92. def test_valid_drawstyles():
  93. line = mlines.Line2D([], [])
  94. with pytest.raises(ValueError):
  95. line.set_drawstyle('foobar')
  96. def test_set_drawstyle():
  97. x = np.linspace(0, 2*np.pi, 10)
  98. y = np.sin(x)
  99. fig, ax = plt.subplots()
  100. line, = ax.plot(x, y)
  101. line.set_drawstyle("steps-pre")
  102. assert len(line.get_path().vertices) == 2*len(x)-1
  103. line.set_drawstyle("default")
  104. assert len(line.get_path().vertices) == len(x)
  105. @image_comparison(['line_collection_dashes'], remove_text=True, style='mpl20')
  106. def test_set_line_coll_dash_image():
  107. fig = plt.figure()
  108. ax = fig.add_subplot(1, 1, 1)
  109. np.random.seed(0)
  110. ax.contour(np.random.randn(20, 30), linestyles=[(0, (3, 3))])
  111. @image_comparison(['marker_fill_styles.png'], remove_text=True)
  112. def test_marker_fill_styles():
  113. colors = itertools.cycle([[0, 0, 1], 'g', '#ff0000', 'c', 'm', 'y',
  114. np.array([0, 0, 0])])
  115. altcolor = 'lightgreen'
  116. y = np.array([1, 1])
  117. x = np.array([0, 9])
  118. fig, ax = plt.subplots()
  119. for j, marker in enumerate(mlines.Line2D.filled_markers):
  120. for i, fs in enumerate(mlines.Line2D.fillStyles):
  121. color = next(colors)
  122. ax.plot(j * 10 + x, y + i + .5 * (j % 2),
  123. marker=marker,
  124. markersize=20,
  125. markerfacecoloralt=altcolor,
  126. fillstyle=fs,
  127. label=fs,
  128. linewidth=5,
  129. color=color,
  130. markeredgecolor=color,
  131. markeredgewidth=2)
  132. ax.set_ylim([0, 7.5])
  133. ax.set_xlim([-5, 155])
  134. @image_comparison(['scaled_lines'], style='default')
  135. def test_lw_scaling():
  136. th = np.linspace(0, 32)
  137. fig, ax = plt.subplots()
  138. lins_styles = ['dashed', 'dotted', 'dashdot']
  139. cy = cycler(matplotlib.rcParams['axes.prop_cycle'])
  140. for j, (ls, sty) in enumerate(zip(lins_styles, cy)):
  141. for lw in np.linspace(.5, 10, 10):
  142. ax.plot(th, j*np.ones(50) + .1 * lw, linestyle=ls, lw=lw, **sty)
  143. def test_nan_is_sorted():
  144. line = mlines.Line2D([], [])
  145. assert line._is_sorted(np.array([1, 2, 3]))
  146. assert line._is_sorted(np.array([1, np.nan, 3]))
  147. assert not line._is_sorted([3, 5] + [np.nan] * 100 + [0, 2])
  148. @check_figures_equal()
  149. def test_step_markers(fig_test, fig_ref):
  150. fig_test.subplots().step([0, 1], "-o")
  151. fig_ref.subplots().plot([0, 0, 1], [0, 1, 1], "-o", markevery=[0, 2])