test_figure.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. from datetime import datetime
  2. import io
  3. from pathlib import Path
  4. import platform
  5. from types import SimpleNamespace
  6. import warnings
  7. try:
  8. from contextlib import nullcontext
  9. except ImportError:
  10. from contextlib import ExitStack as nullcontext # Py3.6
  11. import matplotlib as mpl
  12. from matplotlib import cbook, rcParams
  13. from matplotlib.testing.decorators import image_comparison, check_figures_equal
  14. from matplotlib.axes import Axes
  15. from matplotlib.ticker import AutoMinorLocator, FixedFormatter, ScalarFormatter
  16. import matplotlib.pyplot as plt
  17. import matplotlib.dates as mdates
  18. import matplotlib.gridspec as gridspec
  19. import numpy as np
  20. import pytest
  21. @image_comparison(['figure_align_labels'],
  22. tol=0 if platform.machine() == 'x86_64' else 0.01)
  23. def test_align_labels():
  24. fig = plt.figure(tight_layout=True)
  25. gs = gridspec.GridSpec(3, 3)
  26. ax = fig.add_subplot(gs[0, :2])
  27. ax.plot(np.arange(0, 1e6, 1000))
  28. ax.set_ylabel('Ylabel0 0')
  29. ax = fig.add_subplot(gs[0, -1])
  30. ax.plot(np.arange(0, 1e4, 100))
  31. for i in range(3):
  32. ax = fig.add_subplot(gs[1, i])
  33. ax.set_ylabel('YLabel1 %d' % i)
  34. ax.set_xlabel('XLabel1 %d' % i)
  35. if i in [0, 2]:
  36. ax.xaxis.set_label_position("top")
  37. ax.xaxis.tick_top()
  38. if i == 0:
  39. for tick in ax.get_xticklabels():
  40. tick.set_rotation(90)
  41. if i == 2:
  42. ax.yaxis.set_label_position("right")
  43. ax.yaxis.tick_right()
  44. for i in range(3):
  45. ax = fig.add_subplot(gs[2, i])
  46. ax.set_xlabel(f'XLabel2 {i}')
  47. ax.set_ylabel(f'YLabel2 {i}')
  48. if i == 2:
  49. ax.plot(np.arange(0, 1e4, 10))
  50. ax.yaxis.set_label_position("right")
  51. ax.yaxis.tick_right()
  52. for tick in ax.get_xticklabels():
  53. tick.set_rotation(90)
  54. fig.align_labels()
  55. def test_figure_label():
  56. # pyplot figure creation, selection and closing with figure label and
  57. # number
  58. plt.close('all')
  59. plt.figure('today')
  60. plt.figure(3)
  61. plt.figure('tomorrow')
  62. plt.figure()
  63. plt.figure(0)
  64. plt.figure(1)
  65. plt.figure(3)
  66. assert plt.get_fignums() == [0, 1, 3, 4, 5]
  67. assert plt.get_figlabels() == ['', 'today', '', 'tomorrow', '']
  68. plt.close(10)
  69. plt.close()
  70. plt.close(5)
  71. plt.close('tomorrow')
  72. assert plt.get_fignums() == [0, 1]
  73. assert plt.get_figlabels() == ['', 'today']
  74. def test_fignum_exists():
  75. # pyplot figure creation, selection and closing with fignum_exists
  76. plt.figure('one')
  77. plt.figure(2)
  78. plt.figure('three')
  79. plt.figure()
  80. assert plt.fignum_exists('one')
  81. assert plt.fignum_exists(2)
  82. assert plt.fignum_exists('three')
  83. assert plt.fignum_exists(4)
  84. plt.close('one')
  85. plt.close(4)
  86. assert not plt.fignum_exists('one')
  87. assert not plt.fignum_exists(4)
  88. def test_clf_keyword():
  89. # test if existing figure is cleared with figure() and subplots()
  90. text1 = 'A fancy plot'
  91. text2 = 'Really fancy!'
  92. fig0 = plt.figure(num=1)
  93. fig0.suptitle(text1)
  94. assert [t.get_text() for t in fig0.texts] == [text1]
  95. fig1 = plt.figure(num=1, clear=False)
  96. fig1.text(0.5, 0.5, text2)
  97. assert fig0 is fig1
  98. assert [t.get_text() for t in fig1.texts] == [text1, text2]
  99. fig2, ax2 = plt.subplots(2, 1, num=1, clear=True)
  100. assert fig0 is fig2
  101. assert [t.get_text() for t in fig2.texts] == []
  102. @image_comparison(['figure_today'])
  103. def test_figure():
  104. # named figure support
  105. fig = plt.figure('today')
  106. ax = fig.add_subplot()
  107. ax.set_title(fig.get_label())
  108. ax.plot(np.arange(5))
  109. # plot red line in a different figure.
  110. plt.figure('tomorrow')
  111. plt.plot([0, 1], [1, 0], 'r')
  112. # Return to the original; make sure the red line is not there.
  113. plt.figure('today')
  114. plt.close('tomorrow')
  115. @image_comparison(['figure_legend'])
  116. def test_figure_legend():
  117. fig, axs = plt.subplots(2)
  118. axs[0].plot([0, 1], [1, 0], label='x', color='g')
  119. axs[0].plot([0, 1], [0, 1], label='y', color='r')
  120. axs[0].plot([0, 1], [0.5, 0.5], label='y', color='k')
  121. axs[1].plot([0, 1], [1, 0], label='_y', color='r')
  122. axs[1].plot([0, 1], [0, 1], label='z', color='b')
  123. fig.legend()
  124. def test_gca():
  125. fig = plt.figure()
  126. with pytest.warns(UserWarning):
  127. # empty call to add_axes() will throw deprecation warning
  128. assert fig.add_axes() is None
  129. ax0 = fig.add_axes([0, 0, 1, 1])
  130. assert fig.gca(projection='rectilinear') is ax0
  131. assert fig.gca() is ax0
  132. ax1 = fig.add_axes(rect=[0.1, 0.1, 0.8, 0.8])
  133. assert fig.gca(projection='rectilinear') is ax1
  134. assert fig.gca() is ax1
  135. ax2 = fig.add_subplot(121, projection='polar')
  136. assert fig.gca() is ax2
  137. assert fig.gca(polar=True) is ax2
  138. ax3 = fig.add_subplot(122)
  139. assert fig.gca() is ax3
  140. # the final request for a polar axes will end up creating one
  141. # with a spec of 111.
  142. with pytest.warns(UserWarning):
  143. # Changing the projection will throw a warning
  144. assert fig.gca(polar=True) is not ax3
  145. assert fig.gca(polar=True) is not ax2
  146. assert fig.gca().get_geometry() == (1, 1, 1)
  147. fig.sca(ax1)
  148. assert fig.gca(projection='rectilinear') is ax1
  149. assert fig.gca() is ax1
  150. def test_add_subplot_invalid():
  151. fig = plt.figure()
  152. with pytest.raises(ValueError,
  153. match='Number of columns must be a positive integer'):
  154. fig.add_subplot(2, 0, 1)
  155. with pytest.raises(ValueError,
  156. match='Number of rows must be a positive integer'):
  157. fig.add_subplot(0, 2, 1)
  158. with pytest.raises(ValueError, match='num must be 1 <= num <= 4'):
  159. fig.add_subplot(2, 2, 0)
  160. with pytest.raises(ValueError, match='num must be 1 <= num <= 4'):
  161. fig.add_subplot(2, 2, 5)
  162. with pytest.raises(ValueError, match='must be a three-digit integer'):
  163. fig.add_subplot(42)
  164. with pytest.raises(ValueError, match='must be a three-digit integer'):
  165. fig.add_subplot(1000)
  166. with pytest.raises(TypeError, match='takes 1 or 3 positional arguments '
  167. 'but 2 were given'):
  168. fig.add_subplot(2, 2)
  169. with pytest.raises(TypeError, match='takes 1 or 3 positional arguments '
  170. 'but 4 were given'):
  171. fig.add_subplot(1, 2, 3, 4)
  172. with pytest.warns(cbook.MatplotlibDeprecationWarning,
  173. match='Passing non-integers as three-element position '
  174. 'specification is deprecated'):
  175. fig.add_subplot('2', 2, 1)
  176. with pytest.warns(cbook.MatplotlibDeprecationWarning,
  177. match='Passing non-integers as three-element position '
  178. 'specification is deprecated'):
  179. fig.add_subplot(2.0, 2, 1)
  180. @image_comparison(['figure_suptitle'])
  181. def test_suptitle():
  182. fig, _ = plt.subplots()
  183. fig.suptitle('hello', color='r')
  184. fig.suptitle('title', color='g', rotation='30')
  185. def test_suptitle_fontproperties():
  186. fig, ax = plt.subplots()
  187. fps = mpl.font_manager.FontProperties(size='large', weight='bold')
  188. txt = fig.suptitle('fontprops title', fontproperties=fps)
  189. assert txt.get_fontsize() == fps.get_size_in_points()
  190. assert txt.get_weight() == fps.get_weight()
  191. @image_comparison(['alpha_background'],
  192. # only test png and svg. The PDF output appears correct,
  193. # but Ghostscript does not preserve the background color.
  194. extensions=['png', 'svg'],
  195. savefig_kwarg={'facecolor': (0, 1, 0.4),
  196. 'edgecolor': 'none'})
  197. def test_alpha():
  198. # We want an image which has a background color and an alpha of 0.4.
  199. fig = plt.figure(figsize=[2, 1])
  200. fig.set_facecolor((0, 1, 0.4))
  201. fig.patch.set_alpha(0.4)
  202. fig.patches.append(mpl.patches.CirclePolygon(
  203. [20, 20], radius=15, alpha=0.6, facecolor='red'))
  204. def test_too_many_figures():
  205. with pytest.warns(RuntimeWarning):
  206. for i in range(rcParams['figure.max_open_warning'] + 1):
  207. plt.figure()
  208. def test_iterability_axes_argument():
  209. # This is a regression test for matplotlib/matplotlib#3196. If one of the
  210. # arguments returned by _as_mpl_axes defines __getitem__ but is not
  211. # iterable, this would raise an exception. This is because we check
  212. # whether the arguments are iterable, and if so we try and convert them
  213. # to a tuple. However, the ``iterable`` function returns True if
  214. # __getitem__ is present, but some classes can define __getitem__ without
  215. # being iterable. The tuple conversion is now done in a try...except in
  216. # case it fails.
  217. class MyAxes(Axes):
  218. def __init__(self, *args, myclass=None, **kwargs):
  219. return Axes.__init__(self, *args, **kwargs)
  220. class MyClass:
  221. def __getitem__(self, item):
  222. if item != 'a':
  223. raise ValueError("item should be a")
  224. def _as_mpl_axes(self):
  225. return MyAxes, {'myclass': self}
  226. fig = plt.figure()
  227. fig.add_subplot(1, 1, 1, projection=MyClass())
  228. plt.close(fig)
  229. def test_set_fig_size():
  230. fig = plt.figure()
  231. # check figwidth
  232. fig.set_figwidth(5)
  233. assert fig.get_figwidth() == 5
  234. # check figheight
  235. fig.set_figheight(1)
  236. assert fig.get_figheight() == 1
  237. # check using set_size_inches
  238. fig.set_size_inches(2, 4)
  239. assert fig.get_figwidth() == 2
  240. assert fig.get_figheight() == 4
  241. # check using tuple to first argument
  242. fig.set_size_inches((1, 3))
  243. assert fig.get_figwidth() == 1
  244. assert fig.get_figheight() == 3
  245. def test_axes_remove():
  246. fig, axs = plt.subplots(2, 2)
  247. axs[-1, -1].remove()
  248. for ax in axs.ravel()[:-1]:
  249. assert ax in fig.axes
  250. assert axs[-1, -1] not in fig.axes
  251. assert len(fig.axes) == 3
  252. def test_figaspect():
  253. w, h = plt.figaspect(np.float64(2) / np.float64(1))
  254. assert h / w == 2
  255. w, h = plt.figaspect(2)
  256. assert h / w == 2
  257. w, h = plt.figaspect(np.zeros((1, 2)))
  258. assert h / w == 0.5
  259. w, h = plt.figaspect(np.zeros((2, 2)))
  260. assert h / w == 1
  261. @pytest.mark.parametrize('which', [None, 'both', 'major', 'minor'])
  262. def test_autofmt_xdate(which):
  263. date = ['3 Jan 2013', '4 Jan 2013', '5 Jan 2013', '6 Jan 2013',
  264. '7 Jan 2013', '8 Jan 2013', '9 Jan 2013', '10 Jan 2013',
  265. '11 Jan 2013', '12 Jan 2013', '13 Jan 2013', '14 Jan 2013']
  266. time = ['16:44:00', '16:45:00', '16:46:00', '16:47:00', '16:48:00',
  267. '16:49:00', '16:51:00', '16:52:00', '16:53:00', '16:55:00',
  268. '16:56:00', '16:57:00']
  269. angle = 60
  270. minors = [1, 2, 3, 4, 5, 6, 7]
  271. x = mdates.datestr2num(date)
  272. y = mdates.datestr2num(time)
  273. fig, ax = plt.subplots()
  274. ax.plot(x, y)
  275. ax.yaxis_date()
  276. ax.xaxis_date()
  277. ax.xaxis.set_minor_locator(AutoMinorLocator(2))
  278. with warnings.catch_warnings():
  279. warnings.filterwarnings(
  280. 'ignore',
  281. 'FixedFormatter should only be used together with FixedLocator')
  282. ax.xaxis.set_minor_formatter(FixedFormatter(minors))
  283. with (pytest.warns(mpl.MatplotlibDeprecationWarning) if which is None else
  284. nullcontext()):
  285. fig.autofmt_xdate(0.2, angle, 'right', which)
  286. if which in ('both', 'major', None):
  287. for label in fig.axes[0].get_xticklabels(False, 'major'):
  288. assert int(label.get_rotation()) == angle
  289. if which in ('both', 'minor'):
  290. for label in fig.axes[0].get_xticklabels(True, 'minor'):
  291. assert int(label.get_rotation()) == angle
  292. @pytest.mark.style('default')
  293. def test_change_dpi():
  294. fig = plt.figure(figsize=(4, 4))
  295. fig.canvas.draw()
  296. assert fig.canvas.renderer.height == 400
  297. assert fig.canvas.renderer.width == 400
  298. fig.dpi = 50
  299. fig.canvas.draw()
  300. assert fig.canvas.renderer.height == 200
  301. assert fig.canvas.renderer.width == 200
  302. @pytest.mark.parametrize('width, height', [
  303. (1, np.nan),
  304. (-1, 1),
  305. (np.inf, 1)
  306. ])
  307. def test_invalid_figure_size(width, height):
  308. with pytest.raises(ValueError):
  309. plt.figure(figsize=(width, height))
  310. fig = plt.figure()
  311. with pytest.raises(ValueError):
  312. fig.set_size_inches(width, height)
  313. def test_invalid_figure_add_axes():
  314. fig = plt.figure()
  315. with pytest.raises(ValueError):
  316. fig.add_axes((.1, .1, .5, np.nan))
  317. with pytest.raises(TypeError, match="multiple values for argument 'rect'"):
  318. fig.add_axes([0, 0, 1, 1], rect=[0, 0, 1, 1])
  319. def test_subplots_shareax_loglabels():
  320. fig, axs = plt.subplots(2, 2, sharex=True, sharey=True, squeeze=False)
  321. for ax in axs.flat:
  322. ax.plot([10, 20, 30], [10, 20, 30])
  323. ax.set_yscale("log")
  324. ax.set_xscale("log")
  325. for ax in axs[0, :]:
  326. assert 0 == len(ax.xaxis.get_ticklabels(which='both'))
  327. for ax in axs[1, :]:
  328. assert 0 < len(ax.xaxis.get_ticklabels(which='both'))
  329. for ax in axs[:, 1]:
  330. assert 0 == len(ax.yaxis.get_ticklabels(which='both'))
  331. for ax in axs[:, 0]:
  332. assert 0 < len(ax.yaxis.get_ticklabels(which='both'))
  333. def test_savefig():
  334. fig = plt.figure()
  335. msg = r"savefig\(\) takes 2 positional arguments but 3 were given"
  336. with pytest.raises(TypeError, match=msg):
  337. fig.savefig("fname1.png", "fname2.png")
  338. def test_savefig_warns():
  339. fig = plt.figure()
  340. msg = r'savefig\(\) got unexpected keyword argument "non_existent_kwarg"'
  341. for format in ['png', 'pdf', 'svg', 'tif', 'jpg']:
  342. with pytest.warns(cbook.MatplotlibDeprecationWarning, match=msg):
  343. fig.savefig(io.BytesIO(), format=format, non_existent_kwarg=True)
  344. def test_savefig_backend():
  345. fig = plt.figure()
  346. # Intentionally use an invalid module name.
  347. with pytest.raises(ModuleNotFoundError, match="No module named '@absent'"):
  348. fig.savefig("test", backend="module://@absent")
  349. with pytest.raises(ValueError,
  350. match="The 'pdf' backend does not support png output"):
  351. fig.savefig("test.png", backend="pdf")
  352. def test_figure_repr():
  353. fig = plt.figure(figsize=(10, 20), dpi=10)
  354. assert repr(fig) == "<Figure size 100x200 with 0 Axes>"
  355. def test_warn_cl_plus_tl():
  356. fig, ax = plt.subplots(constrained_layout=True)
  357. with pytest.warns(UserWarning):
  358. # this should warn,
  359. fig.subplots_adjust(top=0.8)
  360. assert not(fig.get_constrained_layout())
  361. @check_figures_equal(extensions=["png", "pdf"])
  362. def test_add_artist(fig_test, fig_ref):
  363. fig_test.set_dpi(100)
  364. fig_ref.set_dpi(100)
  365. fig_test.subplots()
  366. l1 = plt.Line2D([.2, .7], [.7, .7], gid='l1')
  367. l2 = plt.Line2D([.2, .7], [.8, .8], gid='l2')
  368. r1 = plt.Circle((20, 20), 100, transform=None, gid='C1')
  369. r2 = plt.Circle((.7, .5), .05, gid='C2')
  370. r3 = plt.Circle((4.5, .8), .55, transform=fig_test.dpi_scale_trans,
  371. facecolor='crimson', gid='C3')
  372. for a in [l1, l2, r1, r2, r3]:
  373. fig_test.add_artist(a)
  374. l2.remove()
  375. ax2 = fig_ref.subplots()
  376. l1 = plt.Line2D([.2, .7], [.7, .7], transform=fig_ref.transFigure,
  377. gid='l1', zorder=21)
  378. r1 = plt.Circle((20, 20), 100, transform=None, clip_on=False, zorder=20,
  379. gid='C1')
  380. r2 = plt.Circle((.7, .5), .05, transform=fig_ref.transFigure, gid='C2',
  381. zorder=20)
  382. r3 = plt.Circle((4.5, .8), .55, transform=fig_ref.dpi_scale_trans,
  383. facecolor='crimson', clip_on=False, zorder=20, gid='C3')
  384. for a in [l1, r1, r2, r3]:
  385. ax2.add_artist(a)
  386. @pytest.mark.parametrize("fmt", ["png", "pdf", "ps", "eps", "svg"])
  387. def test_fspath(fmt, tmpdir):
  388. out = Path(tmpdir, "test.{}".format(fmt))
  389. plt.savefig(out)
  390. with out.open("rb") as file:
  391. # All the supported formats include the format name (case-insensitive)
  392. # in the first 100 bytes.
  393. assert fmt.encode("ascii") in file.read(100).lower()
  394. def test_tightbbox():
  395. fig, ax = plt.subplots()
  396. ax.set_xlim(0, 1)
  397. t = ax.text(1., 0.5, 'This dangles over end')
  398. renderer = fig.canvas.get_renderer()
  399. x1Nom0 = 9.035 # inches
  400. assert abs(t.get_tightbbox(renderer).x1 - x1Nom0 * fig.dpi) < 2
  401. assert abs(ax.get_tightbbox(renderer).x1 - x1Nom0 * fig.dpi) < 2
  402. assert abs(fig.get_tightbbox(renderer).x1 - x1Nom0) < 0.05
  403. assert abs(fig.get_tightbbox(renderer).x0 - 0.679) < 0.05
  404. # now exclude t from the tight bbox so now the bbox is quite a bit
  405. # smaller
  406. t.set_in_layout(False)
  407. x1Nom = 7.333
  408. assert abs(ax.get_tightbbox(renderer).x1 - x1Nom * fig.dpi) < 2
  409. assert abs(fig.get_tightbbox(renderer).x1 - x1Nom) < 0.05
  410. t.set_in_layout(True)
  411. x1Nom = 7.333
  412. assert abs(ax.get_tightbbox(renderer).x1 - x1Nom0 * fig.dpi) < 2
  413. # test bbox_extra_artists method...
  414. assert abs(ax.get_tightbbox(renderer, bbox_extra_artists=[]).x1
  415. - x1Nom * fig.dpi) < 2
  416. def test_axes_removal():
  417. # Check that units can set the formatter after an Axes removal
  418. fig, axs = plt.subplots(1, 2, sharex=True)
  419. axs[1].remove()
  420. axs[0].plot([datetime(2000, 1, 1), datetime(2000, 2, 1)], [0, 1])
  421. assert isinstance(axs[0].xaxis.get_major_formatter(),
  422. mdates.AutoDateFormatter)
  423. # Check that manually setting the formatter, then removing Axes keeps
  424. # the set formatter.
  425. fig, axs = plt.subplots(1, 2, sharex=True)
  426. axs[1].xaxis.set_major_formatter(ScalarFormatter())
  427. axs[1].remove()
  428. axs[0].plot([datetime(2000, 1, 1), datetime(2000, 2, 1)], [0, 1])
  429. assert isinstance(axs[0].xaxis.get_major_formatter(),
  430. ScalarFormatter)
  431. def test_removed_axis():
  432. # Simple smoke test to make sure removing a shared axis works
  433. fig, axs = plt.subplots(2, sharex=True)
  434. axs[0].remove()
  435. fig.canvas.draw()
  436. @pytest.mark.style('mpl20')
  437. def test_picking_does_not_stale():
  438. fig, ax = plt.subplots()
  439. col = ax.scatter([0], [0], [1000], picker=True)
  440. fig.canvas.draw()
  441. assert not fig.stale
  442. mouse_event = SimpleNamespace(x=ax.bbox.x0 + ax.bbox.width / 2,
  443. y=ax.bbox.y0 + ax.bbox.height / 2,
  444. inaxes=ax, guiEvent=None)
  445. fig.pick(mouse_event)
  446. assert not fig.stale
  447. def test_add_subplot_twotuple():
  448. fig = plt.figure()
  449. ax1 = fig.add_subplot(3, 2, (3, 5))
  450. assert ax1.get_subplotspec().rowspan == range(1, 3)
  451. assert ax1.get_subplotspec().colspan == range(0, 1)
  452. ax2 = fig.add_subplot(3, 2, (4, 6))
  453. assert ax2.get_subplotspec().rowspan == range(1, 3)
  454. assert ax2.get_subplotspec().colspan == range(1, 2)
  455. ax3 = fig.add_subplot(3, 2, (3, 6))
  456. assert ax3.get_subplotspec().rowspan == range(1, 3)
  457. assert ax3.get_subplotspec().colspan == range(0, 2)
  458. ax4 = fig.add_subplot(3, 2, (4, 5))
  459. assert ax4.get_subplotspec().rowspan == range(1, 3)
  460. assert ax4.get_subplotspec().colspan == range(0, 2)
  461. with pytest.raises(IndexError):
  462. fig.add_subplot(3, 2, (6, 3))
  463. @image_comparison(['tightbbox_box_aspect.svg'], style='mpl20',
  464. savefig_kwarg={'bbox_inches': 'tight',
  465. 'facecolor': 'teal'},
  466. remove_text=True)
  467. def test_tightbbox_box_aspect():
  468. fig = plt.figure()
  469. gs = fig.add_gridspec(1, 2)
  470. ax1 = fig.add_subplot(gs[0, 0])
  471. ax2 = fig.add_subplot(gs[0, 1], projection='3d')
  472. ax1.set_box_aspect(.5)
  473. ax2.set_box_aspect((2, 1, 1))
  474. @check_figures_equal(extensions=["svg", "pdf", "eps", "png"])
  475. def test_animated_with_canvas_change(fig_test, fig_ref):
  476. ax_ref = fig_ref.subplots()
  477. ax_ref.plot(range(5))
  478. ax_test = fig_test.subplots()
  479. ax_test.plot(range(5), animated=True)
  480. class TestSubplotMosaic:
  481. @check_figures_equal(extensions=["png"])
  482. @pytest.mark.parametrize(
  483. "x", [[["A", "A", "B"], ["C", "D", "B"]], [[1, 1, 2], [3, 4, 2]]]
  484. )
  485. def test_basic(self, fig_test, fig_ref, x):
  486. grid_axes = fig_test.subplot_mosaic(x)
  487. for k, ax in grid_axes.items():
  488. ax.set_title(k)
  489. labels = sorted(np.unique(x))
  490. assert len(labels) == len(grid_axes)
  491. gs = fig_ref.add_gridspec(2, 3)
  492. axA = fig_ref.add_subplot(gs[:1, :2])
  493. axA.set_title(labels[0])
  494. axB = fig_ref.add_subplot(gs[:, 2])
  495. axB.set_title(labels[1])
  496. axC = fig_ref.add_subplot(gs[1, 0])
  497. axC.set_title(labels[2])
  498. axD = fig_ref.add_subplot(gs[1, 1])
  499. axD.set_title(labels[3])
  500. @check_figures_equal(extensions=["png"])
  501. def test_all_nested(self, fig_test, fig_ref):
  502. x = [["A", "B"], ["C", "D"]]
  503. y = [["E", "F"], ["G", "H"]]
  504. fig_ref.set_constrained_layout(True)
  505. fig_test.set_constrained_layout(True)
  506. grid_axes = fig_test.subplot_mosaic([[x, y]])
  507. for ax in grid_axes.values():
  508. ax.set_title(ax.get_label())
  509. gs = fig_ref.add_gridspec(1, 2)
  510. gs_left = gs[0, 0].subgridspec(2, 2)
  511. for j, r in enumerate(x):
  512. for k, label in enumerate(r):
  513. fig_ref.add_subplot(gs_left[j, k]).set_title(label)
  514. gs_right = gs[0, 1].subgridspec(2, 2)
  515. for j, r in enumerate(y):
  516. for k, label in enumerate(r):
  517. fig_ref.add_subplot(gs_right[j, k]).set_title(label)
  518. @check_figures_equal(extensions=["png"])
  519. def test_nested(self, fig_test, fig_ref):
  520. fig_ref.set_constrained_layout(True)
  521. fig_test.set_constrained_layout(True)
  522. x = [["A", "B"], ["C", "D"]]
  523. y = [["F"], [x]]
  524. grid_axes = fig_test.subplot_mosaic(y)
  525. for k, ax in grid_axes.items():
  526. ax.set_title(k)
  527. gs = fig_ref.add_gridspec(2, 1)
  528. gs_n = gs[1, 0].subgridspec(2, 2)
  529. axA = fig_ref.add_subplot(gs_n[0, 0])
  530. axA.set_title("A")
  531. axB = fig_ref.add_subplot(gs_n[0, 1])
  532. axB.set_title("B")
  533. axC = fig_ref.add_subplot(gs_n[1, 0])
  534. axC.set_title("C")
  535. axD = fig_ref.add_subplot(gs_n[1, 1])
  536. axD.set_title("D")
  537. axF = fig_ref.add_subplot(gs[0, 0])
  538. axF.set_title("F")
  539. @check_figures_equal(extensions=["png"])
  540. def test_nested_tuple(self, fig_test, fig_ref):
  541. x = [["A", "B", "B"], ["C", "C", "D"]]
  542. xt = (("A", "B", "B"), ("C", "C", "D"))
  543. fig_ref.subplot_mosaic([["F"], [x]])
  544. fig_test.subplot_mosaic([["F"], [xt]])
  545. @check_figures_equal(extensions=["png"])
  546. @pytest.mark.parametrize(
  547. "x, empty_sentinel",
  548. [
  549. ([["A", None], [None, "B"]], None),
  550. ([["A", "."], [".", "B"]], "SKIP"),
  551. ([["A", 0], [0, "B"]], 0),
  552. ([[1, None], [None, 2]], None),
  553. ([[1, "."], [".", 2]], "SKIP"),
  554. ([[1, 0], [0, 2]], 0),
  555. ],
  556. )
  557. def test_empty(self, fig_test, fig_ref, x, empty_sentinel):
  558. if empty_sentinel != "SKIP":
  559. kwargs = {"empty_sentinel": empty_sentinel}
  560. else:
  561. kwargs = {}
  562. grid_axes = fig_test.subplot_mosaic(x, **kwargs)
  563. for k, ax in grid_axes.items():
  564. ax.set_title(k)
  565. labels = sorted(
  566. {name for row in x for name in row} - {empty_sentinel, "."}
  567. )
  568. assert len(labels) == len(grid_axes)
  569. gs = fig_ref.add_gridspec(2, 2)
  570. axA = fig_ref.add_subplot(gs[0, 0])
  571. axA.set_title(labels[0])
  572. axB = fig_ref.add_subplot(gs[1, 1])
  573. axB.set_title(labels[1])
  574. def test_fail_list_of_str(self):
  575. with pytest.raises(ValueError, match='must be 2D'):
  576. plt.subplot_mosaic(['foo', 'bar'])
  577. @check_figures_equal(extensions=["png"])
  578. @pytest.mark.parametrize("subplot_kw", [{}, {"projection": "polar"}, None])
  579. def test_subplot_kw(self, fig_test, fig_ref, subplot_kw):
  580. x = [[1, 2]]
  581. grid_axes = fig_test.subplot_mosaic(x, subplot_kw=subplot_kw)
  582. subplot_kw = subplot_kw or {}
  583. gs = fig_ref.add_gridspec(1, 2)
  584. axA = fig_ref.add_subplot(gs[0, 0], **subplot_kw)
  585. axB = fig_ref.add_subplot(gs[0, 1], **subplot_kw)
  586. @check_figures_equal(extensions=["png"])
  587. @pytest.mark.parametrize("str_pattern",
  588. ["AAA\nBBB", "\nAAA\nBBB\n", "ABC\nDEF"]
  589. )
  590. def test_single_str_input(self, fig_test, fig_ref, str_pattern):
  591. grid_axes = fig_test.subplot_mosaic(str_pattern)
  592. grid_axes = fig_ref.subplot_mosaic(
  593. [list(ln) for ln in str_pattern.strip().split("\n")]
  594. )
  595. @pytest.mark.parametrize(
  596. "x,match",
  597. [
  598. (
  599. [["A", "."], [".", "A"]],
  600. (
  601. "(?m)we found that the label .A. specifies a "
  602. + "non-rectangular or non-contiguous area."
  603. ),
  604. ),
  605. (
  606. [["A", "B"], [None, [["A", "B"], ["C", "D"]]]],
  607. "There are duplicate keys .* between the outer layout",
  608. ),
  609. ("AAA\nc\nBBB", "All of the rows must be the same length"),
  610. (
  611. [["A", [["B", "C"], ["D"]]], ["E", "E"]],
  612. "All of the rows must be the same length",
  613. ),
  614. ],
  615. )
  616. def test_fail(self, x, match):
  617. fig = plt.figure()
  618. with pytest.raises(ValueError, match=match):
  619. fig.subplot_mosaic(x)
  620. @check_figures_equal(extensions=["png"])
  621. def test_hashable_keys(self, fig_test, fig_ref):
  622. fig_test.subplot_mosaic([[object(), object()]])
  623. fig_ref.subplot_mosaic([["A", "B"]])