tight_layout.py 14 KB

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