test_tightlayout.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. import warnings
  2. import numpy as np
  3. from numpy.testing import assert_array_equal
  4. import pytest
  5. import matplotlib as mpl
  6. from matplotlib.testing.decorators import image_comparison
  7. import matplotlib.pyplot as plt
  8. from matplotlib.offsetbox import AnchoredOffsetbox, DrawingArea
  9. from matplotlib.patches import Rectangle
  10. def example_plot(ax, fontsize=12):
  11. ax.plot([1, 2])
  12. ax.locator_params(nbins=3)
  13. ax.set_xlabel('x-label', fontsize=fontsize)
  14. ax.set_ylabel('y-label', fontsize=fontsize)
  15. ax.set_title('Title', fontsize=fontsize)
  16. @image_comparison(['tight_layout1'], tol=1.9)
  17. def test_tight_layout1():
  18. """Test tight_layout for a single subplot."""
  19. fig, ax = plt.subplots()
  20. example_plot(ax, fontsize=24)
  21. plt.tight_layout()
  22. @image_comparison(['tight_layout2'])
  23. def test_tight_layout2():
  24. """Test tight_layout for multiple subplots."""
  25. fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
  26. example_plot(ax1)
  27. example_plot(ax2)
  28. example_plot(ax3)
  29. example_plot(ax4)
  30. plt.tight_layout()
  31. @image_comparison(['tight_layout3'])
  32. def test_tight_layout3():
  33. """Test tight_layout for multiple subplots."""
  34. ax1 = plt.subplot(221)
  35. ax2 = plt.subplot(223)
  36. ax3 = plt.subplot(122)
  37. example_plot(ax1)
  38. example_plot(ax2)
  39. example_plot(ax3)
  40. plt.tight_layout()
  41. @image_comparison(['tight_layout4'], freetype_version=('2.5.5', '2.6.1'),
  42. tol=0.015)
  43. def test_tight_layout4():
  44. """Test tight_layout for subplot2grid."""
  45. ax1 = plt.subplot2grid((3, 3), (0, 0))
  46. ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)
  47. ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
  48. ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
  49. example_plot(ax1)
  50. example_plot(ax2)
  51. example_plot(ax3)
  52. example_plot(ax4)
  53. plt.tight_layout()
  54. @image_comparison(['tight_layout5'])
  55. def test_tight_layout5():
  56. """Test tight_layout for image."""
  57. ax = plt.subplot()
  58. arr = np.arange(100).reshape((10, 10))
  59. ax.imshow(arr, interpolation="none")
  60. plt.tight_layout()
  61. @image_comparison(['tight_layout6'])
  62. def test_tight_layout6():
  63. """Test tight_layout for gridspec."""
  64. # This raises warnings since tight layout cannot
  65. # do this fully automatically. But the test is
  66. # correct since the layout is manually edited
  67. with warnings.catch_warnings():
  68. warnings.simplefilter("ignore", UserWarning)
  69. fig = plt.figure()
  70. gs1 = mpl.gridspec.GridSpec(2, 1)
  71. ax1 = fig.add_subplot(gs1[0])
  72. ax2 = fig.add_subplot(gs1[1])
  73. example_plot(ax1)
  74. example_plot(ax2)
  75. gs1.tight_layout(fig, rect=[0, 0, 0.5, 1])
  76. gs2 = mpl.gridspec.GridSpec(3, 1)
  77. for ss in gs2:
  78. ax = fig.add_subplot(ss)
  79. example_plot(ax)
  80. ax.set_title("")
  81. ax.set_xlabel("")
  82. ax.set_xlabel("x-label", fontsize=12)
  83. gs2.tight_layout(fig, rect=[0.5, 0, 1, 1], h_pad=0.45)
  84. top = min(gs1.top, gs2.top)
  85. bottom = max(gs1.bottom, gs2.bottom)
  86. gs1.tight_layout(fig, rect=[None, 0 + (bottom-gs1.bottom),
  87. 0.5, 1 - (gs1.top-top)])
  88. gs2.tight_layout(fig, rect=[0.5, 0 + (bottom-gs2.bottom),
  89. None, 1 - (gs2.top-top)],
  90. h_pad=0.45)
  91. @image_comparison(['tight_layout7'], tol=1.9)
  92. def test_tight_layout7():
  93. # tight layout with left and right titles
  94. fontsize = 24
  95. fig, ax = plt.subplots()
  96. ax.plot([1, 2])
  97. ax.locator_params(nbins=3)
  98. ax.set_xlabel('x-label', fontsize=fontsize)
  99. ax.set_ylabel('y-label', fontsize=fontsize)
  100. ax.set_title('Left Title', loc='left', fontsize=fontsize)
  101. ax.set_title('Right Title', loc='right', fontsize=fontsize)
  102. plt.tight_layout()
  103. @image_comparison(['tight_layout8'])
  104. def test_tight_layout8():
  105. """Test automatic use of tight_layout."""
  106. fig = plt.figure()
  107. fig.set_layout_engine(layout='tight', pad=0.1)
  108. ax = fig.add_subplot()
  109. example_plot(ax, fontsize=24)
  110. fig.draw_without_rendering()
  111. @image_comparison(['tight_layout9'])
  112. def test_tight_layout9():
  113. # Test tight_layout for non-visible subplots
  114. # GH 8244
  115. f, axarr = plt.subplots(2, 2)
  116. axarr[1][1].set_visible(False)
  117. plt.tight_layout()
  118. def test_outward_ticks():
  119. """Test automatic use of tight_layout."""
  120. fig = plt.figure()
  121. ax = fig.add_subplot(221)
  122. ax.xaxis.set_tick_params(tickdir='out', length=16, width=3)
  123. ax.yaxis.set_tick_params(tickdir='out', length=16, width=3)
  124. ax.xaxis.set_tick_params(
  125. tickdir='out', length=32, width=3, tick1On=True, which='minor')
  126. ax.yaxis.set_tick_params(
  127. tickdir='out', length=32, width=3, tick1On=True, which='minor')
  128. ax.xaxis.set_ticks([0], minor=True)
  129. ax.yaxis.set_ticks([0], minor=True)
  130. ax = fig.add_subplot(222)
  131. ax.xaxis.set_tick_params(tickdir='in', length=32, width=3)
  132. ax.yaxis.set_tick_params(tickdir='in', length=32, width=3)
  133. ax = fig.add_subplot(223)
  134. ax.xaxis.set_tick_params(tickdir='inout', length=32, width=3)
  135. ax.yaxis.set_tick_params(tickdir='inout', length=32, width=3)
  136. ax = fig.add_subplot(224)
  137. ax.xaxis.set_tick_params(tickdir='out', length=32, width=3)
  138. ax.yaxis.set_tick_params(tickdir='out', length=32, width=3)
  139. plt.tight_layout()
  140. # These values were obtained after visual checking that they correspond
  141. # to a tight layouting that did take the ticks into account.
  142. ans = [[[0.091, 0.607], [0.433, 0.933]],
  143. [[0.579, 0.607], [0.922, 0.933]],
  144. [[0.091, 0.140], [0.433, 0.466]],
  145. [[0.579, 0.140], [0.922, 0.466]]]
  146. for nn, ax in enumerate(fig.axes):
  147. assert_array_equal(np.round(ax.get_position().get_points(), 3),
  148. ans[nn])
  149. def add_offsetboxes(ax, size=10, margin=.1, color='black'):
  150. """
  151. Surround ax with OffsetBoxes
  152. """
  153. m, mp = margin, 1+margin
  154. anchor_points = [(-m, -m), (-m, .5), (-m, mp),
  155. (mp, .5), (.5, mp), (mp, mp),
  156. (.5, -m), (mp, -m), (.5, -m)]
  157. for point in anchor_points:
  158. da = DrawingArea(size, size)
  159. background = Rectangle((0, 0), width=size,
  160. height=size,
  161. facecolor=color,
  162. edgecolor='None',
  163. linewidth=0,
  164. antialiased=False)
  165. da.add_artist(background)
  166. anchored_box = AnchoredOffsetbox(
  167. loc='center',
  168. child=da,
  169. pad=0.,
  170. frameon=False,
  171. bbox_to_anchor=point,
  172. bbox_transform=ax.transAxes,
  173. borderpad=0.)
  174. ax.add_artist(anchored_box)
  175. return anchored_box
  176. @image_comparison(['tight_layout_offsetboxes1', 'tight_layout_offsetboxes2'])
  177. def test_tight_layout_offsetboxes():
  178. # 1.
  179. # - Create 4 subplots
  180. # - Plot a diagonal line on them
  181. # - Surround each plot with 7 boxes
  182. # - Use tight_layout
  183. # - See that the squares are included in the tight_layout
  184. # and that the squares in the middle do not overlap
  185. #
  186. # 2.
  187. # - Make the squares around the right side axes invisible
  188. # - See that the invisible squares do not affect the
  189. # tight_layout
  190. rows = cols = 2
  191. colors = ['red', 'blue', 'green', 'yellow']
  192. x = y = [0, 1]
  193. def _subplots():
  194. _, axs = plt.subplots(rows, cols)
  195. axs = axs.flat
  196. for ax, color in zip(axs, colors):
  197. ax.plot(x, y, color=color)
  198. add_offsetboxes(ax, 20, color=color)
  199. return axs
  200. # 1.
  201. axs = _subplots()
  202. plt.tight_layout()
  203. # 2.
  204. axs = _subplots()
  205. for ax in (axs[cols-1::rows]):
  206. for child in ax.get_children():
  207. if isinstance(child, AnchoredOffsetbox):
  208. child.set_visible(False)
  209. plt.tight_layout()
  210. def test_empty_layout():
  211. """Test that tight layout doesn't cause an error when there are no axes."""
  212. fig = plt.gcf()
  213. fig.tight_layout()
  214. @pytest.mark.parametrize("label", ["xlabel", "ylabel"])
  215. def test_verybig_decorators(label):
  216. """Test that no warning emitted when xlabel/ylabel too big."""
  217. fig, ax = plt.subplots(figsize=(3, 2))
  218. ax.set(**{label: 'a' * 100})
  219. def test_big_decorators_horizontal():
  220. """Test that doesn't warn when xlabel too big."""
  221. fig, axs = plt.subplots(1, 2, figsize=(3, 2))
  222. axs[0].set_xlabel('a' * 30)
  223. axs[1].set_xlabel('b' * 30)
  224. def test_big_decorators_vertical():
  225. """Test that doesn't warn when ylabel too big."""
  226. fig, axs = plt.subplots(2, 1, figsize=(3, 2))
  227. axs[0].set_ylabel('a' * 20)
  228. axs[1].set_ylabel('b' * 20)
  229. def test_badsubplotgrid():
  230. # test that we get warning for mismatched subplot grids, not than an error
  231. plt.subplot2grid((4, 5), (0, 0))
  232. # this is the bad entry:
  233. plt.subplot2grid((5, 5), (0, 3), colspan=3, rowspan=5)
  234. with pytest.warns(UserWarning):
  235. plt.tight_layout()
  236. def test_collapsed():
  237. # test that if the amount of space required to make all the axes
  238. # decorations fit would mean that the actual Axes would end up with size
  239. # zero (i.e. margins add up to more than the available width) that a call
  240. # to tight_layout will not get applied:
  241. fig, ax = plt.subplots(tight_layout=True)
  242. ax.set_xlim([0, 1])
  243. ax.set_ylim([0, 1])
  244. ax.annotate('BIG LONG STRING', xy=(1.25, 2), xytext=(10.5, 1.75),
  245. annotation_clip=False)
  246. p1 = ax.get_position()
  247. with pytest.warns(UserWarning):
  248. plt.tight_layout()
  249. p2 = ax.get_position()
  250. assert p1.width == p2.width
  251. # test that passing a rect doesn't crash...
  252. with pytest.warns(UserWarning):
  253. plt.tight_layout(rect=[0, 0, 0.8, 0.8])
  254. def test_suptitle():
  255. fig, ax = plt.subplots(tight_layout=True)
  256. st = fig.suptitle("foo")
  257. t = ax.set_title("bar")
  258. fig.canvas.draw()
  259. assert st.get_window_extent().y0 > t.get_window_extent().y1
  260. @pytest.mark.backend("pdf")
  261. def test_non_agg_renderer(monkeypatch, recwarn):
  262. unpatched_init = mpl.backend_bases.RendererBase.__init__
  263. def __init__(self, *args, **kwargs):
  264. # Check that we don't instantiate any other renderer than a pdf
  265. # renderer to perform pdf tight layout.
  266. assert isinstance(self, mpl.backends.backend_pdf.RendererPdf)
  267. unpatched_init(self, *args, **kwargs)
  268. monkeypatch.setattr(mpl.backend_bases.RendererBase, "__init__", __init__)
  269. fig, ax = plt.subplots()
  270. fig.tight_layout()
  271. def test_manual_colorbar():
  272. # This should warn, but not raise
  273. fig, axes = plt.subplots(1, 2)
  274. pts = axes[1].scatter([0, 1], [0, 1], c=[1, 5])
  275. ax_rect = axes[1].get_position()
  276. cax = fig.add_axes(
  277. [ax_rect.x1 + 0.005, ax_rect.y0, 0.015, ax_rect.height]
  278. )
  279. fig.colorbar(pts, cax=cax)
  280. with pytest.warns(UserWarning, match="This figure includes Axes"):
  281. fig.tight_layout()
  282. def test_clipped_to_axes():
  283. # Ensure that _fully_clipped_to_axes() returns True under default
  284. # conditions for all projection types. Axes.get_tightbbox()
  285. # uses this to skip artists in layout calculations.
  286. arr = np.arange(100).reshape((10, 10))
  287. fig = plt.figure(figsize=(6, 2))
  288. ax1 = fig.add_subplot(131, projection='rectilinear')
  289. ax2 = fig.add_subplot(132, projection='mollweide')
  290. ax3 = fig.add_subplot(133, projection='polar')
  291. for ax in (ax1, ax2, ax3):
  292. # Default conditions (clipped by ax.bbox or ax.patch)
  293. ax.grid(False)
  294. h, = ax.plot(arr[:, 0])
  295. m = ax.pcolor(arr)
  296. assert h._fully_clipped_to_axes()
  297. assert m._fully_clipped_to_axes()
  298. # Non-default conditions (not clipped by ax.patch)
  299. rect = Rectangle((0, 0), 0.5, 0.5, transform=ax.transAxes)
  300. h.set_clip_path(rect)
  301. m.set_clip_path(rect.get_path(), rect.get_transform())
  302. assert not h._fully_clipped_to_axes()
  303. assert not m._fully_clipped_to_axes()
  304. def test_tight_pads():
  305. fig, ax = plt.subplots()
  306. with pytest.warns(PendingDeprecationWarning,
  307. match='will be deprecated'):
  308. fig.set_tight_layout({'pad': 0.15})
  309. fig.draw_without_rendering()
  310. def test_tight_kwargs():
  311. fig, ax = plt.subplots(tight_layout={'pad': 0.15})
  312. fig.draw_without_rendering()
  313. def test_tight_toggle():
  314. fig, ax = plt.subplots()
  315. with pytest.warns(PendingDeprecationWarning):
  316. fig.set_tight_layout(True)
  317. assert fig.get_tight_layout()
  318. fig.set_tight_layout(False)
  319. assert not fig.get_tight_layout()
  320. fig.set_tight_layout(True)
  321. assert fig.get_tight_layout()