Skip to content

PERF: Speed up legend best calculations#31803

Merged
QuLogic merged 4 commits into
matplotlib:mainfrom
scottshambaugh:legend_speedup
Jun 10, 2026
Merged

PERF: Speed up legend best calculations#31803
QuLogic merged 4 commits into
matplotlib:mainfrom
scottshambaugh:legend_speedup

Conversation

@scottshambaugh

@scottshambaugh scottshambaugh commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

PR summary

Closes #8108 (which was partially addressed already in #8224)

The 10 candidate legends are the same size and grid aligned, and so share edges. We can speed up the count_contains hot path by computing whether each point lies in those candidate intervals once, rather than looping over each location. In my profiling, I see a ~5x speedup for Legend._find_best_position, and most of the time there now is spent in other operations.

Did not deprecate count_contains since I found some instances of it being used on github, but it's no longer used anywhere internally so could remove. Added a test since it's no longer being exercised otherwise.

Before:
image

After:
image

Should hopefully cut down a lot on the warning Creating legend with loc="best" can be slow with large amounts of data, which I seem to run into fairly often.

AI Disclosure

Claude code used for first cut, manually cleaned up and refactored.

PR checklist

Comment thread lib/matplotlib/legend.py Outdated
Comment thread lib/matplotlib/legend.py Outdated
Comment thread lib/matplotlib/legend.py Outdated
@scottshambaugh scottshambaugh force-pushed the legend_speedup branch 2 times, most recently from c25072d to 6d9b97c Compare June 4, 2026 16:10
Comment thread lib/matplotlib/legend.py Outdated
@scottshambaugh scottshambaugh force-pushed the legend_speedup branch 3 times, most recently from 7c7158b to ea3bd71 Compare June 4, 2026 21:50
@QuLogic QuLogic merged commit c05922d into matplotlib:main Jun 10, 2026
41 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Default legend location 'best' is extremely slow

3 participants