Skip to content

Backport PR #29317 on branch v3.10.x (FIX: pass renderer through _auto_legend_data) #29320

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions lib/matplotlib/legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -934,7 +934,7 @@ def _init_legend_box(self, handles, labels, markerfirst=True):
self.texts = text_list
self.legend_handles = handle_list

def _auto_legend_data(self):
def _auto_legend_data(self, renderer):
"""
Return display coordinates for hit testing for "best" positioning.

Expand Down Expand Up @@ -969,7 +969,7 @@ def _auto_legend_data(self):
if len(hoffsets):
offsets.extend(transOffset.transform(hoffsets))
elif isinstance(artist, Text):
bboxes.append(artist.get_window_extent())
bboxes.append(artist.get_window_extent(renderer))

return bboxes, lines, offsets

Expand Down Expand Up @@ -1150,7 +1150,7 @@ def _find_best_position(self, width, height, renderer):

start_time = time.perf_counter()

bboxes, lines, offsets = self._auto_legend_data()
bboxes, lines, offsets = self._auto_legend_data(renderer)

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

Expand Down
16 changes: 16 additions & 0 deletions lib/matplotlib/tests/test_legend.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import collections
import io
import itertools
import platform
import time
Expand Down Expand Up @@ -1427,6 +1428,21 @@ def test_legend_text():
assert_allclose(leg_bboxes[1].bounds, leg_bboxes[0].bounds)


def test_legend_annotate():
fig, ax = plt.subplots()

ax.plot([1, 2, 3], label="Line")
ax.annotate("a", xy=(1, 1))
ax.legend(loc=0)

with mock.patch.object(
fig, '_get_renderer', wraps=fig._get_renderer) as mocked_get_renderer:
fig.savefig(io.BytesIO())

# Finding the legend position should not require _get_renderer to be called
mocked_get_renderer.assert_not_called()


def test_boxplot_legend_labels():
# Test that legend entries are generated when passing `label`.
np.random.seed(19680801)
Expand Down
Loading