tight_layout.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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 ax.get_tightbbox and ax.bbox are independent of axes
  7. position. This may fail if Axes.adjustable is datalim. Also, This will fail
  8. for some cases (for example, left or right margin is affected by xlabel).
  9. """
  10. import numpy as np
  11. from matplotlib import cbook, rcParams
  12. from matplotlib.font_manager import FontProperties
  13. from matplotlib.transforms import TransformedBbox, Bbox
  14. def auto_adjust_subplotpars(
  15. fig, renderer, nrows_ncols, num1num2_list, subplot_list,
  16. ax_bbox_list=None, pad=1.08, h_pad=None, w_pad=None, rect=None):
  17. """
  18. Return a dict of subplot parameters to adjust spacing between subplots
  19. or ``None`` if resulting axes would have zero height or width.
  20. Note that this function ignores geometry information of subplot
  21. itself, but uses what is given by the *nrows_ncols* and *num1num2_list*
  22. parameters. Also, the results could be incorrect if some subplots have
  23. ``adjustable=datalim``.
  24. Parameters
  25. ----------
  26. nrows_ncols : Tuple[int, int]
  27. Number of rows and number of columns of the grid.
  28. num1num2_list : List[int]
  29. List of numbers specifying the area occupied by the 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[float, float, float, float]
  39. [left, bottom, right, top] in normalized (0, 1) figure coordinates.
  40. """
  41. rows, cols = nrows_ncols
  42. font_size_inches = (
  43. FontProperties(size=rcParams["font.size"]).get_size_in_points() / 72)
  44. pad_inches = pad * font_size_inches
  45. vpad_inches = h_pad * font_size_inches if h_pad is not None else pad_inches
  46. hpad_inches = w_pad * font_size_inches if w_pad is not None else pad_inches
  47. if len(num1num2_list) != 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, (num1, num2) in zip(subplot_list,
  62. ax_bbox_list,
  63. num1num2_list):
  64. if all(not ax.get_visible() for ax in subplots):
  65. continue
  66. bb = []
  67. for ax in subplots:
  68. if ax.get_visible():
  69. try:
  70. bb += [ax.get_tightbbox(renderer, for_layout_only=True)]
  71. except TypeError:
  72. bb += [ax.get_tightbbox(renderer)]
  73. tight_bbox_raw = Bbox.union(bb)
  74. tight_bbox = TransformedBbox(tight_bbox_raw,
  75. fig.transFigure.inverted())
  76. row1, col1 = divmod(num1, cols)
  77. if num2 is None:
  78. num2 = num1
  79. row2, col2 = divmod(num2, cols)
  80. for row_i in range(row1, row2 + 1):
  81. hspaces[row_i, col1] += ax_bbox.xmin - tight_bbox.xmin # left
  82. hspaces[row_i, col2 + 1] += tight_bbox.xmax - ax_bbox.xmax # right
  83. for col_i in range(col1, col2 + 1):
  84. vspaces[row1, col_i] += tight_bbox.ymax - ax_bbox.ymax # top
  85. vspaces[row2 + 1, col_i] += ax_bbox.ymin - tight_bbox.ymin # bot.
  86. fig_width_inch, fig_height_inch = fig.get_size_inches()
  87. # margins can be negative for axes with aspect applied, so use max(, 0) to
  88. # make them nonnegative.
  89. if not margin_left:
  90. margin_left = (max(hspaces[:, 0].max(), 0)
  91. + pad_inches / fig_width_inch)
  92. if not margin_right:
  93. margin_right = (max(hspaces[:, -1].max(), 0)
  94. + pad_inches / fig_width_inch)
  95. if not margin_top:
  96. margin_top = (max(vspaces[0, :].max(), 0)
  97. + pad_inches / fig_height_inch)
  98. suptitle = fig._suptitle
  99. if suptitle and suptitle.get_in_layout():
  100. rel_suptitle_height = fig.transFigure.inverted().transform_bbox(
  101. suptitle.get_window_extent(renderer)).height
  102. margin_top += rel_suptitle_height + pad_inches / fig_height_inch
  103. if not margin_bottom:
  104. margin_bottom = (max(vspaces[-1, :].max(), 0)
  105. + pad_inches / fig_height_inch)
  106. if margin_left + margin_right >= 1:
  107. cbook._warn_external('Tight layout not applied. The left and right '
  108. 'margins cannot be made large enough to '
  109. 'accommodate all axes decorations. ')
  110. return None
  111. if margin_bottom + margin_top >= 1:
  112. cbook._warn_external('Tight layout not applied. The bottom and top '
  113. 'margins cannot be made large enough to '
  114. 'accommodate all axes decorations. ')
  115. return None
  116. kwargs = dict(left=margin_left,
  117. right=1 - margin_right,
  118. bottom=margin_bottom,
  119. top=1 - margin_top)
  120. if cols > 1:
  121. hspace = hspaces[:, 1:-1].max() + hpad_inches / fig_width_inch
  122. # axes widths:
  123. h_axes = (1 - margin_right - margin_left - hspace * (cols - 1)) / cols
  124. if h_axes < 0:
  125. cbook._warn_external('Tight layout not applied. tight_layout '
  126. 'cannot make axes width small enough to '
  127. 'accommodate all axes decorations')
  128. return None
  129. else:
  130. kwargs["wspace"] = hspace / h_axes
  131. if rows > 1:
  132. vspace = vspaces[1:-1, :].max() + vpad_inches / fig_height_inch
  133. v_axes = (1 - margin_top - margin_bottom - vspace * (rows - 1)) / rows
  134. if v_axes < 0:
  135. cbook._warn_external('Tight layout not applied. tight_layout '
  136. 'cannot make axes height small enough to '
  137. 'accommodate all axes decorations')
  138. return None
  139. else:
  140. kwargs["hspace"] = vspace / v_axes
  141. return kwargs
  142. def get_renderer(fig):
  143. if fig._cachedRenderer:
  144. return fig._cachedRenderer
  145. else:
  146. canvas = fig.canvas
  147. if canvas and hasattr(canvas, "get_renderer"):
  148. return canvas.get_renderer()
  149. else:
  150. from . import backend_bases
  151. return backend_bases._get_renderer(fig)
  152. def get_subplotspec_list(axes_list, grid_spec=None):
  153. """
  154. Return a list of subplotspec from the given list of axes.
  155. For an instance of axes that does not support subplotspec, None is inserted
  156. in the list.
  157. If grid_spec is given, None is inserted for those not from the given
  158. grid_spec.
  159. """
  160. subplotspec_list = []
  161. for ax in axes_list:
  162. axes_or_locator = ax.get_axes_locator()
  163. if axes_or_locator is None:
  164. axes_or_locator = ax
  165. if hasattr(axes_or_locator, "get_subplotspec"):
  166. subplotspec = axes_or_locator.get_subplotspec()
  167. subplotspec = subplotspec.get_topmost_subplotspec()
  168. gs = subplotspec.get_gridspec()
  169. if grid_spec is not None:
  170. if gs != grid_spec:
  171. subplotspec = None
  172. elif gs.locally_modified_subplot_params():
  173. subplotspec = None
  174. else:
  175. subplotspec = None
  176. subplotspec_list.append(subplotspec)
  177. return subplotspec_list
  178. def get_tight_layout_figure(fig, axes_list, subplotspec_list, renderer,
  179. pad=1.08, h_pad=None, w_pad=None, rect=None):
  180. """
  181. Return subplot parameters for tight-layouted-figure with specified padding.
  182. Parameters
  183. ----------
  184. fig : Figure
  185. axes_list : list of Axes
  186. subplotspec_list : list of `.SubplotSpec`
  187. The subplotspecs of each axes.
  188. renderer : renderer
  189. pad : float
  190. Padding between the figure edge and the edges of subplots, as a
  191. fraction of the font size.
  192. h_pad, w_pad : float
  193. Padding (height/width) between edges of adjacent subplots. Defaults to
  194. *pad*.
  195. rect : Tuple[float, float, float, float], optional
  196. (left, bottom, right, top) rectangle in normalized figure coordinates
  197. that the whole subplots area (including labels) will fit into.
  198. Defaults to using the entire figure.
  199. Returns
  200. -------
  201. subplotspec or None
  202. subplotspec kwargs to be passed to `.Figure.subplots_adjust` or
  203. None if tight_layout could not be accomplished.
  204. """
  205. subplot_list = []
  206. nrows_list = []
  207. ncols_list = []
  208. ax_bbox_list = []
  209. # Multiple axes can share same subplot_interface (e.g., axes_grid1); thus
  210. # we need to join them together.
  211. subplot_dict = {}
  212. subplotspec_list2 = []
  213. for ax, subplotspec in zip(axes_list, subplotspec_list):
  214. if subplotspec is None:
  215. continue
  216. subplots = subplot_dict.setdefault(subplotspec, [])
  217. if not subplots:
  218. myrows, mycols, _, _ = subplotspec.get_geometry()
  219. nrows_list.append(myrows)
  220. ncols_list.append(mycols)
  221. subplotspec_list2.append(subplotspec)
  222. subplot_list.append(subplots)
  223. ax_bbox_list.append(subplotspec.get_position(fig))
  224. subplots.append(ax)
  225. if len(nrows_list) == 0 or len(ncols_list) == 0:
  226. return {}
  227. max_nrows = max(nrows_list)
  228. max_ncols = max(ncols_list)
  229. num1num2_list = []
  230. for subplotspec in subplotspec_list2:
  231. rows, cols, num1, num2 = subplotspec.get_geometry()
  232. div_row, mod_row = divmod(max_nrows, rows)
  233. div_col, mod_col = divmod(max_ncols, cols)
  234. if mod_row != 0:
  235. cbook._warn_external('tight_layout not applied: number of rows '
  236. 'in subplot specifications must be '
  237. 'multiples of one another.')
  238. return {}
  239. if mod_col != 0:
  240. cbook._warn_external('tight_layout not applied: number of '
  241. 'columns in subplot specifications must be '
  242. 'multiples of one another.')
  243. return {}
  244. rowNum1, colNum1 = divmod(num1, cols)
  245. if num2 is None:
  246. rowNum2, colNum2 = rowNum1, colNum1
  247. else:
  248. rowNum2, colNum2 = divmod(num2, cols)
  249. num1num2_list.append((rowNum1 * div_row * max_ncols +
  250. colNum1 * div_col,
  251. ((rowNum2 + 1) * div_row - 1) * max_ncols +
  252. (colNum2 + 1) * div_col - 1))
  253. kwargs = auto_adjust_subplotpars(fig, renderer,
  254. nrows_ncols=(max_nrows, max_ncols),
  255. num1num2_list=num1num2_list,
  256. subplot_list=subplot_list,
  257. ax_bbox_list=ax_bbox_list,
  258. pad=pad, h_pad=h_pad, w_pad=w_pad)
  259. # kwargs can be none if tight_layout fails...
  260. if rect is not None and kwargs is not None:
  261. # if rect is given, the whole subplots area (including
  262. # labels) will fit into the rect instead of the
  263. # figure. Note that the rect argument of
  264. # *auto_adjust_subplotpars* specify the area that will be
  265. # covered by the total area of axes.bbox. Thus we call
  266. # auto_adjust_subplotpars twice, where the second run
  267. # with adjusted rect parameters.
  268. left, bottom, right, top = rect
  269. if left is not None:
  270. left += kwargs["left"]
  271. if bottom is not None:
  272. bottom += kwargs["bottom"]
  273. if right is not None:
  274. right -= (1 - kwargs["right"])
  275. if top is not None:
  276. top -= (1 - kwargs["top"])
  277. kwargs = auto_adjust_subplotpars(fig, renderer,
  278. nrows_ncols=(max_nrows, max_ncols),
  279. num1num2_list=num1num2_list,
  280. subplot_list=subplot_list,
  281. ax_bbox_list=ax_bbox_list,
  282. pad=pad, h_pad=h_pad, w_pad=w_pad,
  283. rect=(left, bottom, right, top))
  284. return kwargs