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

Skip to content

Commit 92132ec

Browse files
committed
Include figure-level texts and legends in constrained layout
1 parent c159c26 commit 92132ec

2 files changed

Lines changed: 25 additions & 15 deletions

File tree

lib/matplotlib/_constrained_layout.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -440,20 +440,20 @@ def make_layout_margins(layoutgrids, fig, renderer, *, w_pad=0, h_pad=0,
440440

441441
# make margins for figure-level legends:
442442
for leg in fig.legends:
443-
# === NEW: handle figure-level texts ===
443+
# === NEW: handle figure-level texts ===
444444
inv_trans_fig = fig.transFigure.inverted().transform_bbox
445445

446-
for text in fig.texts:
447-
if not text.get_visible() or not text.get_in_layout():
448-
continue
446+
for text in fig.texts:
447+
if not text.get_visible() or not text.get_in_layout():
448+
continue
449449

450-
try:
451-
bbox = inv_trans_fig(text.get_tightbbox(renderer))
452-
except Exception:
453-
continue
450+
try:
451+
bbox = inv_trans_fig(text.get_tightbbox(renderer))
452+
except Exception:
453+
continue
454454

455-
if bbox is None:
456-
continue
455+
if bbox is None:
456+
continue
457457

458458
w = bbox.width + 2 * w_pad
459459
h = bbox.height + 2 * h_pad
@@ -494,7 +494,6 @@ def make_layout_margins(layoutgrids, fig, renderer, *, w_pad=0, h_pad=0,
494494
if bbox.x1 > 1:
495495
layoutgrids[fig].edit_margin_min('right', w)
496496

497-
498497
def make_margin_suptitles(layoutgrids, fig, renderer, *, w_pad=0, h_pad=0):
499498
# Figure out how large the suptitle is and make the
500499
# top level figure margin larger.

lib/matplotlib/tests/test_constrainedlayout.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,19 +14,30 @@
1414
pytestmark = [
1515
pytest.mark.usefixtures('text_placeholders')
1616
]
17-
def test_constrainedlayout_fig_text():
17+
def test_constrainedlayout_fig_text_included():
1818
import matplotlib.pyplot as plt
1919

2020
fig, ax = plt.subplots(layout="constrained")
21-
fig.text(0.5, 0.98, "Title", ha="center")
21+
fig.text(0.5, 0.98, "Figure Title", ha="center")
2222

2323
fig.draw_without_rendering()
2424

25+
# Ensure no overlap: text should be above axes
2526
ax_bbox = ax.get_position()
26-
27-
# Axes should not touch the top
2827
assert ax_bbox.y1 < 0.98
2928

29+
def test_constrainedlayout_fig_legend_included():
30+
import matplotlib.pyplot as plt
31+
32+
fig, ax = plt.subplots(layout="constrained")
33+
ax.plot([1, 2, 3], label="line")
34+
fig.legend(loc="upper center")
35+
36+
fig.draw_without_rendering()
37+
38+
ax_bbox = ax.get_position()
39+
assert ax_bbox.y1 < 1.0 # leaves space for legend
40+
3041
def example_plot(ax, fontsize=12, nodec=False):
3142
ax.plot([1, 2])
3243
ax.locator_params(nbins=3)

0 commit comments

Comments
 (0)