Skip to content

Commit

Permalink
Merge pull request matplotlib#29320 from meeseeksmachine/auto-backpor…
Browse files Browse the repository at this point in the history
…t-of-pr-29317-on-v3.10.x

Backport PR matplotlib#29317 on branch v3.10.x (FIX: pass renderer through `_auto_legend_data`)
  • Loading branch information
rcomer authored Dec 16, 2024
2 parents e8cc337 + 8cb86a3 commit efefcf4
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
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

0 comments on commit efefcf4

Please sign in to comment.