test_pyplot.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. import difflib
  2. import numpy as np
  3. import sys
  4. from pathlib import Path
  5. import pytest
  6. import matplotlib as mpl
  7. from matplotlib.testing import subprocess_run_for_testing
  8. from matplotlib import pyplot as plt
  9. def test_pyplot_up_to_date(tmpdir):
  10. pytest.importorskip("black")
  11. gen_script = Path(mpl.__file__).parents[2] / "tools/boilerplate.py"
  12. if not gen_script.exists():
  13. pytest.skip("boilerplate.py not found")
  14. orig_contents = Path(plt.__file__).read_text()
  15. plt_file = tmpdir.join('pyplot.py')
  16. plt_file.write_text(orig_contents, 'utf-8')
  17. subprocess_run_for_testing(
  18. [sys.executable, str(gen_script), str(plt_file)],
  19. check=True)
  20. new_contents = plt_file.read_text('utf-8')
  21. if orig_contents != new_contents:
  22. diff_msg = '\n'.join(
  23. difflib.unified_diff(
  24. orig_contents.split('\n'), new_contents.split('\n'),
  25. fromfile='found pyplot.py',
  26. tofile='expected pyplot.py',
  27. n=0, lineterm=''))
  28. pytest.fail(
  29. "pyplot.py is not up-to-date. Please run "
  30. "'python tools/boilerplate.py' to update pyplot.py. "
  31. "This needs to be done from an environment where your "
  32. "current working copy is installed (e.g. 'pip install -e'd). "
  33. "Here is a diff of unexpected differences:\n%s" % diff_msg
  34. )
  35. def test_copy_docstring_and_deprecators(recwarn):
  36. @mpl._api.rename_parameter("(version)", "old", "new")
  37. @mpl._api.make_keyword_only("(version)", "kwo")
  38. def func(new, kwo=None):
  39. pass
  40. @plt._copy_docstring_and_deprecators(func)
  41. def wrapper_func(new, kwo=None):
  42. pass
  43. wrapper_func(None)
  44. wrapper_func(new=None)
  45. wrapper_func(None, kwo=None)
  46. wrapper_func(new=None, kwo=None)
  47. assert not recwarn
  48. with pytest.warns(mpl.MatplotlibDeprecationWarning):
  49. wrapper_func(old=None)
  50. with pytest.warns(mpl.MatplotlibDeprecationWarning):
  51. wrapper_func(None, None)
  52. def test_pyplot_box():
  53. fig, ax = plt.subplots()
  54. plt.box(False)
  55. assert not ax.get_frame_on()
  56. plt.box(True)
  57. assert ax.get_frame_on()
  58. plt.box()
  59. assert not ax.get_frame_on()
  60. plt.box()
  61. assert ax.get_frame_on()
  62. def test_stackplot_smoke():
  63. # Small smoke test for stackplot (see #12405)
  64. plt.stackplot([1, 2, 3], [1, 2, 3])
  65. def test_nrows_error():
  66. with pytest.raises(TypeError):
  67. plt.subplot(nrows=1)
  68. with pytest.raises(TypeError):
  69. plt.subplot(ncols=1)
  70. def test_ioff():
  71. plt.ion()
  72. assert mpl.is_interactive()
  73. with plt.ioff():
  74. assert not mpl.is_interactive()
  75. assert mpl.is_interactive()
  76. plt.ioff()
  77. assert not mpl.is_interactive()
  78. with plt.ioff():
  79. assert not mpl.is_interactive()
  80. assert not mpl.is_interactive()
  81. def test_ion():
  82. plt.ioff()
  83. assert not mpl.is_interactive()
  84. with plt.ion():
  85. assert mpl.is_interactive()
  86. assert not mpl.is_interactive()
  87. plt.ion()
  88. assert mpl.is_interactive()
  89. with plt.ion():
  90. assert mpl.is_interactive()
  91. assert mpl.is_interactive()
  92. def test_nested_ion_ioff():
  93. # initial state is interactive
  94. plt.ion()
  95. # mixed ioff/ion
  96. with plt.ioff():
  97. assert not mpl.is_interactive()
  98. with plt.ion():
  99. assert mpl.is_interactive()
  100. assert not mpl.is_interactive()
  101. assert mpl.is_interactive()
  102. # redundant contexts
  103. with plt.ioff():
  104. with plt.ioff():
  105. assert not mpl.is_interactive()
  106. assert mpl.is_interactive()
  107. with plt.ion():
  108. plt.ioff()
  109. assert mpl.is_interactive()
  110. # initial state is not interactive
  111. plt.ioff()
  112. # mixed ioff/ion
  113. with plt.ion():
  114. assert mpl.is_interactive()
  115. with plt.ioff():
  116. assert not mpl.is_interactive()
  117. assert mpl.is_interactive()
  118. assert not mpl.is_interactive()
  119. # redundant contexts
  120. with plt.ion():
  121. with plt.ion():
  122. assert mpl.is_interactive()
  123. assert not mpl.is_interactive()
  124. with plt.ioff():
  125. plt.ion()
  126. assert not mpl.is_interactive()
  127. def test_close():
  128. try:
  129. plt.close(1.1)
  130. except TypeError as e:
  131. assert str(e) == "close() argument must be a Figure, an int, " \
  132. "a string, or None, not <class 'float'>"
  133. def test_subplot_reuse():
  134. ax1 = plt.subplot(121)
  135. assert ax1 is plt.gca()
  136. ax2 = plt.subplot(122)
  137. assert ax2 is plt.gca()
  138. ax3 = plt.subplot(121)
  139. assert ax1 is plt.gca()
  140. assert ax1 is ax3
  141. def test_axes_kwargs():
  142. # plt.axes() always creates new axes, even if axes kwargs differ.
  143. plt.figure()
  144. ax = plt.axes()
  145. ax1 = plt.axes()
  146. assert ax is not None
  147. assert ax1 is not ax
  148. plt.close()
  149. plt.figure()
  150. ax = plt.axes(projection='polar')
  151. ax1 = plt.axes(projection='polar')
  152. assert ax is not None
  153. assert ax1 is not ax
  154. plt.close()
  155. plt.figure()
  156. ax = plt.axes(projection='polar')
  157. ax1 = plt.axes()
  158. assert ax is not None
  159. assert ax1.name == 'rectilinear'
  160. assert ax1 is not ax
  161. plt.close()
  162. def test_subplot_replace_projection():
  163. # plt.subplot() searches for axes with the same subplot spec, and if one
  164. # exists, and the kwargs match returns it, create a new one if they do not
  165. fig = plt.figure()
  166. ax = plt.subplot(1, 2, 1)
  167. ax1 = plt.subplot(1, 2, 1)
  168. ax2 = plt.subplot(1, 2, 2)
  169. ax3 = plt.subplot(1, 2, 1, projection='polar')
  170. ax4 = plt.subplot(1, 2, 1, projection='polar')
  171. assert ax is not None
  172. assert ax1 is ax
  173. assert ax2 is not ax
  174. assert ax3 is not ax
  175. assert ax3 is ax4
  176. assert ax in fig.axes
  177. assert ax2 in fig.axes
  178. assert ax3 in fig.axes
  179. assert ax.name == 'rectilinear'
  180. assert ax2.name == 'rectilinear'
  181. assert ax3.name == 'polar'
  182. def test_subplot_kwarg_collision():
  183. ax1 = plt.subplot(projection='polar', theta_offset=0)
  184. ax2 = plt.subplot(projection='polar', theta_offset=0)
  185. assert ax1 is ax2
  186. ax1.remove()
  187. ax3 = plt.subplot(projection='polar', theta_offset=1)
  188. assert ax1 is not ax3
  189. assert ax1 not in plt.gcf().axes
  190. def test_gca():
  191. # plt.gca() returns an existing axes, unless there were no axes.
  192. plt.figure()
  193. ax = plt.gca()
  194. ax1 = plt.gca()
  195. assert ax is not None
  196. assert ax1 is ax
  197. plt.close()
  198. def test_subplot_projection_reuse():
  199. # create an Axes
  200. ax1 = plt.subplot(111)
  201. # check that it is current
  202. assert ax1 is plt.gca()
  203. # make sure we get it back if we ask again
  204. assert ax1 is plt.subplot(111)
  205. # remove it
  206. ax1.remove()
  207. # create a polar plot
  208. ax2 = plt.subplot(111, projection='polar')
  209. assert ax2 is plt.gca()
  210. # this should have deleted the first axes
  211. assert ax1 not in plt.gcf().axes
  212. # assert we get it back if no extra parameters passed
  213. assert ax2 is plt.subplot(111)
  214. ax2.remove()
  215. # now check explicitly setting the projection to rectilinear
  216. # makes a new axes
  217. ax3 = plt.subplot(111, projection='rectilinear')
  218. assert ax3 is plt.gca()
  219. assert ax3 is not ax2
  220. assert ax2 not in plt.gcf().axes
  221. def test_subplot_polar_normalization():
  222. ax1 = plt.subplot(111, projection='polar')
  223. ax2 = plt.subplot(111, polar=True)
  224. ax3 = plt.subplot(111, polar=True, projection='polar')
  225. assert ax1 is ax2
  226. assert ax1 is ax3
  227. with pytest.raises(ValueError,
  228. match="polar=True, yet projection='3d'"):
  229. ax2 = plt.subplot(111, polar=True, projection='3d')
  230. def test_subplot_change_projection():
  231. created_axes = set()
  232. ax = plt.subplot()
  233. created_axes.add(ax)
  234. projections = ('aitoff', 'hammer', 'lambert', 'mollweide',
  235. 'polar', 'rectilinear', '3d')
  236. for proj in projections:
  237. ax.remove()
  238. ax = plt.subplot(projection=proj)
  239. assert ax is plt.subplot()
  240. assert ax.name == proj
  241. created_axes.add(ax)
  242. # Check that each call created a new Axes.
  243. assert len(created_axes) == 1 + len(projections)
  244. def test_polar_second_call():
  245. # the first call creates the axes with polar projection
  246. ln1, = plt.polar(0., 1., 'ro')
  247. assert isinstance(ln1, mpl.lines.Line2D)
  248. # the second call should reuse the existing axes
  249. ln2, = plt.polar(1.57, .5, 'bo')
  250. assert isinstance(ln2, mpl.lines.Line2D)
  251. assert ln1.axes is ln2.axes
  252. def test_fallback_position():
  253. # check that position kwarg works if rect not supplied
  254. axref = plt.axes([0.2, 0.2, 0.5, 0.5])
  255. axtest = plt.axes(position=[0.2, 0.2, 0.5, 0.5])
  256. np.testing.assert_allclose(axtest.bbox.get_points(),
  257. axref.bbox.get_points())
  258. # check that position kwarg ignored if rect is supplied
  259. axref = plt.axes([0.2, 0.2, 0.5, 0.5])
  260. axtest = plt.axes([0.2, 0.2, 0.5, 0.5], position=[0.1, 0.1, 0.8, 0.8])
  261. np.testing.assert_allclose(axtest.bbox.get_points(),
  262. axref.bbox.get_points())
  263. def test_set_current_figure_via_subfigure():
  264. fig1 = plt.figure()
  265. subfigs = fig1.subfigures(2)
  266. plt.figure()
  267. assert plt.gcf() != fig1
  268. current = plt.figure(subfigs[1])
  269. assert plt.gcf() == fig1
  270. assert current == fig1
  271. def test_set_current_axes_on_subfigure():
  272. fig = plt.figure()
  273. subfigs = fig.subfigures(2)
  274. ax = subfigs[0].subplots(1, squeeze=True)
  275. subfigs[1].subplots(1, squeeze=True)
  276. assert plt.gca() != ax
  277. plt.sca(ax)
  278. assert plt.gca() == ax
  279. def test_pylab_integration():
  280. IPython = pytest.importorskip("IPython")
  281. mpl.testing.subprocess_run_helper(
  282. IPython.start_ipython,
  283. "--pylab",
  284. "-c",
  285. ";".join((
  286. "import matplotlib.pyplot as plt",
  287. "assert plt._REPL_DISPLAYHOOK == plt._ReplDisplayHook.IPYTHON",
  288. )),
  289. timeout=60,
  290. )
  291. def test_doc_pyplot_summary():
  292. """Test that pyplot_summary lists all the plot functions."""
  293. pyplot_docs = Path(__file__).parent / '../../../doc/api/pyplot_summary.rst'
  294. if not pyplot_docs.exists():
  295. pytest.skip("Documentation sources not available")
  296. def extract_documented_functions(lines):
  297. """
  298. Return a list of all the functions that are mentioned in the
  299. autosummary blocks contained in *lines*.
  300. An autosummary block looks like this::
  301. .. autosummary::
  302. :toctree: _as_gen
  303. :template: autosummary.rst
  304. :nosignatures:
  305. plot
  306. plot_date
  307. """
  308. functions = []
  309. in_autosummary = False
  310. for line in lines:
  311. if not in_autosummary:
  312. if line.startswith(".. autosummary::"):
  313. in_autosummary = True
  314. else:
  315. if not line or line.startswith(" :"):
  316. # empty line or autosummary parameter
  317. continue
  318. if not line[0].isspace():
  319. # no more indentation: end of autosummary block
  320. in_autosummary = False
  321. continue
  322. functions.append(line.strip())
  323. return functions
  324. lines = pyplot_docs.read_text().split("\n")
  325. doc_functions = set(extract_documented_functions(lines))
  326. plot_commands = set(plt._get_pyplot_commands())
  327. missing = plot_commands.difference(doc_functions)
  328. if missing:
  329. raise AssertionError(
  330. f"The following pyplot functions are not listed in the "
  331. f"documentation. Please add them to doc/api/pyplot_summary.rst: "
  332. f"{missing!r}")
  333. extra = doc_functions.difference(plot_commands)
  334. if extra:
  335. raise AssertionError(
  336. f"The following functions are listed in the pyplot documentation, "
  337. f"but they do not exist in pyplot. "
  338. f"Please remove them from doc/api/pyplot_summary.rst: {extra!r}")
  339. def test_minor_ticks():
  340. plt.figure()
  341. plt.plot(np.arange(1, 10))
  342. tick_pos, tick_labels = plt.xticks(minor=True)
  343. assert np.all(tick_labels == np.array([], dtype=np.float64))
  344. assert tick_labels == []
  345. plt.yticks(ticks=[3.5, 6.5], labels=["a", "b"], minor=True)
  346. ax = plt.gca()
  347. tick_pos = ax.get_yticks(minor=True)
  348. tick_labels = ax.get_yticklabels(minor=True)
  349. assert np.all(tick_pos == np.array([3.5, 6.5]))
  350. assert [l.get_text() for l in tick_labels] == ['a', 'b']
  351. def test_switch_backend_no_close():
  352. plt.switch_backend('agg')
  353. fig = plt.figure()
  354. fig = plt.figure()
  355. assert len(plt.get_fignums()) == 2
  356. plt.switch_backend('agg')
  357. assert len(plt.get_fignums()) == 2
  358. with pytest.warns(mpl.MatplotlibDeprecationWarning):
  359. plt.switch_backend('svg')
  360. assert len(plt.get_fignums()) == 0
  361. def figure_hook_example(figure):
  362. figure._test_was_here = True
  363. def test_figure_hook():
  364. test_rc = {
  365. 'figure.hooks': ['matplotlib.tests.test_pyplot:figure_hook_example']
  366. }
  367. with mpl.rc_context(test_rc):
  368. fig = plt.figure()
  369. assert fig._test_was_here