Temporarily adjust the figure so that only the specified area (bbox_inches) is saved. It modifies fig.bbox, fig.bbox_inches, fig.transFigure._boxout, and fig.patch. While the figure size changes, the scale of the original figure is conserved. A function which restores the
(fig, bbox_inches, renderer, fixed_dpi=None)
| 6 | |
| 7 | |
| 8 | def adjust_bbox(fig, bbox_inches, renderer, fixed_dpi=None): |
| 9 | """ |
| 10 | Temporarily adjust the figure so that only the specified area |
| 11 | (bbox_inches) is saved. |
| 12 | |
| 13 | It modifies fig.bbox, fig.bbox_inches, |
| 14 | fig.transFigure._boxout, and fig.patch. While the figure size |
| 15 | changes, the scale of the original figure is conserved. A |
| 16 | function which restores the original values are returned. |
| 17 | """ |
| 18 | origBbox = fig.bbox |
| 19 | origBboxInches = fig.bbox_inches |
| 20 | _boxout = fig.transFigure._boxout |
| 21 | |
| 22 | old_aspect = [] |
| 23 | locator_list = [] |
| 24 | sentinel = object() |
| 25 | for ax in fig.axes: |
| 26 | locator = ax.get_axes_locator() |
| 27 | if locator is not None: |
| 28 | ax.apply_aspect(locator(ax, renderer)) |
| 29 | locator_list.append(locator) |
| 30 | current_pos = ax.get_position(original=False).frozen() |
| 31 | ax.set_axes_locator(lambda a, r, _pos=current_pos: _pos) |
| 32 | # override the method that enforces the aspect ratio on the Axes |
| 33 | if 'apply_aspect' in ax.__dict__: |
| 34 | old_aspect.append(ax.apply_aspect) |
| 35 | else: |
| 36 | old_aspect.append(sentinel) |
| 37 | ax.apply_aspect = lambda pos=None: None |
| 38 | |
| 39 | def restore_bbox(): |
| 40 | for ax, loc, aspect in zip(fig.axes, locator_list, old_aspect): |
| 41 | ax.set_axes_locator(loc) |
| 42 | if aspect is sentinel: |
| 43 | # delete our no-op function which un-hides the original method |
| 44 | del ax.apply_aspect |
| 45 | else: |
| 46 | ax.apply_aspect = aspect |
| 47 | |
| 48 | fig.bbox = origBbox |
| 49 | fig.bbox_inches = origBboxInches |
| 50 | fig.transFigure._boxout = _boxout |
| 51 | fig.transFigure.invalidate() |
| 52 | fig.patch.set_bounds(0, 0, 1, 1) |
| 53 | |
| 54 | if fixed_dpi is None: |
| 55 | fixed_dpi = fig.dpi |
| 56 | tr = Affine2D().scale(fixed_dpi) |
| 57 | dpi_scale = fixed_dpi / fig.dpi |
| 58 | |
| 59 | fig.bbox_inches = Bbox.from_bounds(0, 0, *bbox_inches.size) |
| 60 | x0, y0 = tr.transform(bbox_inches.p0) |
| 61 | w1, h1 = fig.bbox.size * dpi_scale |
| 62 | fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1) |
| 63 | fig.transFigure.invalidate() |
| 64 | |
| 65 | fig.bbox = TransformedBbox(fig.bbox_inches, tr) |
no test coverage detected
searching dependent graphs…