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

Skip to content

Commit d9ef7af

Browse files
committed
Fix #21409: Make twin axes inherit parent position
When set_position() is called before twinx() or twiny(), the twin axes are created using the original subplot position instead of the current position of the parent. Set the twin position from the parent in _make_twin_axes so that twins start aligned with the parent axes. Add a regression test covering both twinx() and twiny().
1 parent 726af38 commit d9ef7af

2 files changed

Lines changed: 13 additions & 0 deletions

File tree

lib/matplotlib/axes/_base.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4657,6 +4657,9 @@ def _make_twin_axes(self, *args, **kwargs):
46574657
twin.set_zorder(self.zorder)
46584658

46594659
self._twinned_axes.join(self, twin)
4660+
4661+
twin.set_position(self.get_position())
4662+
46604663
return twin
46614664

46624665
def twinx(self, axes_class=None, **kwargs):

lib/matplotlib/tests/test_axes.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,16 @@ def test_twin_inherit_autoscale_setting():
477477
assert not ax_y_off.get_autoscaley_on()
478478

479479

480+
@pytest.mark.parametrize("twin", ("x", "y"))
481+
def test_twin_respects_position_after_set_position(twin):
482+
fig, ax = plt.subplots()
483+
484+
ax.set_position([0.2, 0.2, 0.5, 0.5])
485+
ax2 = getattr(ax, f"twin{twin}")()
486+
487+
assert_allclose(ax.bbox.bounds, ax2.bbox.bounds)
488+
489+
480490
def test_inverted_cla():
481491
# GitHub PR #5450. Setting autoscale should reset
482492
# axes to be non-inverted.

0 commit comments

Comments
 (0)