Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 3 additions & 12 deletions lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2570,18 +2570,9 @@ def _update_patch_limits(self, patch):
if (isinstance(patch, mpatches.Rectangle) and
((not patch.get_width()) and (not patch.get_height()))):
return

p = patch.get_path()
# Get all vertices on the path
# Loop through each segment to get extrema for Bezier curve sections
vertices = []
for curve, code in p.iter_bezier(simplify=False):
# Get distance along the curve of any extrema
_, dzeros = curve.axis_aligned_extrema()
# Calculate vertices of start, end and any extrema in between
vertices.append(curve([0, *dzeros, 1]))

if len(vertices):
vertices = np.vstack(vertices)
extent_vertices = p._extent_vertices(simplify=False)

patch_trf = patch.get_transform()
updatex, updatey = patch_trf.contains_branch_separately(self.transData)
Expand All @@ -2594,7 +2585,7 @@ def _update_patch_limits(self, patch):
if updatey and patch_trf == self.get_xaxis_transform():
updatey = False
trf_to_data = patch_trf - self.transData
xys = trf_to_data.transform(vertices)
xys = trf_to_data.transform(extent_vertices)
self.update_datalim(xys, updatex=updatex, updatey=updatey)

def _update_collection_limits(self, collection):
Expand Down
51 changes: 33 additions & 18 deletions lib/matplotlib/path.py
Original file line number Diff line number Diff line change
Expand Up @@ -623,6 +623,35 @@ def contains_path(self, path, transform=None):
transform = transform.frozen()
return _path.path_in_path(self, None, path, transform)

def _extent_vertices(self, **kwargs):
"""
Return the vertices that determine this path's axis-aligned extents.

Parameters
----------
**kwargs
Forwarded to `.iter_bezier`.

Returns
-------
(N, 2) array of float
The vertices whose bounding box equals the bounding box of the path.
"""
if self.codes is None:
return self.vertices
if not ((self.codes == Path.CURVE3) | (self.codes == Path.CURVE4)).any():
# No curves: every vertex lies on a straight segment except the
# STOP/CLOSEPOLY placeholders, which do not affect the extents.
ignore = (self.codes == Path.STOP) | (self.codes == Path.CLOSEPOLY)
return self.vertices[~ignore] if ignore.any() else self.vertices
# Curved segments: solve for each segment's endpoints and interior
# extrema, since the control points may lie outside the drawn curve.
vertices = []
for curve, _ in self.iter_bezier(**kwargs):
_, dzeros = curve.axis_aligned_extrema()
vertices.append(curve([0, *dzeros, 1]))
return np.concatenate(vertices) if vertices else np.empty((0, 2))

def get_extents(self, transform=None, **kwargs):
"""
Get Bbox of the path.
Expand All @@ -642,25 +671,11 @@ def get_extents(self, transform=None, **kwargs):
from .transforms import Bbox
if transform is not None:
self = transform.transform_path(self)
if self.codes is None:
xys = self.vertices
elif len(np.intersect1d(self.codes, [Path.CURVE3, Path.CURVE4])) == 0:
# Optimization for the straight line case.
# Instead of iterating through each curve, consider
# each line segment's end-points
# (recall that STOP and CLOSEPOLY vertices are ignored)
xys = self.vertices[np.isin(self.codes,
[Path.MOVETO, Path.LINETO])]
else:
xys = []
for curve, code in self.iter_bezier(**kwargs):
# places where the derivative is zero can be extrema
_, dzeros = curve.axis_aligned_extrema()
# as can the ends of the curve
xys.append(curve([0, *dzeros, 1]))
xys = np.concatenate(xys)
xys = self._extent_vertices(**kwargs)
if len(xys):
return Bbox([xys.min(axis=0), xys.max(axis=0)])
x = xys[:, 0]
y = xys[:, 1]
return Bbox([[x.min(), y.min()], [x.max(), y.max()]])

@scottshambaugh scottshambaugh Jul 10, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This ended up being a hot path after the other changes, and is ~20x faster for a n=100000 point line. Surprised the numpy reduction is so slow tbh.

else:
return Bbox.null()

Expand Down
29 changes: 28 additions & 1 deletion lib/matplotlib/tests/test_path.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import numpy as np

from numpy.testing import assert_array_equal
from numpy.testing import assert_array_equal, assert_allclose
import pytest

from matplotlib import patches
Expand Down Expand Up @@ -129,6 +129,33 @@ def test_extents_with_ignored_codes(ignored_code):
assert np.all(path.get_extents().extents == (0., 0., 1., 1.))


@pytest.mark.parametrize("path, expected", [
# codes=None: every vertex is used
(Path([[0, 0], [1, 2], [3, 1]]), [[0, 0], [1, 2], [3, 1]]),
# straight path: all MOVETO/LINETO vertices are on the path
(Path([[0, 0], [1, 1], [2, 0]], [Path.MOVETO, Path.LINETO, Path.LINETO]),
[[0, 0], [1, 1], [2, 0]]),
# STOP/CLOSEPOLY carry placeholder vertices that must not affect extents
(Path([[0, 0], [1, 1], [5, 5]], [Path.MOVETO, Path.LINETO, Path.STOP]),
[[0, 0], [1, 1]]),
(Path([[0, 0], [1, 1], [5, 5]], [Path.MOVETO, Path.LINETO, Path.CLOSEPOLY]),
[[0, 0], [1, 1]]),
])
def test_extent_vertices_straight(path, expected):
assert_allclose(path._extent_vertices(), expected)


def test_extent_vertices_curve():
# A cubic whose control points overshoot the drawn curve: the returned
# vertices must capture the true interior extrema (xmax 0.75), not the
# control-point hull (xmax 1.0).
path = Path([[0, 0], [1, 0], [1, 1], [0, 1]],
[Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4])
xys = path._extent_vertices()
assert_allclose([xys[:, 0].min(), xys[:, 1].min(),
xys[:, 0].max(), xys[:, 1].max()], [0, 0, 0.75, 1])


def test_point_in_path_nan():
box = np.array([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]])
p = Path(box)
Expand Down
Loading