test_figure.py 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821
  1. import copy
  2. from datetime import datetime
  3. import io
  4. import pickle
  5. import platform
  6. from threading import Timer
  7. from types import SimpleNamespace
  8. import warnings
  9. import numpy as np
  10. import pytest
  11. from PIL import Image
  12. import matplotlib as mpl
  13. from matplotlib import gridspec
  14. from matplotlib.testing.decorators import image_comparison, check_figures_equal
  15. from matplotlib.axes import Axes
  16. from matplotlib.backend_bases import KeyEvent, MouseEvent
  17. from matplotlib.figure import Figure, FigureBase
  18. from matplotlib.layout_engine import (ConstrainedLayoutEngine,
  19. TightLayoutEngine,
  20. PlaceHolderLayoutEngine)
  21. from matplotlib.ticker import AutoMinorLocator, FixedFormatter, ScalarFormatter
  22. import matplotlib.pyplot as plt
  23. import matplotlib.dates as mdates
  24. @image_comparison(['figure_align_labels'], extensions=['png', 'svg'],
  25. tol=0 if platform.machine() == 'x86_64' else 0.01)
  26. def test_align_labels():
  27. fig = plt.figure(layout='tight')
  28. gs = gridspec.GridSpec(3, 3)
  29. ax = fig.add_subplot(gs[0, :2])
  30. ax.plot(np.arange(0, 1e6, 1000))
  31. ax.set_ylabel('Ylabel0 0')
  32. ax = fig.add_subplot(gs[0, -1])
  33. ax.plot(np.arange(0, 1e4, 100))
  34. for i in range(3):
  35. ax = fig.add_subplot(gs[1, i])
  36. ax.set_ylabel('YLabel1 %d' % i)
  37. ax.set_xlabel('XLabel1 %d' % i)
  38. if i in [0, 2]:
  39. ax.xaxis.set_label_position("top")
  40. ax.xaxis.tick_top()
  41. if i == 0:
  42. for tick in ax.get_xticklabels():
  43. tick.set_rotation(90)
  44. if i == 2:
  45. ax.yaxis.set_label_position("right")
  46. ax.yaxis.tick_right()
  47. for i in range(3):
  48. ax = fig.add_subplot(gs[2, i])
  49. ax.set_xlabel(f'XLabel2 {i}')
  50. ax.set_ylabel(f'YLabel2 {i}')
  51. if i == 2:
  52. ax.plot(np.arange(0, 1e4, 10))
  53. ax.yaxis.set_label_position("right")
  54. ax.yaxis.tick_right()
  55. for tick in ax.get_xticklabels():
  56. tick.set_rotation(90)
  57. fig.align_labels()
  58. @image_comparison(['figure_align_titles_tight.png',
  59. 'figure_align_titles_constrained.png'],
  60. tol=0 if platform.machine() == 'x86_64' else 0.022,
  61. style='mpl20')
  62. def test_align_titles():
  63. for layout in ['tight', 'constrained']:
  64. fig, axs = plt.subplots(1, 2, layout=layout, width_ratios=[2, 1])
  65. ax = axs[0]
  66. ax.plot(np.arange(0, 1e6, 1000))
  67. ax.set_title('Title0 left', loc='left')
  68. ax.set_title('Title0 center', loc='center')
  69. ax.set_title('Title0 right', loc='right')
  70. ax = axs[1]
  71. ax.plot(np.arange(0, 1e4, 100))
  72. ax.set_title('Title1')
  73. ax.set_xlabel('Xlabel0')
  74. ax.xaxis.set_label_position("top")
  75. ax.xaxis.tick_top()
  76. for tick in ax.get_xticklabels():
  77. tick.set_rotation(90)
  78. fig.align_titles()
  79. def test_align_labels_stray_axes():
  80. fig, axs = plt.subplots(2, 2)
  81. for nn, ax in enumerate(axs.flat):
  82. ax.set_xlabel('Boo')
  83. ax.set_xlabel('Who')
  84. ax.plot(np.arange(4)**nn, np.arange(4)**nn)
  85. fig.align_ylabels()
  86. fig.align_xlabels()
  87. fig.draw_without_rendering()
  88. xn = np.zeros(4)
  89. yn = np.zeros(4)
  90. for nn, ax in enumerate(axs.flat):
  91. yn[nn] = ax.xaxis.label.get_position()[1]
  92. xn[nn] = ax.yaxis.label.get_position()[0]
  93. np.testing.assert_allclose(xn[:2], xn[2:])
  94. np.testing.assert_allclose(yn[::2], yn[1::2])
  95. fig, axs = plt.subplots(2, 2, constrained_layout=True)
  96. for nn, ax in enumerate(axs.flat):
  97. ax.set_xlabel('Boo')
  98. ax.set_xlabel('Who')
  99. pc = ax.pcolormesh(np.random.randn(10, 10))
  100. fig.colorbar(pc, ax=ax)
  101. fig.align_ylabels()
  102. fig.align_xlabels()
  103. fig.draw_without_rendering()
  104. xn = np.zeros(4)
  105. yn = np.zeros(4)
  106. for nn, ax in enumerate(axs.flat):
  107. yn[nn] = ax.xaxis.label.get_position()[1]
  108. xn[nn] = ax.yaxis.label.get_position()[0]
  109. np.testing.assert_allclose(xn[:2], xn[2:])
  110. np.testing.assert_allclose(yn[::2], yn[1::2])
  111. def test_figure_label():
  112. # pyplot figure creation, selection, and closing with label/number/instance
  113. plt.close('all')
  114. fig_today = plt.figure('today')
  115. plt.figure(3)
  116. plt.figure('tomorrow')
  117. plt.figure()
  118. plt.figure(0)
  119. plt.figure(1)
  120. plt.figure(3)
  121. assert plt.get_fignums() == [0, 1, 3, 4, 5]
  122. assert plt.get_figlabels() == ['', 'today', '', 'tomorrow', '']
  123. plt.close(10)
  124. plt.close()
  125. plt.close(5)
  126. plt.close('tomorrow')
  127. assert plt.get_fignums() == [0, 1]
  128. assert plt.get_figlabels() == ['', 'today']
  129. plt.figure(fig_today)
  130. assert plt.gcf() == fig_today
  131. with pytest.raises(ValueError):
  132. plt.figure(Figure())
  133. def test_figure_label_replaced():
  134. plt.close('all')
  135. fig = plt.figure(1)
  136. with pytest.warns(mpl.MatplotlibDeprecationWarning,
  137. match="Changing 'Figure.number' is deprecated"):
  138. fig.number = 2
  139. assert fig.number == 2
  140. def test_figure_no_label():
  141. # standalone figures do not have a figure attribute
  142. fig = Figure()
  143. with pytest.raises(AttributeError):
  144. fig.number
  145. # but one can set one
  146. with pytest.warns(mpl.MatplotlibDeprecationWarning,
  147. match="Changing 'Figure.number' is deprecated"):
  148. fig.number = 5
  149. assert fig.number == 5
  150. # even though it's not known by pyplot
  151. assert not plt.fignum_exists(fig.number)
  152. def test_fignum_exists():
  153. # pyplot figure creation, selection and closing with fignum_exists
  154. plt.figure('one')
  155. plt.figure(2)
  156. plt.figure('three')
  157. plt.figure()
  158. assert plt.fignum_exists('one')
  159. assert plt.fignum_exists(2)
  160. assert plt.fignum_exists('three')
  161. assert plt.fignum_exists(4)
  162. plt.close('one')
  163. plt.close(4)
  164. assert not plt.fignum_exists('one')
  165. assert not plt.fignum_exists(4)
  166. def test_clf_keyword():
  167. # test if existing figure is cleared with figure() and subplots()
  168. text1 = 'A fancy plot'
  169. text2 = 'Really fancy!'
  170. fig0 = plt.figure(num=1)
  171. fig0.suptitle(text1)
  172. assert [t.get_text() for t in fig0.texts] == [text1]
  173. fig1 = plt.figure(num=1, clear=False)
  174. fig1.text(0.5, 0.5, text2)
  175. assert fig0 is fig1
  176. assert [t.get_text() for t in fig1.texts] == [text1, text2]
  177. fig2, ax2 = plt.subplots(2, 1, num=1, clear=True)
  178. assert fig0 is fig2
  179. assert [t.get_text() for t in fig2.texts] == []
  180. @image_comparison(['figure_today.png'],
  181. tol=0 if platform.machine() == 'x86_64' else 0.015)
  182. def test_figure():
  183. # named figure support
  184. fig = plt.figure('today')
  185. ax = fig.add_subplot()
  186. ax.set_title(fig.get_label())
  187. ax.plot(np.arange(5))
  188. # plot red line in a different figure.
  189. plt.figure('tomorrow')
  190. plt.plot([0, 1], [1, 0], 'r')
  191. # Return to the original; make sure the red line is not there.
  192. plt.figure('today')
  193. plt.close('tomorrow')
  194. @image_comparison(['figure_legend.png'])
  195. def test_figure_legend():
  196. fig, axs = plt.subplots(2)
  197. axs[0].plot([0, 1], [1, 0], label='x', color='g')
  198. axs[0].plot([0, 1], [0, 1], label='y', color='r')
  199. axs[0].plot([0, 1], [0.5, 0.5], label='y', color='k')
  200. axs[1].plot([0, 1], [1, 0], label='_y', color='r')
  201. axs[1].plot([0, 1], [0, 1], label='z', color='b')
  202. fig.legend()
  203. def test_gca():
  204. fig = plt.figure()
  205. # test that gca() picks up Axes created via add_axes()
  206. ax0 = fig.add_axes([0, 0, 1, 1])
  207. assert fig.gca() is ax0
  208. # test that gca() picks up Axes created via add_subplot()
  209. ax1 = fig.add_subplot(111)
  210. assert fig.gca() is ax1
  211. # add_axes on an existing Axes should not change stored order, but will
  212. # make it current.
  213. fig.add_axes(ax0)
  214. assert fig.axes == [ax0, ax1]
  215. assert fig.gca() is ax0
  216. # sca() should not change stored order of Axes, which is order added.
  217. fig.sca(ax0)
  218. assert fig.axes == [ax0, ax1]
  219. # add_subplot on an existing Axes should not change stored order, but will
  220. # make it current.
  221. fig.add_subplot(ax1)
  222. assert fig.axes == [ax0, ax1]
  223. assert fig.gca() is ax1
  224. def test_add_subplot_subclass():
  225. fig = plt.figure()
  226. fig.add_subplot(axes_class=Axes)
  227. with pytest.raises(ValueError):
  228. fig.add_subplot(axes_class=Axes, projection="3d")
  229. with pytest.raises(ValueError):
  230. fig.add_subplot(axes_class=Axes, polar=True)
  231. with pytest.raises(ValueError):
  232. fig.add_subplot(projection="3d", polar=True)
  233. with pytest.raises(TypeError):
  234. fig.add_subplot(projection=42)
  235. def test_add_subplot_invalid():
  236. fig = plt.figure()
  237. with pytest.raises(ValueError,
  238. match='Number of columns must be a positive integer'):
  239. fig.add_subplot(2, 0, 1)
  240. with pytest.raises(ValueError,
  241. match='Number of rows must be a positive integer'):
  242. fig.add_subplot(0, 2, 1)
  243. with pytest.raises(ValueError, match='num must be an integer with '
  244. '1 <= num <= 4'):
  245. fig.add_subplot(2, 2, 0)
  246. with pytest.raises(ValueError, match='num must be an integer with '
  247. '1 <= num <= 4'):
  248. fig.add_subplot(2, 2, 5)
  249. with pytest.raises(ValueError, match='num must be an integer with '
  250. '1 <= num <= 4'):
  251. fig.add_subplot(2, 2, 0.5)
  252. with pytest.raises(ValueError, match='must be a three-digit integer'):
  253. fig.add_subplot(42)
  254. with pytest.raises(ValueError, match='must be a three-digit integer'):
  255. fig.add_subplot(1000)
  256. with pytest.raises(TypeError, match='takes 1 or 3 positional arguments '
  257. 'but 2 were given'):
  258. fig.add_subplot(2, 2)
  259. with pytest.raises(TypeError, match='takes 1 or 3 positional arguments '
  260. 'but 4 were given'):
  261. fig.add_subplot(1, 2, 3, 4)
  262. with pytest.raises(ValueError,
  263. match="Number of rows must be a positive integer, "
  264. "not '2'"):
  265. fig.add_subplot('2', 2, 1)
  266. with pytest.raises(ValueError,
  267. match='Number of columns must be a positive integer, '
  268. 'not 2.0'):
  269. fig.add_subplot(2, 2.0, 1)
  270. _, ax = plt.subplots()
  271. with pytest.raises(ValueError,
  272. match='The Axes must have been created in the '
  273. 'present figure'):
  274. fig.add_subplot(ax)
  275. @image_comparison(['figure_suptitle.png'])
  276. def test_suptitle():
  277. fig, _ = plt.subplots()
  278. fig.suptitle('hello', color='r')
  279. fig.suptitle('title', color='g', rotation=30)
  280. def test_suptitle_fontproperties():
  281. fig, ax = plt.subplots()
  282. fps = mpl.font_manager.FontProperties(size='large', weight='bold')
  283. txt = fig.suptitle('fontprops title', fontproperties=fps)
  284. assert txt.get_fontsize() == fps.get_size_in_points()
  285. assert txt.get_weight() == fps.get_weight()
  286. def test_suptitle_subfigures():
  287. fig = plt.figure(figsize=(4, 3))
  288. sf1, sf2 = fig.subfigures(1, 2)
  289. sf2.set_facecolor('white')
  290. sf1.subplots()
  291. sf2.subplots()
  292. fig.suptitle("This is a visible suptitle.")
  293. # verify the first subfigure facecolor is the default transparent
  294. assert sf1.get_facecolor() == (0.0, 0.0, 0.0, 0.0)
  295. # verify the second subfigure facecolor is white
  296. assert sf2.get_facecolor() == (1.0, 1.0, 1.0, 1.0)
  297. def test_get_suptitle_supxlabel_supylabel():
  298. fig, ax = plt.subplots()
  299. assert fig.get_suptitle() == ""
  300. assert fig.get_supxlabel() == ""
  301. assert fig.get_supylabel() == ""
  302. fig.suptitle('suptitle')
  303. assert fig.get_suptitle() == 'suptitle'
  304. fig.supxlabel('supxlabel')
  305. assert fig.get_supxlabel() == 'supxlabel'
  306. fig.supylabel('supylabel')
  307. assert fig.get_supylabel() == 'supylabel'
  308. @image_comparison(['alpha_background'],
  309. # only test png and svg. The PDF output appears correct,
  310. # but Ghostscript does not preserve the background color.
  311. extensions=['png', 'svg'],
  312. savefig_kwarg={'facecolor': (0, 1, 0.4),
  313. 'edgecolor': 'none'})
  314. def test_alpha():
  315. # We want an image which has a background color and an alpha of 0.4.
  316. fig = plt.figure(figsize=[2, 1])
  317. fig.set_facecolor((0, 1, 0.4))
  318. fig.patch.set_alpha(0.4)
  319. fig.patches.append(mpl.patches.CirclePolygon(
  320. [20, 20], radius=15, alpha=0.6, facecolor='red'))
  321. def test_too_many_figures():
  322. with pytest.warns(RuntimeWarning):
  323. for i in range(mpl.rcParams['figure.max_open_warning'] + 1):
  324. plt.figure()
  325. def test_iterability_axes_argument():
  326. # This is a regression test for matplotlib/matplotlib#3196. If one of the
  327. # arguments returned by _as_mpl_axes defines __getitem__ but is not
  328. # iterable, this would raise an exception. This is because we check
  329. # whether the arguments are iterable, and if so we try and convert them
  330. # to a tuple. However, the ``iterable`` function returns True if
  331. # __getitem__ is present, but some classes can define __getitem__ without
  332. # being iterable. The tuple conversion is now done in a try...except in
  333. # case it fails.
  334. class MyAxes(Axes):
  335. def __init__(self, *args, myclass=None, **kwargs):
  336. Axes.__init__(self, *args, **kwargs)
  337. class MyClass:
  338. def __getitem__(self, item):
  339. if item != 'a':
  340. raise ValueError("item should be a")
  341. def _as_mpl_axes(self):
  342. return MyAxes, {'myclass': self}
  343. fig = plt.figure()
  344. fig.add_subplot(1, 1, 1, projection=MyClass())
  345. plt.close(fig)
  346. def test_set_fig_size():
  347. fig = plt.figure()
  348. # check figwidth
  349. fig.set_figwidth(5)
  350. assert fig.get_figwidth() == 5
  351. # check figheight
  352. fig.set_figheight(1)
  353. assert fig.get_figheight() == 1
  354. # check using set_size_inches
  355. fig.set_size_inches(2, 4)
  356. assert fig.get_figwidth() == 2
  357. assert fig.get_figheight() == 4
  358. # check using tuple to first argument
  359. fig.set_size_inches((1, 3))
  360. assert fig.get_figwidth() == 1
  361. assert fig.get_figheight() == 3
  362. def test_axes_remove():
  363. fig, axs = plt.subplots(2, 2)
  364. axs[-1, -1].remove()
  365. for ax in axs.ravel()[:-1]:
  366. assert ax in fig.axes
  367. assert axs[-1, -1] not in fig.axes
  368. assert len(fig.axes) == 3
  369. def test_figaspect():
  370. w, h = plt.figaspect(np.float64(2) / np.float64(1))
  371. assert h / w == 2
  372. w, h = plt.figaspect(2)
  373. assert h / w == 2
  374. w, h = plt.figaspect(np.zeros((1, 2)))
  375. assert h / w == 0.5
  376. w, h = plt.figaspect(np.zeros((2, 2)))
  377. assert h / w == 1
  378. @pytest.mark.parametrize('which', ['both', 'major', 'minor'])
  379. def test_autofmt_xdate(which):
  380. date = ['3 Jan 2013', '4 Jan 2013', '5 Jan 2013', '6 Jan 2013',
  381. '7 Jan 2013', '8 Jan 2013', '9 Jan 2013', '10 Jan 2013',
  382. '11 Jan 2013', '12 Jan 2013', '13 Jan 2013', '14 Jan 2013']
  383. time = ['16:44:00', '16:45:00', '16:46:00', '16:47:00', '16:48:00',
  384. '16:49:00', '16:51:00', '16:52:00', '16:53:00', '16:55:00',
  385. '16:56:00', '16:57:00']
  386. angle = 60
  387. minors = [1, 2, 3, 4, 5, 6, 7]
  388. x = mdates.datestr2num(date)
  389. y = mdates.datestr2num(time)
  390. fig, ax = plt.subplots()
  391. ax.plot(x, y)
  392. ax.yaxis_date()
  393. ax.xaxis_date()
  394. ax.xaxis.set_minor_locator(AutoMinorLocator(2))
  395. with warnings.catch_warnings():
  396. warnings.filterwarnings(
  397. 'ignore',
  398. 'FixedFormatter should only be used together with FixedLocator')
  399. ax.xaxis.set_minor_formatter(FixedFormatter(minors))
  400. fig.autofmt_xdate(0.2, angle, 'right', which)
  401. if which in ('both', 'major'):
  402. for label in fig.axes[0].get_xticklabels(False, 'major'):
  403. assert int(label.get_rotation()) == angle
  404. if which in ('both', 'minor'):
  405. for label in fig.axes[0].get_xticklabels(True, 'minor'):
  406. assert int(label.get_rotation()) == angle
  407. def test_autofmt_xdate_colorbar_constrained():
  408. # check works with a colorbar.
  409. # with constrained layout, colorbars do not have a gridspec,
  410. # but autofmt_xdate checks if all axes have a gridspec before being
  411. # applied.
  412. fig, ax = plt.subplots(layout="constrained")
  413. im = ax.imshow([[1, 4, 6], [2, 3, 5]])
  414. plt.colorbar(im)
  415. fig.autofmt_xdate()
  416. fig.draw_without_rendering()
  417. label = ax.get_xticklabels(which='major')[1]
  418. assert label.get_rotation() == 30.0
  419. @mpl.style.context('default')
  420. def test_change_dpi():
  421. fig = plt.figure(figsize=(4, 4))
  422. fig.draw_without_rendering()
  423. assert fig.canvas.renderer.height == 400
  424. assert fig.canvas.renderer.width == 400
  425. fig.dpi = 50
  426. fig.draw_without_rendering()
  427. assert fig.canvas.renderer.height == 200
  428. assert fig.canvas.renderer.width == 200
  429. @pytest.mark.parametrize('width, height', [
  430. (1, np.nan),
  431. (-1, 1),
  432. (np.inf, 1)
  433. ])
  434. def test_invalid_figure_size(width, height):
  435. with pytest.raises(ValueError):
  436. plt.figure(figsize=(width, height))
  437. fig = plt.figure()
  438. with pytest.raises(ValueError):
  439. fig.set_size_inches(width, height)
  440. def test_invalid_figure_add_axes():
  441. fig = plt.figure()
  442. with pytest.raises(TypeError,
  443. match="missing 1 required positional argument: 'rect'"):
  444. fig.add_axes()
  445. with pytest.raises(ValueError):
  446. fig.add_axes((.1, .1, .5, np.nan))
  447. with pytest.raises(TypeError, match="multiple values for argument 'rect'"):
  448. fig.add_axes([0, 0, 1, 1], rect=[0, 0, 1, 1])
  449. fig2, ax = plt.subplots()
  450. with pytest.raises(ValueError,
  451. match="The Axes must have been created in the present "
  452. "figure"):
  453. fig.add_axes(ax)
  454. fig2.delaxes(ax)
  455. with pytest.raises(TypeError, match=r"add_axes\(\) takes 1 positional arguments"):
  456. fig2.add_axes(ax, "extra positional argument")
  457. with pytest.raises(TypeError, match=r"add_axes\(\) takes 1 positional arguments"):
  458. fig.add_axes([0, 0, 1, 1], "extra positional argument")
  459. def test_subplots_shareax_loglabels():
  460. fig, axs = plt.subplots(2, 2, sharex=True, sharey=True, squeeze=False)
  461. for ax in axs.flat:
  462. ax.plot([10, 20, 30], [10, 20, 30])
  463. ax.set_yscale("log")
  464. ax.set_xscale("log")
  465. for ax in axs[0, :]:
  466. assert 0 == len(ax.xaxis.get_ticklabels(which='both'))
  467. for ax in axs[1, :]:
  468. assert 0 < len(ax.xaxis.get_ticklabels(which='both'))
  469. for ax in axs[:, 1]:
  470. assert 0 == len(ax.yaxis.get_ticklabels(which='both'))
  471. for ax in axs[:, 0]:
  472. assert 0 < len(ax.yaxis.get_ticklabels(which='both'))
  473. def test_savefig():
  474. fig = plt.figure()
  475. msg = r"savefig\(\) takes 2 positional arguments but 3 were given"
  476. with pytest.raises(TypeError, match=msg):
  477. fig.savefig("fname1.png", "fname2.png")
  478. def test_savefig_warns():
  479. fig = plt.figure()
  480. for format in ['png', 'pdf', 'svg', 'tif', 'jpg']:
  481. with pytest.raises(TypeError):
  482. fig.savefig(io.BytesIO(), format=format, non_existent_kwarg=True)
  483. def test_savefig_backend():
  484. fig = plt.figure()
  485. # Intentionally use an invalid module name.
  486. with pytest.raises(ModuleNotFoundError, match="No module named '@absent'"):
  487. fig.savefig("test", backend="module://@absent")
  488. with pytest.raises(ValueError,
  489. match="The 'pdf' backend does not support png output"):
  490. fig.savefig("test.png", backend="pdf")
  491. @pytest.mark.parametrize('backend', [
  492. pytest.param('Agg', marks=[pytest.mark.backend('Agg')]),
  493. pytest.param('Cairo', marks=[pytest.mark.backend('Cairo')]),
  494. ])
  495. def test_savefig_pixel_ratio(backend):
  496. fig, ax = plt.subplots()
  497. ax.plot([1, 2, 3])
  498. with io.BytesIO() as buf:
  499. fig.savefig(buf, format='png')
  500. ratio1 = Image.open(buf)
  501. ratio1.load()
  502. fig, ax = plt.subplots()
  503. ax.plot([1, 2, 3])
  504. fig.canvas._set_device_pixel_ratio(2)
  505. with io.BytesIO() as buf:
  506. fig.savefig(buf, format='png')
  507. ratio2 = Image.open(buf)
  508. ratio2.load()
  509. assert ratio1 == ratio2
  510. def test_savefig_preserve_layout_engine():
  511. fig = plt.figure(layout='compressed')
  512. fig.savefig(io.BytesIO(), bbox_inches='tight')
  513. assert fig.get_layout_engine()._compress
  514. def test_savefig_locate_colorbar():
  515. fig, ax = plt.subplots()
  516. pc = ax.pcolormesh(np.random.randn(2, 2))
  517. cbar = fig.colorbar(pc, aspect=40)
  518. fig.savefig(io.BytesIO(), bbox_inches=mpl.transforms.Bbox([[0, 0], [4, 4]]))
  519. # Check that an aspect ratio has been applied.
  520. assert (cbar.ax.get_position(original=True).bounds !=
  521. cbar.ax.get_position(original=False).bounds)
  522. @mpl.rc_context({"savefig.transparent": True})
  523. @check_figures_equal(extensions=["png"])
  524. def test_savefig_transparent(fig_test, fig_ref):
  525. # create two transparent subfigures with corresponding transparent inset
  526. # axes. the entire background of the image should be transparent.
  527. gs1 = fig_test.add_gridspec(3, 3, left=0.05, wspace=0.05)
  528. f1 = fig_test.add_subfigure(gs1[:, :])
  529. f2 = f1.add_subfigure(gs1[0, 0])
  530. ax12 = f2.add_subplot(gs1[:, :])
  531. ax1 = f1.add_subplot(gs1[:-1, :])
  532. iax1 = ax1.inset_axes([.1, .2, .3, .4])
  533. iax2 = iax1.inset_axes([.1, .2, .3, .4])
  534. ax2 = fig_test.add_subplot(gs1[-1, :-1])
  535. ax3 = fig_test.add_subplot(gs1[-1, -1])
  536. for ax in [ax12, ax1, iax1, iax2, ax2, ax3]:
  537. ax.set(xticks=[], yticks=[])
  538. ax.spines[:].set_visible(False)
  539. def test_figure_repr():
  540. fig = plt.figure(figsize=(10, 20), dpi=10)
  541. assert repr(fig) == "<Figure size 100x200 with 0 Axes>"
  542. def test_valid_layouts():
  543. fig = Figure(layout=None)
  544. assert not fig.get_tight_layout()
  545. assert not fig.get_constrained_layout()
  546. fig = Figure(layout='tight')
  547. assert fig.get_tight_layout()
  548. assert not fig.get_constrained_layout()
  549. fig = Figure(layout='constrained')
  550. assert not fig.get_tight_layout()
  551. assert fig.get_constrained_layout()
  552. def test_invalid_layouts():
  553. fig, ax = plt.subplots(layout="constrained")
  554. with pytest.warns(UserWarning):
  555. # this should warn,
  556. fig.subplots_adjust(top=0.8)
  557. assert isinstance(fig.get_layout_engine(), ConstrainedLayoutEngine)
  558. # Using layout + (tight|constrained)_layout warns, but the former takes
  559. # precedence.
  560. wst = "The Figure parameters 'layout' and 'tight_layout'"
  561. with pytest.warns(UserWarning, match=wst):
  562. fig = Figure(layout='tight', tight_layout=False)
  563. assert isinstance(fig.get_layout_engine(), TightLayoutEngine)
  564. wst = "The Figure parameters 'layout' and 'constrained_layout'"
  565. with pytest.warns(UserWarning, match=wst):
  566. fig = Figure(layout='constrained', constrained_layout=False)
  567. assert not isinstance(fig.get_layout_engine(), TightLayoutEngine)
  568. assert isinstance(fig.get_layout_engine(), ConstrainedLayoutEngine)
  569. with pytest.raises(ValueError,
  570. match="Invalid value for 'layout'"):
  571. Figure(layout='foobar')
  572. # test that layouts can be swapped if no colorbar:
  573. fig, ax = plt.subplots(layout="constrained")
  574. fig.set_layout_engine("tight")
  575. assert isinstance(fig.get_layout_engine(), TightLayoutEngine)
  576. fig.set_layout_engine("constrained")
  577. assert isinstance(fig.get_layout_engine(), ConstrainedLayoutEngine)
  578. # test that layouts cannot be swapped if there is a colorbar:
  579. fig, ax = plt.subplots(layout="constrained")
  580. pc = ax.pcolormesh(np.random.randn(2, 2))
  581. fig.colorbar(pc)
  582. with pytest.raises(RuntimeError, match='Colorbar layout of new layout'):
  583. fig.set_layout_engine("tight")
  584. fig.set_layout_engine("none")
  585. with pytest.raises(RuntimeError, match='Colorbar layout of new layout'):
  586. fig.set_layout_engine("tight")
  587. fig, ax = plt.subplots(layout="tight")
  588. pc = ax.pcolormesh(np.random.randn(2, 2))
  589. fig.colorbar(pc)
  590. with pytest.raises(RuntimeError, match='Colorbar layout of new layout'):
  591. fig.set_layout_engine("constrained")
  592. fig.set_layout_engine("none")
  593. assert isinstance(fig.get_layout_engine(), PlaceHolderLayoutEngine)
  594. with pytest.raises(RuntimeError, match='Colorbar layout of new layout'):
  595. fig.set_layout_engine("constrained")
  596. @check_figures_equal(extensions=["png"])
  597. def test_tightlayout_autolayout_deconflict(fig_test, fig_ref):
  598. for fig, autolayout in zip([fig_ref, fig_test], [False, True]):
  599. with mpl.rc_context({'figure.autolayout': autolayout}):
  600. axes = fig.subplots(ncols=2)
  601. fig.tight_layout(w_pad=10)
  602. assert isinstance(fig.get_layout_engine(), PlaceHolderLayoutEngine)
  603. @pytest.mark.parametrize('layout', ['constrained', 'compressed'])
  604. def test_layout_change_warning(layout):
  605. """
  606. Raise a warning when a previously assigned layout changes to tight using
  607. plt.tight_layout().
  608. """
  609. fig, ax = plt.subplots(layout=layout)
  610. with pytest.warns(UserWarning, match='The figure layout has changed to'):
  611. plt.tight_layout()
  612. def test_repeated_tightlayout():
  613. fig = Figure()
  614. fig.tight_layout()
  615. # subsequent calls should not warn
  616. fig.tight_layout()
  617. fig.tight_layout()
  618. @check_figures_equal(extensions=["png", "pdf"])
  619. def test_add_artist(fig_test, fig_ref):
  620. fig_test.dpi = 100
  621. fig_ref.dpi = 100
  622. fig_test.subplots()
  623. l1 = plt.Line2D([.2, .7], [.7, .7], gid='l1')
  624. l2 = plt.Line2D([.2, .7], [.8, .8], gid='l2')
  625. r1 = plt.Circle((20, 20), 100, transform=None, gid='C1')
  626. r2 = plt.Circle((.7, .5), .05, gid='C2')
  627. r3 = plt.Circle((4.5, .8), .55, transform=fig_test.dpi_scale_trans,
  628. facecolor='crimson', gid='C3')
  629. for a in [l1, l2, r1, r2, r3]:
  630. fig_test.add_artist(a)
  631. l2.remove()
  632. ax2 = fig_ref.subplots()
  633. l1 = plt.Line2D([.2, .7], [.7, .7], transform=fig_ref.transFigure,
  634. gid='l1', zorder=21)
  635. r1 = plt.Circle((20, 20), 100, transform=None, clip_on=False, zorder=20,
  636. gid='C1')
  637. r2 = plt.Circle((.7, .5), .05, transform=fig_ref.transFigure, gid='C2',
  638. zorder=20)
  639. r3 = plt.Circle((4.5, .8), .55, transform=fig_ref.dpi_scale_trans,
  640. facecolor='crimson', clip_on=False, zorder=20, gid='C3')
  641. for a in [l1, r1, r2, r3]:
  642. ax2.add_artist(a)
  643. @pytest.mark.parametrize("fmt", ["png", "pdf", "ps", "eps", "svg"])
  644. def test_fspath(fmt, tmp_path):
  645. out = tmp_path / f"test.{fmt}"
  646. plt.savefig(out)
  647. with out.open("rb") as file:
  648. # All the supported formats include the format name (case-insensitive)
  649. # in the first 100 bytes.
  650. assert fmt.encode("ascii") in file.read(100).lower()
  651. def test_tightbbox():
  652. fig, ax = plt.subplots()
  653. ax.set_xlim(0, 1)
  654. t = ax.text(1., 0.5, 'This dangles over end')
  655. renderer = fig.canvas.get_renderer()
  656. x1Nom0 = 9.035 # inches
  657. assert abs(t.get_tightbbox(renderer).x1 - x1Nom0 * fig.dpi) < 2
  658. assert abs(ax.get_tightbbox(renderer).x1 - x1Nom0 * fig.dpi) < 2
  659. assert abs(fig.get_tightbbox(renderer).x1 - x1Nom0) < 0.05
  660. assert abs(fig.get_tightbbox(renderer).x0 - 0.679) < 0.05
  661. # now exclude t from the tight bbox so now the bbox is quite a bit
  662. # smaller
  663. t.set_in_layout(False)
  664. x1Nom = 7.333
  665. assert abs(ax.get_tightbbox(renderer).x1 - x1Nom * fig.dpi) < 2
  666. assert abs(fig.get_tightbbox(renderer).x1 - x1Nom) < 0.05
  667. t.set_in_layout(True)
  668. x1Nom = 7.333
  669. assert abs(ax.get_tightbbox(renderer).x1 - x1Nom0 * fig.dpi) < 2
  670. # test bbox_extra_artists method...
  671. assert abs(ax.get_tightbbox(renderer, bbox_extra_artists=[]).x1
  672. - x1Nom * fig.dpi) < 2
  673. def test_axes_removal():
  674. # Check that units can set the formatter after an Axes removal
  675. fig, axs = plt.subplots(1, 2, sharex=True)
  676. axs[1].remove()
  677. axs[0].plot([datetime(2000, 1, 1), datetime(2000, 2, 1)], [0, 1])
  678. assert isinstance(axs[0].xaxis.get_major_formatter(),
  679. mdates.AutoDateFormatter)
  680. # Check that manually setting the formatter, then removing Axes keeps
  681. # the set formatter.
  682. fig, axs = plt.subplots(1, 2, sharex=True)
  683. axs[1].xaxis.set_major_formatter(ScalarFormatter())
  684. axs[1].remove()
  685. axs[0].plot([datetime(2000, 1, 1), datetime(2000, 2, 1)], [0, 1])
  686. assert isinstance(axs[0].xaxis.get_major_formatter(),
  687. ScalarFormatter)
  688. def test_removed_axis():
  689. # Simple smoke test to make sure removing a shared axis works
  690. fig, axs = plt.subplots(2, sharex=True)
  691. axs[0].remove()
  692. fig.canvas.draw()
  693. @pytest.mark.parametrize('clear_meth', ['clear', 'clf'])
  694. def test_figure_clear(clear_meth):
  695. # we test the following figure clearing scenarios:
  696. fig = plt.figure()
  697. # a) an empty figure
  698. fig.clear()
  699. assert fig.axes == []
  700. # b) a figure with a single unnested axes
  701. ax = fig.add_subplot(111)
  702. getattr(fig, clear_meth)()
  703. assert fig.axes == []
  704. # c) a figure multiple unnested axes
  705. axes = [fig.add_subplot(2, 1, i+1) for i in range(2)]
  706. getattr(fig, clear_meth)()
  707. assert fig.axes == []
  708. # d) a figure with a subfigure
  709. gs = fig.add_gridspec(ncols=2, nrows=1)
  710. subfig = fig.add_subfigure(gs[0])
  711. subaxes = subfig.add_subplot(111)
  712. getattr(fig, clear_meth)()
  713. assert subfig not in fig.subfigs
  714. assert fig.axes == []
  715. # e) a figure with a subfigure and a subplot
  716. subfig = fig.add_subfigure(gs[0])
  717. subaxes = subfig.add_subplot(111)
  718. mainaxes = fig.add_subplot(gs[1])
  719. # e.1) removing just the axes leaves the subplot
  720. mainaxes.remove()
  721. assert fig.axes == [subaxes]
  722. # e.2) removing just the subaxes leaves the subplot
  723. # and subfigure
  724. mainaxes = fig.add_subplot(gs[1])
  725. subaxes.remove()
  726. assert fig.axes == [mainaxes]
  727. assert subfig in fig.subfigs
  728. # e.3) clearing the subfigure leaves the subplot
  729. subaxes = subfig.add_subplot(111)
  730. assert mainaxes in fig.axes
  731. assert subaxes in fig.axes
  732. getattr(subfig, clear_meth)()
  733. assert subfig in fig.subfigs
  734. assert subaxes not in subfig.axes
  735. assert subaxes not in fig.axes
  736. assert mainaxes in fig.axes
  737. # e.4) clearing the whole thing
  738. subaxes = subfig.add_subplot(111)
  739. getattr(fig, clear_meth)()
  740. assert fig.axes == []
  741. assert fig.subfigs == []
  742. # f) multiple subfigures
  743. subfigs = [fig.add_subfigure(gs[i]) for i in [0, 1]]
  744. subaxes = [sfig.add_subplot(111) for sfig in subfigs]
  745. assert all(ax in fig.axes for ax in subaxes)
  746. assert all(sfig in fig.subfigs for sfig in subfigs)
  747. # f.1) clearing only one subfigure
  748. getattr(subfigs[0], clear_meth)()
  749. assert subaxes[0] not in fig.axes
  750. assert subaxes[1] in fig.axes
  751. assert subfigs[1] in fig.subfigs
  752. # f.2) clearing the whole thing
  753. getattr(subfigs[1], clear_meth)()
  754. subfigs = [fig.add_subfigure(gs[i]) for i in [0, 1]]
  755. subaxes = [sfig.add_subplot(111) for sfig in subfigs]
  756. assert all(ax in fig.axes for ax in subaxes)
  757. assert all(sfig in fig.subfigs for sfig in subfigs)
  758. getattr(fig, clear_meth)()
  759. assert fig.subfigs == []
  760. assert fig.axes == []
  761. def test_clf_not_redefined():
  762. for klass in FigureBase.__subclasses__():
  763. # check that subclasses do not get redefined in our Figure subclasses
  764. assert 'clf' not in klass.__dict__
  765. @mpl.style.context('mpl20')
  766. def test_picking_does_not_stale():
  767. fig, ax = plt.subplots()
  768. ax.scatter([0], [0], [1000], picker=True)
  769. fig.canvas.draw()
  770. assert not fig.stale
  771. mouse_event = SimpleNamespace(x=ax.bbox.x0 + ax.bbox.width / 2,
  772. y=ax.bbox.y0 + ax.bbox.height / 2,
  773. inaxes=ax, guiEvent=None)
  774. fig.pick(mouse_event)
  775. assert not fig.stale
  776. def test_add_subplot_twotuple():
  777. fig = plt.figure()
  778. ax1 = fig.add_subplot(3, 2, (3, 5))
  779. assert ax1.get_subplotspec().rowspan == range(1, 3)
  780. assert ax1.get_subplotspec().colspan == range(0, 1)
  781. ax2 = fig.add_subplot(3, 2, (4, 6))
  782. assert ax2.get_subplotspec().rowspan == range(1, 3)
  783. assert ax2.get_subplotspec().colspan == range(1, 2)
  784. ax3 = fig.add_subplot(3, 2, (3, 6))
  785. assert ax3.get_subplotspec().rowspan == range(1, 3)
  786. assert ax3.get_subplotspec().colspan == range(0, 2)
  787. ax4 = fig.add_subplot(3, 2, (4, 5))
  788. assert ax4.get_subplotspec().rowspan == range(1, 3)
  789. assert ax4.get_subplotspec().colspan == range(0, 2)
  790. with pytest.raises(IndexError):
  791. fig.add_subplot(3, 2, (6, 3))
  792. @image_comparison(['tightbbox_box_aspect.svg'], style='mpl20',
  793. savefig_kwarg={'bbox_inches': 'tight',
  794. 'facecolor': 'teal'},
  795. remove_text=True)
  796. def test_tightbbox_box_aspect():
  797. fig = plt.figure()
  798. gs = fig.add_gridspec(1, 2)
  799. ax1 = fig.add_subplot(gs[0, 0])
  800. ax2 = fig.add_subplot(gs[0, 1], projection='3d')
  801. ax1.set_box_aspect(.5)
  802. ax2.set_box_aspect((2, 1, 1))
  803. @check_figures_equal(extensions=["svg", "pdf", "eps", "png"])
  804. def test_animated_with_canvas_change(fig_test, fig_ref):
  805. ax_ref = fig_ref.subplots()
  806. ax_ref.plot(range(5))
  807. ax_test = fig_test.subplots()
  808. ax_test.plot(range(5), animated=True)
  809. class TestSubplotMosaic:
  810. @check_figures_equal(extensions=["png"])
  811. @pytest.mark.parametrize(
  812. "x", [
  813. [["A", "A", "B"], ["C", "D", "B"]],
  814. [[1, 1, 2], [3, 4, 2]],
  815. (("A", "A", "B"), ("C", "D", "B")),
  816. ((1, 1, 2), (3, 4, 2))
  817. ]
  818. )
  819. def test_basic(self, fig_test, fig_ref, x):
  820. grid_axes = fig_test.subplot_mosaic(x)
  821. for k, ax in grid_axes.items():
  822. ax.set_title(k)
  823. labels = sorted(np.unique(x))
  824. assert len(labels) == len(grid_axes)
  825. gs = fig_ref.add_gridspec(2, 3)
  826. axA = fig_ref.add_subplot(gs[:1, :2])
  827. axA.set_title(labels[0])
  828. axB = fig_ref.add_subplot(gs[:, 2])
  829. axB.set_title(labels[1])
  830. axC = fig_ref.add_subplot(gs[1, 0])
  831. axC.set_title(labels[2])
  832. axD = fig_ref.add_subplot(gs[1, 1])
  833. axD.set_title(labels[3])
  834. @check_figures_equal(extensions=["png"])
  835. def test_all_nested(self, fig_test, fig_ref):
  836. x = [["A", "B"], ["C", "D"]]
  837. y = [["E", "F"], ["G", "H"]]
  838. fig_ref.set_layout_engine("constrained")
  839. fig_test.set_layout_engine("constrained")
  840. grid_axes = fig_test.subplot_mosaic([[x, y]])
  841. for ax in grid_axes.values():
  842. ax.set_title(ax.get_label())
  843. gs = fig_ref.add_gridspec(1, 2)
  844. gs_left = gs[0, 0].subgridspec(2, 2)
  845. for j, r in enumerate(x):
  846. for k, label in enumerate(r):
  847. fig_ref.add_subplot(gs_left[j, k]).set_title(label)
  848. gs_right = gs[0, 1].subgridspec(2, 2)
  849. for j, r in enumerate(y):
  850. for k, label in enumerate(r):
  851. fig_ref.add_subplot(gs_right[j, k]).set_title(label)
  852. @check_figures_equal(extensions=["png"])
  853. def test_nested(self, fig_test, fig_ref):
  854. fig_ref.set_layout_engine("constrained")
  855. fig_test.set_layout_engine("constrained")
  856. x = [["A", "B"], ["C", "D"]]
  857. y = [["F"], [x]]
  858. grid_axes = fig_test.subplot_mosaic(y)
  859. for k, ax in grid_axes.items():
  860. ax.set_title(k)
  861. gs = fig_ref.add_gridspec(2, 1)
  862. gs_n = gs[1, 0].subgridspec(2, 2)
  863. axA = fig_ref.add_subplot(gs_n[0, 0])
  864. axA.set_title("A")
  865. axB = fig_ref.add_subplot(gs_n[0, 1])
  866. axB.set_title("B")
  867. axC = fig_ref.add_subplot(gs_n[1, 0])
  868. axC.set_title("C")
  869. axD = fig_ref.add_subplot(gs_n[1, 1])
  870. axD.set_title("D")
  871. axF = fig_ref.add_subplot(gs[0, 0])
  872. axF.set_title("F")
  873. @check_figures_equal(extensions=["png"])
  874. def test_nested_tuple(self, fig_test, fig_ref):
  875. x = [["A", "B", "B"], ["C", "C", "D"]]
  876. xt = (("A", "B", "B"), ("C", "C", "D"))
  877. fig_ref.subplot_mosaic([["F"], [x]])
  878. fig_test.subplot_mosaic([["F"], [xt]])
  879. def test_nested_width_ratios(self):
  880. x = [["A", [["B"],
  881. ["C"]]]]
  882. width_ratios = [2, 1]
  883. fig, axd = plt.subplot_mosaic(x, width_ratios=width_ratios)
  884. assert axd["A"].get_gridspec().get_width_ratios() == width_ratios
  885. assert axd["B"].get_gridspec().get_width_ratios() != width_ratios
  886. def test_nested_height_ratios(self):
  887. x = [["A", [["B"],
  888. ["C"]]], ["D", "D"]]
  889. height_ratios = [1, 2]
  890. fig, axd = plt.subplot_mosaic(x, height_ratios=height_ratios)
  891. assert axd["D"].get_gridspec().get_height_ratios() == height_ratios
  892. assert axd["B"].get_gridspec().get_height_ratios() != height_ratios
  893. @check_figures_equal(extensions=["png"])
  894. @pytest.mark.parametrize(
  895. "x, empty_sentinel",
  896. [
  897. ([["A", None], [None, "B"]], None),
  898. ([["A", "."], [".", "B"]], "SKIP"),
  899. ([["A", 0], [0, "B"]], 0),
  900. ([[1, None], [None, 2]], None),
  901. ([[1, "."], [".", 2]], "SKIP"),
  902. ([[1, 0], [0, 2]], 0),
  903. ],
  904. )
  905. def test_empty(self, fig_test, fig_ref, x, empty_sentinel):
  906. if empty_sentinel != "SKIP":
  907. kwargs = {"empty_sentinel": empty_sentinel}
  908. else:
  909. kwargs = {}
  910. grid_axes = fig_test.subplot_mosaic(x, **kwargs)
  911. for k, ax in grid_axes.items():
  912. ax.set_title(k)
  913. labels = sorted(
  914. {name for row in x for name in row} - {empty_sentinel, "."}
  915. )
  916. assert len(labels) == len(grid_axes)
  917. gs = fig_ref.add_gridspec(2, 2)
  918. axA = fig_ref.add_subplot(gs[0, 0])
  919. axA.set_title(labels[0])
  920. axB = fig_ref.add_subplot(gs[1, 1])
  921. axB.set_title(labels[1])
  922. def test_fail_list_of_str(self):
  923. with pytest.raises(ValueError, match='must be 2D'):
  924. plt.subplot_mosaic(['foo', 'bar'])
  925. with pytest.raises(ValueError, match='must be 2D'):
  926. plt.subplot_mosaic(['foo'])
  927. with pytest.raises(ValueError, match='must be 2D'):
  928. plt.subplot_mosaic([['foo', ('bar',)]])
  929. with pytest.raises(ValueError, match='must be 2D'):
  930. plt.subplot_mosaic([['a', 'b'], [('a', 'b'), 'c']])
  931. @check_figures_equal(extensions=["png"])
  932. @pytest.mark.parametrize("subplot_kw", [{}, {"projection": "polar"}, None])
  933. def test_subplot_kw(self, fig_test, fig_ref, subplot_kw):
  934. x = [[1, 2]]
  935. grid_axes = fig_test.subplot_mosaic(x, subplot_kw=subplot_kw)
  936. subplot_kw = subplot_kw or {}
  937. gs = fig_ref.add_gridspec(1, 2)
  938. axA = fig_ref.add_subplot(gs[0, 0], **subplot_kw)
  939. axB = fig_ref.add_subplot(gs[0, 1], **subplot_kw)
  940. @check_figures_equal(extensions=["png"])
  941. @pytest.mark.parametrize("multi_value", ['BC', tuple('BC')])
  942. def test_per_subplot_kw(self, fig_test, fig_ref, multi_value):
  943. x = 'AB;CD'
  944. grid_axes = fig_test.subplot_mosaic(
  945. x,
  946. subplot_kw={'facecolor': 'red'},
  947. per_subplot_kw={
  948. 'D': {'facecolor': 'blue'},
  949. multi_value: {'facecolor': 'green'},
  950. }
  951. )
  952. gs = fig_ref.add_gridspec(2, 2)
  953. for color, spec in zip(['red', 'green', 'green', 'blue'], gs):
  954. fig_ref.add_subplot(spec, facecolor=color)
  955. def test_string_parser(self):
  956. normalize = Figure._normalize_grid_string
  957. assert normalize('ABC') == [['A', 'B', 'C']]
  958. assert normalize('AB;CC') == [['A', 'B'], ['C', 'C']]
  959. assert normalize('AB;CC;DE') == [['A', 'B'], ['C', 'C'], ['D', 'E']]
  960. assert normalize("""
  961. ABC
  962. """) == [['A', 'B', 'C']]
  963. assert normalize("""
  964. AB
  965. CC
  966. """) == [['A', 'B'], ['C', 'C']]
  967. assert normalize("""
  968. AB
  969. CC
  970. DE
  971. """) == [['A', 'B'], ['C', 'C'], ['D', 'E']]
  972. def test_per_subplot_kw_expander(self):
  973. normalize = Figure._norm_per_subplot_kw
  974. assert normalize({"A": {}, "B": {}}) == {"A": {}, "B": {}}
  975. assert normalize({("A", "B"): {}}) == {"A": {}, "B": {}}
  976. with pytest.raises(
  977. ValueError, match=f'The key {"B"!r} appears multiple times'
  978. ):
  979. normalize({("A", "B"): {}, "B": {}})
  980. with pytest.raises(
  981. ValueError, match=f'The key {"B"!r} appears multiple times'
  982. ):
  983. normalize({"B": {}, ("A", "B"): {}})
  984. def test_extra_per_subplot_kw(self):
  985. with pytest.raises(
  986. ValueError, match=f'The keys {set("B")!r} are in'
  987. ):
  988. Figure().subplot_mosaic("A", per_subplot_kw={"B": {}})
  989. @check_figures_equal(extensions=["png"])
  990. @pytest.mark.parametrize("str_pattern",
  991. ["AAA\nBBB", "\nAAA\nBBB\n", "ABC\nDEF"]
  992. )
  993. def test_single_str_input(self, fig_test, fig_ref, str_pattern):
  994. grid_axes = fig_test.subplot_mosaic(str_pattern)
  995. grid_axes = fig_ref.subplot_mosaic(
  996. [list(ln) for ln in str_pattern.strip().split("\n")]
  997. )
  998. @pytest.mark.parametrize(
  999. "x,match",
  1000. [
  1001. (
  1002. [["A", "."], [".", "A"]],
  1003. (
  1004. "(?m)we found that the label .A. specifies a "
  1005. + "non-rectangular or non-contiguous area."
  1006. ),
  1007. ),
  1008. (
  1009. [["A", "B"], [None, [["A", "B"], ["C", "D"]]]],
  1010. "There are duplicate keys .* between the outer layout",
  1011. ),
  1012. ("AAA\nc\nBBB", "All of the rows must be the same length"),
  1013. (
  1014. [["A", [["B", "C"], ["D"]]], ["E", "E"]],
  1015. "All of the rows must be the same length",
  1016. ),
  1017. ],
  1018. )
  1019. def test_fail(self, x, match):
  1020. fig = plt.figure()
  1021. with pytest.raises(ValueError, match=match):
  1022. fig.subplot_mosaic(x)
  1023. @check_figures_equal(extensions=["png"])
  1024. def test_hashable_keys(self, fig_test, fig_ref):
  1025. fig_test.subplot_mosaic([[object(), object()]])
  1026. fig_ref.subplot_mosaic([["A", "B"]])
  1027. @pytest.mark.parametrize('str_pattern',
  1028. ['abc', 'cab', 'bca', 'cba', 'acb', 'bac'])
  1029. def test_user_order(self, str_pattern):
  1030. fig = plt.figure()
  1031. ax_dict = fig.subplot_mosaic(str_pattern)
  1032. assert list(str_pattern) == list(ax_dict)
  1033. assert list(fig.axes) == list(ax_dict.values())
  1034. def test_nested_user_order(self):
  1035. layout = [
  1036. ["A", [["B", "C"],
  1037. ["D", "E"]]],
  1038. ["F", "G"],
  1039. [".", [["H", [["I"],
  1040. ["."]]]]]
  1041. ]
  1042. fig = plt.figure()
  1043. ax_dict = fig.subplot_mosaic(layout)
  1044. assert list(ax_dict) == list("ABCDEFGHI")
  1045. assert list(fig.axes) == list(ax_dict.values())
  1046. def test_share_all(self):
  1047. layout = [
  1048. ["A", [["B", "C"],
  1049. ["D", "E"]]],
  1050. ["F", "G"],
  1051. [".", [["H", [["I"],
  1052. ["."]]]]]
  1053. ]
  1054. fig = plt.figure()
  1055. ax_dict = fig.subplot_mosaic(layout, sharex=True, sharey=True)
  1056. ax_dict["A"].set(xscale="log", yscale="logit")
  1057. assert all(ax.get_xscale() == "log" and ax.get_yscale() == "logit"
  1058. for ax in ax_dict.values())
  1059. def test_reused_gridspec():
  1060. """Test that these all use the same gridspec"""
  1061. fig = plt.figure()
  1062. ax1 = fig.add_subplot(3, 2, (3, 5))
  1063. ax2 = fig.add_subplot(3, 2, 4)
  1064. ax3 = plt.subplot2grid((3, 2), (2, 1), colspan=2, fig=fig)
  1065. gs1 = ax1.get_subplotspec().get_gridspec()
  1066. gs2 = ax2.get_subplotspec().get_gridspec()
  1067. gs3 = ax3.get_subplotspec().get_gridspec()
  1068. assert gs1 == gs2
  1069. assert gs1 == gs3
  1070. @image_comparison(['test_subfigure.png'], style='mpl20',
  1071. savefig_kwarg={'facecolor': 'teal'})
  1072. def test_subfigure():
  1073. np.random.seed(19680801)
  1074. fig = plt.figure(layout='constrained')
  1075. sub = fig.subfigures(1, 2)
  1076. axs = sub[0].subplots(2, 2)
  1077. for ax in axs.flat:
  1078. pc = ax.pcolormesh(np.random.randn(30, 30), vmin=-2, vmax=2)
  1079. sub[0].colorbar(pc, ax=axs)
  1080. sub[0].suptitle('Left Side')
  1081. sub[0].set_facecolor('white')
  1082. axs = sub[1].subplots(1, 3)
  1083. for ax in axs.flat:
  1084. pc = ax.pcolormesh(np.random.randn(30, 30), vmin=-2, vmax=2)
  1085. sub[1].colorbar(pc, ax=axs, location='bottom')
  1086. sub[1].suptitle('Right Side')
  1087. sub[1].set_facecolor('white')
  1088. fig.suptitle('Figure suptitle', fontsize='xx-large')
  1089. # below tests for the draw zorder of subfigures.
  1090. leg = fig.legend(handles=[plt.Line2D([0], [0], label='Line{}'.format(i))
  1091. for i in range(5)], loc='center')
  1092. sub[0].set_zorder(leg.get_zorder() - 1)
  1093. sub[1].set_zorder(leg.get_zorder() + 1)
  1094. def test_subfigure_tightbbox():
  1095. # test that we can get the tightbbox with a subfigure...
  1096. fig = plt.figure(layout='constrained')
  1097. sub = fig.subfigures(1, 2)
  1098. np.testing.assert_allclose(
  1099. fig.get_tightbbox(fig.canvas.get_renderer()).width,
  1100. 8.0)
  1101. def test_subfigure_dpi():
  1102. fig = plt.figure(dpi=100)
  1103. sub_fig = fig.subfigures()
  1104. assert sub_fig.get_dpi() == fig.get_dpi()
  1105. sub_fig.set_dpi(200)
  1106. assert sub_fig.get_dpi() == 200
  1107. assert fig.get_dpi() == 200
  1108. @image_comparison(['test_subfigure_ss.png'], style='mpl20',
  1109. savefig_kwarg={'facecolor': 'teal'}, tol=0.02)
  1110. def test_subfigure_ss():
  1111. # test assigning the subfigure via subplotspec
  1112. np.random.seed(19680801)
  1113. fig = plt.figure(layout='constrained')
  1114. gs = fig.add_gridspec(1, 2)
  1115. sub = fig.add_subfigure(gs[0], facecolor='pink')
  1116. axs = sub.subplots(2, 2)
  1117. for ax in axs.flat:
  1118. pc = ax.pcolormesh(np.random.randn(30, 30), vmin=-2, vmax=2)
  1119. sub.colorbar(pc, ax=axs)
  1120. sub.suptitle('Left Side')
  1121. ax = fig.add_subplot(gs[1])
  1122. ax.plot(np.arange(20))
  1123. ax.set_title('Axes')
  1124. fig.suptitle('Figure suptitle', fontsize='xx-large')
  1125. @image_comparison(['test_subfigure_double.png'], style='mpl20',
  1126. savefig_kwarg={'facecolor': 'teal'})
  1127. def test_subfigure_double():
  1128. # test assigning the subfigure via subplotspec
  1129. np.random.seed(19680801)
  1130. fig = plt.figure(layout='constrained', figsize=(10, 8))
  1131. fig.suptitle('fig')
  1132. subfigs = fig.subfigures(1, 2, wspace=0.07)
  1133. subfigs[0].set_facecolor('coral')
  1134. subfigs[0].suptitle('subfigs[0]')
  1135. subfigs[1].set_facecolor('coral')
  1136. subfigs[1].suptitle('subfigs[1]')
  1137. subfigsnest = subfigs[0].subfigures(2, 1, height_ratios=[1, 1.4])
  1138. subfigsnest[0].suptitle('subfigsnest[0]')
  1139. subfigsnest[0].set_facecolor('r')
  1140. axsnest0 = subfigsnest[0].subplots(1, 2, sharey=True)
  1141. for ax in axsnest0:
  1142. fontsize = 12
  1143. pc = ax.pcolormesh(np.random.randn(30, 30), vmin=-2.5, vmax=2.5)
  1144. ax.set_xlabel('x-label', fontsize=fontsize)
  1145. ax.set_ylabel('y-label', fontsize=fontsize)
  1146. ax.set_title('Title', fontsize=fontsize)
  1147. subfigsnest[0].colorbar(pc, ax=axsnest0)
  1148. subfigsnest[1].suptitle('subfigsnest[1]')
  1149. subfigsnest[1].set_facecolor('g')
  1150. axsnest1 = subfigsnest[1].subplots(3, 1, sharex=True)
  1151. for nn, ax in enumerate(axsnest1):
  1152. ax.set_ylabel(f'ylabel{nn}')
  1153. subfigsnest[1].supxlabel('supxlabel')
  1154. subfigsnest[1].supylabel('supylabel')
  1155. axsRight = subfigs[1].subplots(2, 2)
  1156. def test_subfigure_spanning():
  1157. # test that subfigures get laid out properly...
  1158. fig = plt.figure(constrained_layout=True)
  1159. gs = fig.add_gridspec(3, 3)
  1160. sub_figs = [
  1161. fig.add_subfigure(gs[0, 0]),
  1162. fig.add_subfigure(gs[0:2, 1]),
  1163. fig.add_subfigure(gs[2, 1:3]),
  1164. fig.add_subfigure(gs[0:, 1:])
  1165. ]
  1166. w = 640
  1167. h = 480
  1168. np.testing.assert_allclose(sub_figs[0].bbox.min, [0., h * 2/3])
  1169. np.testing.assert_allclose(sub_figs[0].bbox.max, [w / 3, h])
  1170. np.testing.assert_allclose(sub_figs[1].bbox.min, [w / 3, h / 3])
  1171. np.testing.assert_allclose(sub_figs[1].bbox.max, [w * 2/3, h])
  1172. np.testing.assert_allclose(sub_figs[2].bbox.min, [w / 3, 0])
  1173. np.testing.assert_allclose(sub_figs[2].bbox.max, [w, h / 3])
  1174. # check here that slicing actually works. Last sub_fig
  1175. # with open slices failed, but only on draw...
  1176. for i in range(4):
  1177. sub_figs[i].add_subplot()
  1178. fig.draw_without_rendering()
  1179. @mpl.style.context('mpl20')
  1180. def test_subfigure_ticks():
  1181. # This tests a tick-spacing error that only seems applicable
  1182. # when the subfigures are saved to file. It is very hard to replicate
  1183. fig = plt.figure(constrained_layout=True, figsize=(10, 3))
  1184. # create left/right subfigs nested in bottom subfig
  1185. (subfig_bl, subfig_br) = fig.subfigures(1, 2, wspace=0.01,
  1186. width_ratios=[7, 2])
  1187. # put ax1-ax3 in gridspec of bottom-left subfig
  1188. gs = subfig_bl.add_gridspec(nrows=1, ncols=14)
  1189. ax1 = subfig_bl.add_subplot(gs[0, :1])
  1190. ax1.scatter(x=[-56.46881504821776, 24.179891162109396], y=[1500, 3600])
  1191. ax2 = subfig_bl.add_subplot(gs[0, 1:3], sharey=ax1)
  1192. ax2.scatter(x=[-126.5357270050049, 94.68456736755368], y=[1500, 3600])
  1193. ax3 = subfig_bl.add_subplot(gs[0, 3:14], sharey=ax1)
  1194. fig.dpi = 120
  1195. fig.draw_without_rendering()
  1196. ticks120 = ax2.get_xticks()
  1197. fig.dpi = 300
  1198. fig.draw_without_rendering()
  1199. ticks300 = ax2.get_xticks()
  1200. np.testing.assert_allclose(ticks120, ticks300)
  1201. @image_comparison(['test_subfigure_scatter_size.png'], style='mpl20',
  1202. remove_text=True)
  1203. def test_subfigure_scatter_size():
  1204. # markers in the left- and right-most subplots should be the same
  1205. fig = plt.figure()
  1206. gs = fig.add_gridspec(1, 2)
  1207. ax0 = fig.add_subplot(gs[1])
  1208. ax0.scatter([1, 2, 3], [1, 2, 3], s=30, marker='s')
  1209. ax0.scatter([3, 4, 5], [1, 2, 3], s=[20, 30, 40], marker='s')
  1210. sfig = fig.add_subfigure(gs[0])
  1211. axs = sfig.subplots(1, 2)
  1212. for ax in [ax0, axs[0]]:
  1213. ax.scatter([1, 2, 3], [1, 2, 3], s=30, marker='s', color='r')
  1214. ax.scatter([3, 4, 5], [1, 2, 3], s=[20, 30, 40], marker='s', color='g')
  1215. def test_subfigure_pdf():
  1216. fig = plt.figure(layout='constrained')
  1217. sub_fig = fig.subfigures()
  1218. ax = sub_fig.add_subplot(111)
  1219. b = ax.bar(1, 1)
  1220. ax.bar_label(b)
  1221. buffer = io.BytesIO()
  1222. fig.savefig(buffer, format='pdf')
  1223. def test_subfigures_wspace_hspace():
  1224. sub_figs = plt.figure().subfigures(2, 3, hspace=0.5, wspace=1/6.)
  1225. w = 640
  1226. h = 480
  1227. np.testing.assert_allclose(sub_figs[0, 0].bbox.min, [0., h * 0.6])
  1228. np.testing.assert_allclose(sub_figs[0, 0].bbox.max, [w * 0.3, h])
  1229. np.testing.assert_allclose(sub_figs[0, 1].bbox.min, [w * 0.35, h * 0.6])
  1230. np.testing.assert_allclose(sub_figs[0, 1].bbox.max, [w * 0.65, h])
  1231. np.testing.assert_allclose(sub_figs[0, 2].bbox.min, [w * 0.7, h * 0.6])
  1232. np.testing.assert_allclose(sub_figs[0, 2].bbox.max, [w, h])
  1233. np.testing.assert_allclose(sub_figs[1, 0].bbox.min, [0, 0])
  1234. np.testing.assert_allclose(sub_figs[1, 0].bbox.max, [w * 0.3, h * 0.4])
  1235. np.testing.assert_allclose(sub_figs[1, 1].bbox.min, [w * 0.35, 0])
  1236. np.testing.assert_allclose(sub_figs[1, 1].bbox.max, [w * 0.65, h * 0.4])
  1237. np.testing.assert_allclose(sub_figs[1, 2].bbox.min, [w * 0.7, 0])
  1238. np.testing.assert_allclose(sub_figs[1, 2].bbox.max, [w, h * 0.4])
  1239. def test_subfigure_remove():
  1240. fig = plt.figure()
  1241. sfs = fig.subfigures(2, 2)
  1242. sfs[1, 1].remove()
  1243. assert len(fig.subfigs) == 3
  1244. def test_add_subplot_kwargs():
  1245. # fig.add_subplot() always creates new axes, even if axes kwargs differ.
  1246. fig = plt.figure()
  1247. ax = fig.add_subplot(1, 1, 1)
  1248. ax1 = fig.add_subplot(1, 1, 1)
  1249. assert ax is not None
  1250. assert ax1 is not ax
  1251. plt.close()
  1252. fig = plt.figure()
  1253. ax = fig.add_subplot(1, 1, 1, projection='polar')
  1254. ax1 = fig.add_subplot(1, 1, 1, projection='polar')
  1255. assert ax is not None
  1256. assert ax1 is not ax
  1257. plt.close()
  1258. fig = plt.figure()
  1259. ax = fig.add_subplot(1, 1, 1, projection='polar')
  1260. ax1 = fig.add_subplot(1, 1, 1)
  1261. assert ax is not None
  1262. assert ax1.name == 'rectilinear'
  1263. assert ax1 is not ax
  1264. plt.close()
  1265. def test_add_axes_kwargs():
  1266. # fig.add_axes() always creates new axes, even if axes kwargs differ.
  1267. fig = plt.figure()
  1268. ax = fig.add_axes([0, 0, 1, 1])
  1269. ax1 = fig.add_axes([0, 0, 1, 1])
  1270. assert ax is not None
  1271. assert ax1 is not ax
  1272. plt.close()
  1273. fig = plt.figure()
  1274. ax = fig.add_axes([0, 0, 1, 1], projection='polar')
  1275. ax1 = fig.add_axes([0, 0, 1, 1], projection='polar')
  1276. assert ax is not None
  1277. assert ax1 is not ax
  1278. plt.close()
  1279. fig = plt.figure()
  1280. ax = fig.add_axes([0, 0, 1, 1], projection='polar')
  1281. ax1 = fig.add_axes([0, 0, 1, 1])
  1282. assert ax is not None
  1283. assert ax1.name == 'rectilinear'
  1284. assert ax1 is not ax
  1285. plt.close()
  1286. def test_ginput(recwarn): # recwarn undoes warn filters at exit.
  1287. warnings.filterwarnings("ignore", "cannot show the figure")
  1288. fig, ax = plt.subplots()
  1289. trans = ax.transData.transform
  1290. def single_press():
  1291. MouseEvent("button_press_event", fig.canvas, *trans((.1, .2)), 1)._process()
  1292. Timer(.1, single_press).start()
  1293. assert fig.ginput() == [(.1, .2)]
  1294. def multi_presses():
  1295. MouseEvent("button_press_event", fig.canvas, *trans((.1, .2)), 1)._process()
  1296. KeyEvent("key_press_event", fig.canvas, "backspace")._process()
  1297. MouseEvent("button_press_event", fig.canvas, *trans((.3, .4)), 1)._process()
  1298. MouseEvent("button_press_event", fig.canvas, *trans((.5, .6)), 1)._process()
  1299. MouseEvent("button_press_event", fig.canvas, *trans((0, 0)), 2)._process()
  1300. Timer(.1, multi_presses).start()
  1301. np.testing.assert_allclose(fig.ginput(3), [(.3, .4), (.5, .6)])
  1302. def test_waitforbuttonpress(recwarn): # recwarn undoes warn filters at exit.
  1303. warnings.filterwarnings("ignore", "cannot show the figure")
  1304. fig = plt.figure()
  1305. assert fig.waitforbuttonpress(timeout=.1) is None
  1306. Timer(.1, KeyEvent("key_press_event", fig.canvas, "z")._process).start()
  1307. assert fig.waitforbuttonpress() is True
  1308. Timer(.1, MouseEvent("button_press_event", fig.canvas, 0, 0, 1)._process).start()
  1309. assert fig.waitforbuttonpress() is False
  1310. def test_kwargs_pass():
  1311. fig = Figure(label='whole Figure')
  1312. sub_fig = fig.subfigures(1, 1, label='sub figure')
  1313. assert fig.get_label() == 'whole Figure'
  1314. assert sub_fig.get_label() == 'sub figure'
  1315. @check_figures_equal(extensions=["png"])
  1316. def test_rcparams(fig_test, fig_ref):
  1317. fig_ref.supxlabel("xlabel", weight='bold', size=15)
  1318. fig_ref.supylabel("ylabel", weight='bold', size=15)
  1319. fig_ref.suptitle("Title", weight='light', size=20)
  1320. with mpl.rc_context({'figure.labelweight': 'bold',
  1321. 'figure.labelsize': 15,
  1322. 'figure.titleweight': 'light',
  1323. 'figure.titlesize': 20}):
  1324. fig_test.supxlabel("xlabel")
  1325. fig_test.supylabel("ylabel")
  1326. fig_test.suptitle("Title")
  1327. def test_deepcopy():
  1328. fig1, ax = plt.subplots()
  1329. ax.plot([0, 1], [2, 3])
  1330. ax.set_yscale('log')
  1331. fig2 = copy.deepcopy(fig1)
  1332. # Make sure it is a new object
  1333. assert fig2.axes[0] is not ax
  1334. # And that the axis scale got propagated
  1335. assert fig2.axes[0].get_yscale() == 'log'
  1336. # Update the deepcopy and check the original isn't modified
  1337. fig2.axes[0].set_yscale('linear')
  1338. assert ax.get_yscale() == 'log'
  1339. # And test the limits of the axes don't get propagated
  1340. ax.set_xlim(1e-1, 1e2)
  1341. # Draw these to make sure limits are updated
  1342. fig1.draw_without_rendering()
  1343. fig2.draw_without_rendering()
  1344. assert ax.get_xlim() == (1e-1, 1e2)
  1345. assert fig2.axes[0].get_xlim() == (0, 1)
  1346. def test_unpickle_with_device_pixel_ratio():
  1347. fig = Figure(dpi=42)
  1348. fig.canvas._set_device_pixel_ratio(7)
  1349. assert fig.dpi == 42*7
  1350. fig2 = pickle.loads(pickle.dumps(fig))
  1351. assert fig2.dpi == 42
  1352. def test_gridspec_no_mutate_input():
  1353. gs = {'left': .1}
  1354. gs_orig = dict(gs)
  1355. plt.subplots(1, 2, width_ratios=[1, 2], gridspec_kw=gs)
  1356. assert gs == gs_orig
  1357. plt.subplot_mosaic('AB', width_ratios=[1, 2], gridspec_kw=gs)
  1358. @pytest.mark.parametrize('fmt', ['eps', 'pdf', 'png', 'ps', 'svg', 'svgz'])
  1359. def test_savefig_metadata(fmt):
  1360. Figure().savefig(io.BytesIO(), format=fmt, metadata={})
  1361. @pytest.mark.parametrize('fmt', ['jpeg', 'jpg', 'tif', 'tiff', 'webp', "raw", "rgba"])
  1362. def test_savefig_metadata_error(fmt):
  1363. with pytest.raises(ValueError, match="metadata not supported"):
  1364. Figure().savefig(io.BytesIO(), format=fmt, metadata={})
  1365. def test_get_constrained_layout_pads():
  1366. params = {'w_pad': 0.01, 'h_pad': 0.02, 'wspace': 0.03, 'hspace': 0.04}
  1367. expected = tuple([*params.values()])
  1368. fig = plt.figure(layout=mpl.layout_engine.ConstrainedLayoutEngine(**params))
  1369. with pytest.warns(PendingDeprecationWarning, match="will be deprecated"):
  1370. assert fig.get_constrained_layout_pads() == expected
  1371. def test_not_visible_figure():
  1372. fig = Figure()
  1373. buf = io.StringIO()
  1374. fig.savefig(buf, format='svg')
  1375. buf.seek(0)
  1376. assert '<g ' in buf.read()
  1377. fig.set_visible(False)
  1378. buf = io.StringIO()
  1379. fig.savefig(buf, format='svg')
  1380. buf.seek(0)
  1381. assert '<g ' not in buf.read()
  1382. def test_warn_colorbar_mismatch():
  1383. fig1, ax1 = plt.subplots()
  1384. fig2, (ax2_1, ax2_2) = plt.subplots(2)
  1385. im = ax1.imshow([[1, 2], [3, 4]])
  1386. fig1.colorbar(im) # should not warn
  1387. with pytest.warns(UserWarning, match="different Figure"):
  1388. fig2.colorbar(im)
  1389. # warn mismatch even when the host figure is not inferred
  1390. with pytest.warns(UserWarning, match="different Figure"):
  1391. fig2.colorbar(im, ax=ax1)
  1392. with pytest.warns(UserWarning, match="different Figure"):
  1393. fig2.colorbar(im, ax=ax2_1)
  1394. with pytest.warns(UserWarning, match="different Figure"):
  1395. fig2.colorbar(im, cax=ax2_2)
  1396. # edge case: only compare top level artist in case of subfigure
  1397. fig3 = plt.figure()
  1398. fig4 = plt.figure()
  1399. subfig3_1 = fig3.subfigures()
  1400. subfig3_2 = fig3.subfigures()
  1401. subfig4_1 = fig4.subfigures()
  1402. ax3_1 = subfig3_1.subplots()
  1403. ax3_2 = subfig3_1.subplots()
  1404. ax4_1 = subfig4_1.subplots()
  1405. im3_1 = ax3_1.imshow([[1, 2], [3, 4]])
  1406. im3_2 = ax3_2.imshow([[1, 2], [3, 4]])
  1407. im4_1 = ax4_1.imshow([[1, 2], [3, 4]])
  1408. fig3.colorbar(im3_1) # should not warn
  1409. subfig3_1.colorbar(im3_1) # should not warn
  1410. subfig3_1.colorbar(im3_2) # should not warn
  1411. with pytest.warns(UserWarning, match="different Figure"):
  1412. subfig3_1.colorbar(im4_1)
  1413. def test_set_figure():
  1414. fig = plt.figure()
  1415. sfig1 = fig.subfigures()
  1416. sfig2 = sfig1.subfigures()
  1417. for f in fig, sfig1, sfig2:
  1418. with pytest.warns(mpl.MatplotlibDeprecationWarning):
  1419. f.set_figure(fig)
  1420. with pytest.raises(ValueError, match="cannot be changed"):
  1421. sfig2.set_figure(sfig1)
  1422. with pytest.raises(ValueError, match="cannot be changed"):
  1423. sfig1.set_figure(plt.figure())
  1424. def test_subfigure_row_order():
  1425. # Test that subfigures are drawn in row-major order.
  1426. fig = plt.figure()
  1427. sf_arr = fig.subfigures(4, 3)
  1428. for a, b in zip(sf_arr.ravel(), fig.subfigs):
  1429. assert a is b
  1430. def test_subfigure_stale_propagation():
  1431. fig = plt.figure()
  1432. fig.draw_without_rendering()
  1433. assert not fig.stale
  1434. sfig1 = fig.subfigures()
  1435. assert fig.stale
  1436. fig.draw_without_rendering()
  1437. assert not fig.stale
  1438. assert not sfig1.stale
  1439. sfig2 = sfig1.subfigures()
  1440. assert fig.stale
  1441. assert sfig1.stale
  1442. fig.draw_without_rendering()
  1443. assert not fig.stale
  1444. assert not sfig1.stale
  1445. assert not sfig2.stale
  1446. sfig2.stale = True
  1447. assert sfig1.stale
  1448. assert fig.stale