Fix: Vertical Misalignment of LaTeX X-tick Labels by jayaprajapatii · Pull Request #31891 · matplotlib/matplotlib
closes #31802
PR Summary
x-tick labels using LaTeX/mathtext were vertically misaligned when savefig(dpi=300) was used, specifically when labels had different "ascents" (height above baseline) due to differing mathtext content — e.g. $w^{(2)}_1$ (superscript + subscript) vs $b^{(2)}$ (superscript only).
Why is this change necessary?
All x-tick label1s are top-aligned (va='top') to the same y-position via _get_text1_transform(). Since baseline_y = y1 - ascent, labels with different ascents end up with different baseline positions even though their top edges align. This difference is small but becomes visually noticeable at high DPI.
What problem does it solve?
It fixes the vertical misalignment of LaTeX x-tick labels, where one label (with a smaller ascent) appeared visually higher than the others.
Reason for this implementation?
Added Axis._align_xtick_label_baselines(), called from Axis.draw() after _update_ticks(). For each visible x-tick label1:
- Measure its
ascentvialabel._get_layout(renderer). - Find
max_ascentacross all labels. - Shift labels with smaller ascent down by
(max_ascent - ascent), so all baselines align with the label that has the largest ascent. - Added Regression test.
NOTE: A 0.5px threshold skips labels whose ascent differs only by sub-pixel amounts, so plain numeric/text tick labels (where this difference is negligible) remain unaffected.
AI Disclosure
AI was used in documentation build and suggesting validation scenarios.
All Implementation, testing, and verification were done manually.
PR checklist
- "closes #0000" 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