ENH: Add pre_draw_event callback by Vikash-Kumar-23 · Pull Request #31887 · matplotlib/matplotlib
Closes #17168.
This PR adds a new pre_draw_event callback that is emitted during Figure.draw() after layout and geometry have been finalized but before any rendering occurs.
Currently, draw_event is emitted only after rendering has completed, which makes it difficult for callbacks to inspect or modify artists based on their final geometry before pixels are written to the renderer.
The new event is emitted after _get_draw_artists(renderer) so that:
- layout engines have already executed,
- axes positions have been finalized,
- locator-based axes (such as inset axes) have resolved their geometry,
- artist extents can be queried reliably,
while still allowing callbacks to run before rendering begins.
One motivating use case is overlay systems that need access to final axes geometry before rendering occurs without requiring an additional draw pass.
Minimum self-contained example
import matplotlib.pyplot as plt fig, ax = plt.subplots() def on_pre(event): print("pre_draw_event") def on_draw(event): print("draw_event") fig.canvas.mpl_connect("pre_draw_event", on_pre) fig.canvas.mpl_connect("draw_event", on_draw) fig.canvas.draw()
Output:
pre_draw_event
draw_event
pre_draw_event is emitted before rendering begins, while
draw_event is emitted after rendering completes.
AI Disclosure
AI tools were used to assist in drafting text and suggesting validation scenarios.
All code changes, final implementation decisions, and verification were done manually.
PR checklist
- "closes Add a pre_draw_event event #17168 " is in the body of the PR description to link the related issue
- new and changed code is tested
- Plotting related features are demonstrated in an example
- New Features and API Changes are noted with a directive and release note
- Documentation complies with general and docstring guidelines