Skip to content

PERF: Speed up legend best calculations#31803

Open
scottshambaugh wants to merge 2 commits into
matplotlib:mainfrom
scottshambaugh:legend_speedup
Open

PERF: Speed up legend best calculations#31803
scottshambaugh wants to merge 2 commits into
matplotlib:mainfrom
scottshambaugh:legend_speedup

Conversation

@scottshambaugh
Copy link
Copy Markdown
Contributor

@scottshambaugh scottshambaugh commented Jun 2, 2026

PR summary

Closes #8108

The 10 candidate legend locations are 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.

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

AI Disclosure

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

PR checklist

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

1 participant