test_figure.py 54 KB

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