_tight_layout.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. """
  2. Routines to adjust subplot params so that subplots are
  3. nicely fit in the figure. In doing so, only axis labels, tick labels, axes
  4. titles and offsetboxes that are anchored to axes are currently considered.
  5. Internally, this module assumes that the margins (left margin, etc.) which are
  6. differences between ``Axes.get_tightbbox`` and ``Axes.bbox`` are independent of
  7. Axes position. This may fail if ``Axes.adjustable`` is ``datalim`` as well as
  8. such cases as when left or right margin are affected by xlabel.
  9. """
  10. import numpy as np
  11. import matplotlib as mpl
  12. from matplotlib import _api, artist as martist
  13. from matplotlib.font_manager import FontProperties
  14. from matplotlib.transforms import Bbox
  15. def _auto_adjust_subplotpars(
  16. fig, renderer, shape, span_pairs, subplot_list,
  17. ax_bbox_list=None, pad=1.08, h_pad=None, w_pad=None, rect=None):
  18. """
  19. Return a dict of subplot parameters to adjust spacing between subplots
  20. or ``None`` if resulting axes would have zero height or width.
  21. Note that this function ignores geometry information of subplot itself, but
  22. uses what is given by the *shape* and *subplot_list* parameters. Also, the
  23. results could be incorrect if some subplots have ``adjustable=datalim``.
  24. Parameters
  25. ----------
  26. shape : tuple[int, int]
  27. Number of rows and columns of the grid.
  28. span_pairs : list[tuple[slice, slice]]
  29. List of rowspans and colspans occupied by each subplot.
  30. subplot_list : list of subplots
  31. List of subplots that will be used to calculate optimal subplot_params.
  32. pad : float
  33. Padding between the figure edge and the edges of subplots, as a
  34. fraction of the font size.
  35. h_pad, w_pad : float
  36. Padding (height/width) between edges of adjacent subplots, as a
  37. fraction of the font size. Defaults to *pad*.
  38. rect : tuple
  39. (left, bottom, right, top), default: None.
  40. """
  41. rows, cols = shape
  42. font_size_inch = (FontProperties(
  43. size=mpl.rcParams["font.size"]).get_size_in_points() / 72)
  44. pad_inch = pad * font_size_inch
  45. vpad_inch = h_pad * font_size_inch if h_pad is not None else pad_inch
  46. hpad_inch = w_pad * font_size_inch if w_pad is not None else pad_inch
  47. if len(span_pairs) != len(subplot_list) or len(subplot_list) == 0:
  48. raise ValueError
  49. if rect is None:
  50. margin_left = margin_bottom = margin_right = margin_top = None
  51. else:
  52. margin_left, margin_bottom, _right, _top = rect
  53. margin_right = 1 - _right if _right else None
  54. margin_top = 1 - _top if _top else None
  55. vspaces = np.zeros((rows + 1, cols))
  56. hspaces = np.zeros((rows, cols + 1))
  57. if ax_bbox_list is None:
  58. ax_bbox_list = [
  59. Bbox.union([ax.get_position(original=True) for ax in subplots])
  60. for subplots in subplot_list]
  61. for subplots, ax_bbox, (rowspan, colspan) in zip(
  62. subplot_list, ax_bbox_list, span_pairs):
  63. if all(not ax.get_visible() for ax in subplots):
  64. continue
  65. bb = []
  66. for ax in subplots:
  67. if ax.get_visible():
  68. bb += [martist._get_tightbbox_for_layout_only(ax, renderer)]
  69. tight_bbox_raw = Bbox.union(bb)
  70. tight_bbox = fig.transFigure.inverted().transform_bbox(tight_bbox_raw)
  71. hspaces[rowspan, colspan.start] += ax_bbox.xmin - tight_bbox.xmin # l
  72. hspaces[rowspan, colspan.stop] += tight_bbox.xmax - ax_bbox.xmax # r
  73. vspaces[rowspan.start, colspan] += tight_bbox.ymax - ax_bbox.ymax # t
  74. vspaces[rowspan.stop, colspan] += ax_bbox.ymin - tight_bbox.ymin # b
  75. fig_width_inch, fig_height_inch = fig.get_size_inches()
  76. # margins can be negative for axes with aspect applied, so use max(, 0) to
  77. # make them nonnegative.
  78. if not margin_left:
  79. margin_left = max(hspaces[:, 0].max(), 0) + pad_inch/fig_width_inch
  80. suplabel = fig._supylabel
  81. if suplabel and suplabel.get_in_layout():
  82. rel_width = fig.transFigure.inverted().transform_bbox(
  83. suplabel.get_window_extent(renderer)).width
  84. margin_left += rel_width + pad_inch/fig_width_inch
  85. if not margin_right:
  86. margin_right = max(hspaces[:, -1].max(), 0) + pad_inch/fig_width_inch
  87. if not margin_top:
  88. margin_top = max(vspaces[0, :].max(), 0) + pad_inch/fig_height_inch
  89. if fig._suptitle and fig._suptitle.get_in_layout():
  90. rel_height = fig.transFigure.inverted().transform_bbox(
  91. fig._suptitle.get_window_extent(renderer)).height
  92. margin_top += rel_height + pad_inch/fig_height_inch
  93. if not margin_bottom:
  94. margin_bottom = max(vspaces[-1, :].max(), 0) + pad_inch/fig_height_inch
  95. suplabel = fig._supxlabel
  96. if suplabel and suplabel.get_in_layout():
  97. rel_height = fig.transFigure.inverted().transform_bbox(
  98. suplabel.get_window_extent(renderer)).height
  99. margin_bottom += rel_height + pad_inch/fig_height_inch
  100. if margin_left + margin_right >= 1:
  101. _api.warn_external('Tight layout not applied. The left and right '
  102. 'margins cannot be made large enough to '
  103. 'accommodate all axes decorations.')
  104. return None
  105. if margin_bottom + margin_top >= 1:
  106. _api.warn_external('Tight layout not applied. The bottom and top '
  107. 'margins cannot be made large enough to '
  108. 'accommodate all axes decorations.')
  109. return None
  110. kwargs = dict(left=margin_left,
  111. right=1 - margin_right,
  112. bottom=margin_bottom,
  113. top=1 - margin_top)
  114. if cols > 1:
  115. hspace = hspaces[:, 1:-1].max() + hpad_inch / fig_width_inch
  116. # axes widths:
  117. h_axes = (1 - margin_right - margin_left - hspace * (cols - 1)) / cols
  118. if h_axes < 0:
  119. _api.warn_external('Tight layout not applied. tight_layout '
  120. 'cannot make axes width small enough to '
  121. 'accommodate all axes decorations')
  122. return None
  123. else:
  124. kwargs["wspace"] = hspace / h_axes
  125. if rows > 1:
  126. vspace = vspaces[1:-1, :].max() + vpad_inch / fig_height_inch
  127. v_axes = (1 - margin_top - margin_bottom - vspace * (rows - 1)) / rows
  128. if v_axes < 0:
  129. _api.warn_external('Tight layout not applied. tight_layout '
  130. 'cannot make axes height small enough to '
  131. 'accommodate all axes decorations.')
  132. return None
  133. else:
  134. kwargs["hspace"] = vspace / v_axes
  135. return kwargs
  136. def get_subplotspec_list(axes_list, grid_spec=None):
  137. """
  138. Return a list of subplotspec from the given list of axes.
  139. For an instance of axes that does not support subplotspec, None is inserted
  140. in the list.
  141. If grid_spec is given, None is inserted for those not from the given
  142. grid_spec.
  143. """
  144. subplotspec_list = []
  145. for ax in axes_list:
  146. axes_or_locator = ax.get_axes_locator()
  147. if axes_or_locator is None:
  148. axes_or_locator = ax
  149. if hasattr(axes_or_locator, "get_subplotspec"):
  150. subplotspec = axes_or_locator.get_subplotspec()
  151. if subplotspec is not None:
  152. subplotspec = subplotspec.get_topmost_subplotspec()
  153. gs = subplotspec.get_gridspec()
  154. if grid_spec is not None:
  155. if gs != grid_spec:
  156. subplotspec = None
  157. elif gs.locally_modified_subplot_params():
  158. subplotspec = None
  159. else:
  160. subplotspec = None
  161. subplotspec_list.append(subplotspec)
  162. return subplotspec_list
  163. def get_tight_layout_figure(fig, axes_list, subplotspec_list, renderer,
  164. pad=1.08, h_pad=None, w_pad=None, rect=None):
  165. """
  166. Return subplot parameters for tight-layouted-figure with specified padding.
  167. Parameters
  168. ----------
  169. fig : Figure
  170. axes_list : list of Axes
  171. subplotspec_list : list of `.SubplotSpec`
  172. The subplotspecs of each axes.
  173. renderer : renderer
  174. pad : float
  175. Padding between the figure edge and the edges of subplots, as a
  176. fraction of the font size.
  177. h_pad, w_pad : float
  178. Padding (height/width) between edges of adjacent subplots. Defaults to
  179. *pad*.
  180. rect : tuple (left, bottom, right, top), default: None.
  181. rectangle in normalized figure coordinates
  182. that the whole subplots area (including labels) will fit into.
  183. Defaults to using the entire figure.
  184. Returns
  185. -------
  186. subplotspec or None
  187. subplotspec kwargs to be passed to `.Figure.subplots_adjust` or
  188. None if tight_layout could not be accomplished.
  189. """
  190. # Multiple axes can share same subplotspec (e.g., if using axes_grid1);
  191. # we need to group them together.
  192. ss_to_subplots = {ss: [] for ss in subplotspec_list}
  193. for ax, ss in zip(axes_list, subplotspec_list):
  194. ss_to_subplots[ss].append(ax)
  195. if ss_to_subplots.pop(None, None):
  196. _api.warn_external(
  197. "This figure includes Axes that are not compatible with "
  198. "tight_layout, so results might be incorrect.")
  199. if not ss_to_subplots:
  200. return {}
  201. subplot_list = list(ss_to_subplots.values())
  202. ax_bbox_list = [ss.get_position(fig) for ss in ss_to_subplots]
  203. max_nrows = max(ss.get_gridspec().nrows for ss in ss_to_subplots)
  204. max_ncols = max(ss.get_gridspec().ncols for ss in ss_to_subplots)
  205. span_pairs = []
  206. for ss in ss_to_subplots:
  207. # The intent here is to support axes from different gridspecs where
  208. # one's nrows (or ncols) is a multiple of the other (e.g. 2 and 4),
  209. # but this doesn't actually work because the computed wspace, in
  210. # relative-axes-height, corresponds to different physical spacings for
  211. # the 2-row grid and the 4-row grid. Still, this code is left, mostly
  212. # for backcompat.
  213. rows, cols = ss.get_gridspec().get_geometry()
  214. div_row, mod_row = divmod(max_nrows, rows)
  215. div_col, mod_col = divmod(max_ncols, cols)
  216. if mod_row != 0:
  217. _api.warn_external('tight_layout not applied: number of rows '
  218. 'in subplot specifications must be '
  219. 'multiples of one another.')
  220. return {}
  221. if mod_col != 0:
  222. _api.warn_external('tight_layout not applied: number of '
  223. 'columns in subplot specifications must be '
  224. 'multiples of one another.')
  225. return {}
  226. span_pairs.append((
  227. slice(ss.rowspan.start * div_row, ss.rowspan.stop * div_row),
  228. slice(ss.colspan.start * div_col, ss.colspan.stop * div_col)))
  229. kwargs = _auto_adjust_subplotpars(fig, renderer,
  230. shape=(max_nrows, max_ncols),
  231. span_pairs=span_pairs,
  232. subplot_list=subplot_list,
  233. ax_bbox_list=ax_bbox_list,
  234. pad=pad, h_pad=h_pad, w_pad=w_pad)
  235. # kwargs can be none if tight_layout fails...
  236. if rect is not None and kwargs is not None:
  237. # if rect is given, the whole subplots area (including
  238. # labels) will fit into the rect instead of the
  239. # figure. Note that the rect argument of
  240. # *auto_adjust_subplotpars* specify the area that will be
  241. # covered by the total area of axes.bbox. Thus we call
  242. # auto_adjust_subplotpars twice, where the second run
  243. # with adjusted rect parameters.
  244. left, bottom, right, top = rect
  245. if left is not None:
  246. left += kwargs["left"]
  247. if bottom is not None:
  248. bottom += kwargs["bottom"]
  249. if right is not None:
  250. right -= (1 - kwargs["right"])
  251. if top is not None:
  252. top -= (1 - kwargs["top"])
  253. kwargs = _auto_adjust_subplotpars(fig, renderer,
  254. shape=(max_nrows, max_ncols),
  255. span_pairs=span_pairs,
  256. subplot_list=subplot_list,
  257. ax_bbox_list=ax_bbox_list,
  258. pad=pad, h_pad=h_pad, w_pad=w_pad,
  259. rect=(left, bottom, right, top))
  260. return kwargs