Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1839d93

Browse files
committed
FIX: Make sure figure legends are properly transformed in tight_bbox
1 parent 626d54f commit 1839d93

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

lib/matplotlib/tight_bbox.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,11 @@ def _l(a, r, pos=pos):
3535
ax.set_axes_locator(_l)
3636
ax.set_aspect("auto")
3737

38+
legend_anchors = {}
39+
for l in fig.legends: # store legend anchors for the restore step.
40+
anch = l.get_bbox_to_anchor()
41+
legend_anchors[l] = anch.frozen()
42+
3843
def restore_bbox():
3944
for ax, asp, loc in zip(fig.axes, asp_list, locator_list):
4045
ax.set_aspect(asp)
@@ -45,6 +50,9 @@ def restore_bbox():
4550
fig.set_tight_layout(orig_tight_layout)
4651
fig.transFigure._boxout = _boxout
4752
fig.transFigure.invalidate()
53+
for l in fig.legends: # re-set the anchor for legends...
54+
anch = legend_anchors[l].transformed(fig.transFigure.inverted())
55+
l.set_bbox_to_anchor(anch)
4856
fig.patch.set_bounds(0, 0, 1, 1)
4957

5058
if fixed_dpi is not None:
@@ -59,6 +67,11 @@ def restore_bbox():
5967
fig.bbox_inches = Bbox.from_bounds(0, 0,
6068
bbox_inches.width, bbox_inches.height)
6169
x0, y0 = _bbox.x0, _bbox.y0
70+
71+
for l in fig.legends: # offset the anchors...
72+
anchor = legend_anchors[l].translated(-x0, -y0) # in pixels
73+
l.set_bbox_to_anchor(anchor.transformed(fig.transFigure.inverted()))
74+
6275
w1, h1 = fig.bbox.width * dpi_scale, fig.bbox.height * dpi_scale
6376
fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1)
6477
fig.transFigure.invalidate()

0 commit comments

Comments
 (0)