Skip to content

Commit 8cb86a3

Browse files
timhoffmmeeseeksmachine
authored andcommitted
Backport PR matplotlib#29317: FIX: pass renderer through _auto_legend_data
1 parent e8cc337 commit 8cb86a3

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

lib/matplotlib/legend.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -934,7 +934,7 @@ def _init_legend_box(self, handles, labels, markerfirst=True):
934934
self.texts = text_list
935935
self.legend_handles = handle_list
936936

937-
def _auto_legend_data(self):
937+
def _auto_legend_data(self, renderer):
938938
"""
939939
Return display coordinates for hit testing for "best" positioning.
940940
@@ -969,7 +969,7 @@ def _auto_legend_data(self):
969969
if len(hoffsets):
970970
offsets.extend(transOffset.transform(hoffsets))
971971
elif isinstance(artist, Text):
972-
bboxes.append(artist.get_window_extent())
972+
bboxes.append(artist.get_window_extent(renderer))
973973

974974
return bboxes, lines, offsets
975975

@@ -1150,7 +1150,7 @@ def _find_best_position(self, width, height, renderer):
11501150

11511151
start_time = time.perf_counter()
11521152

1153-
bboxes, lines, offsets = self._auto_legend_data()
1153+
bboxes, lines, offsets = self._auto_legend_data(renderer)
11541154

11551155
bbox = Bbox.from_bounds(0, 0, width, height)
11561156

lib/matplotlib/tests/test_legend.py

+16
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import collections
2+
import io
23
import itertools
34
import platform
45
import time
@@ -1427,6 +1428,21 @@ def test_legend_text():
14271428
assert_allclose(leg_bboxes[1].bounds, leg_bboxes[0].bounds)
14281429

14291430

1431+
def test_legend_annotate():
1432+
fig, ax = plt.subplots()
1433+
1434+
ax.plot([1, 2, 3], label="Line")
1435+
ax.annotate("a", xy=(1, 1))
1436+
ax.legend(loc=0)
1437+
1438+
with mock.patch.object(
1439+
fig, '_get_renderer', wraps=fig._get_renderer) as mocked_get_renderer:
1440+
fig.savefig(io.BytesIO())
1441+
1442+
# Finding the legend position should not require _get_renderer to be called
1443+
mocked_get_renderer.assert_not_called()
1444+
1445+
14301446
def test_boxplot_legend_labels():
14311447
# Test that legend entries are generated when passing `label`.
14321448
np.random.seed(19680801)

0 commit comments

Comments
 (0)