Skip to content

Propagate minpos from Collections to Axes.datalim #18642

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jan 5, 2021
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
11 changes: 10 additions & 1 deletion lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2000,7 +2000,16 @@ def add_collection(self, collection, autolim=True):
# Make sure viewLim is not stale (mostly to match
# pre-lazy-autoscale behavior, which is not really better).
self._unstale_viewLim()
self.update_datalim(collection.get_datalim(self.transData))
datalim = collection.get_datalim(self.transData)
points = datalim.get_points()
if not np.isinf(datalim.minpos).all():
# By definition, if minpos (minimum positive value) is set
# (i.e., non-inf), then min(points) <= minpos <= max(points),
# and minpos would be superfluous. However, we add minpos to
# the call so that self.dataLim will update its own minpos.
# This ensures that log scales see the correct minimum.
points = np.concatenate([points, [datalim.minpos]])
self.update_datalim(points)

self.stale = True
return collection
Expand Down
12 changes: 6 additions & 6 deletions lib/matplotlib/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,11 +274,11 @@ def get_datalim(self, transData):
# can properly have the axes limits set by their shape +
# offset. LineCollections that have no offsets can
# also use this algorithm (like streamplot).
result = mpath.get_path_collection_extents(
transform.get_affine(), paths, self.get_transforms(),
return mpath.get_path_collection_extents(
Copy link
Member

Choose a reason for hiding this comment

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

again, this could get some more explanation, given that there is a comment above, but this is clearly different. I'm not even sure I understand why you can change this like this.

Copy link
Member Author

Choose a reason for hiding this comment

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

The first argument is the master transform; instead of doing one transform when finding extents, and a second one after on the result, this does a combined transform from the get-go. This ensures that whatever is calculated for minpos is in the final coordinate space.

transform.get_affine() - transData, paths,
self.get_transforms(),
transOffset.transform_non_affine(offsets),
transOffset.get_affine().frozen())
return result.transformed(transData.inverted())
if not self._offsetsNone:
# this is for collections that have their paths (shapes)
# in physical, axes-relative, or figure-relative units
Expand All @@ -290,9 +290,9 @@ def get_datalim(self, transData):
# note A-B means A B^{-1}
offsets = np.ma.masked_invalid(offsets)
if not offsets.mask.all():
points = np.row_stack((offsets.min(axis=0),
offsets.max(axis=0)))
return transforms.Bbox(points)
bbox = transforms.Bbox.null()
bbox.update_from_data_xy(offsets)
return bbox
return transforms.Bbox.null()

def get_window_extent(self, renderer):
Expand Down
5 changes: 3 additions & 2 deletions lib/matplotlib/path.py
Original file line number Diff line number Diff line change
Expand Up @@ -1039,6 +1039,7 @@ def get_path_collection_extents(
from .transforms import Bbox
if len(paths) == 0:
raise ValueError("No paths provided")
return Bbox.from_extents(*_path.get_path_collection_extents(
extents, minpos = _path.get_path_collection_extents(
master_transform, paths, np.atleast_3d(transforms),
offsets, offset_transform))
offsets, offset_transform)
return Bbox.from_extents(*extents, minpos=minpos)
28 changes: 27 additions & 1 deletion lib/matplotlib/tests/test_collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import matplotlib.transforms as mtransforms
from matplotlib.collections import (Collection, LineCollection,
EventCollection, PolyCollection)
from matplotlib.testing.decorators import image_comparison
from matplotlib.testing.decorators import check_figures_equal, image_comparison


def generate_EventCollection_plot():
Expand Down Expand Up @@ -301,6 +301,32 @@ def test_add_collection():
assert ax.dataLim.bounds == bounds


@pytest.mark.style('mpl20')
@check_figures_equal(extensions=['png'])
def test_collection_log_datalim(fig_test, fig_ref):
# Data limits should respect the minimum x/y when using log scale.
x_vals = [4.38462e-6, 5.54929e-6, 7.02332e-6, 8.88889e-6, 1.12500e-5,
1.42383e-5, 1.80203e-5, 2.28070e-5, 2.88651e-5, 3.65324e-5,
4.62363e-5, 5.85178e-5, 7.40616e-5, 9.37342e-5, 1.18632e-4]
y_vals = [0.0, 0.1, 0.182, 0.332, 0.604, 1.1, 2.0, 3.64, 6.64, 12.1, 22.0,
39.6, 71.3]

x, y = np.meshgrid(x_vals, y_vals)
x = x.flatten()
y = y.flatten()

ax_test = fig_test.subplots()
ax_test.set_xscale('log')
ax_test.set_yscale('log')
ax_test.margins = 0
ax_test.scatter(x, y)

ax_ref = fig_ref.subplots()
ax_ref.set_xscale('log')
ax_ref.set_yscale('log')
ax_ref.plot(x, y, marker="o", ls="")


def test_quiver_limits():
ax = plt.axes()
x, y = np.arange(8), np.arange(10)
Expand Down
38 changes: 36 additions & 2 deletions lib/matplotlib/transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -808,13 +808,26 @@ def from_bounds(x0, y0, width, height):
return Bbox.from_extents(x0, y0, x0 + width, y0 + height)

@staticmethod
def from_extents(*args):
def from_extents(*args, minpos=None):
"""
Create a new Bbox from *left*, *bottom*, *right* and *top*.

The *y*-axis increases upwards.

Parameters
----------
left, bottom, right, top : float
The four extents of the bounding box.

minpos : float or None
If this is supplied, the Bbox will have a minimum positive value
set. This is useful when dealing with logarithmic scales and other
scales where negative bounds result in floating point errors.
"""
return Bbox(np.reshape(args, (2, 2)))
bbox = Bbox(np.reshape(args, (2, 2)))
if minpos is not None:
bbox._minpos[:] = minpos
return bbox

def __format__(self, fmt):
return (
Expand Down Expand Up @@ -953,14 +966,35 @@ def bounds(self, bounds):

@property
def minpos(self):
"""
The minimum positive value in both directions within the Bbox.

This is useful when dealing with logarithmic scales and other scales
where negative bounds result in floating point errors, and will be used
as the minimum extent instead of *p0*.
"""
return self._minpos

@property
def minposx(self):
"""
The minimum positive value in the *x*-direction within the Bbox.

This is useful when dealing with logarithmic scales and other scales
where negative bounds result in floating point errors, and will be used
as the minimum *x*-extent instead of *x0*.
"""
return self._minpos[0]

@property
def minposy(self):
"""
The minimum positive value in the *y*-direction within the Bbox.

This is useful when dealing with logarithmic scales and other scales
where negative bounds result in floating point errors, and will be used
as the minimum *y*-extent instead of *y0*.
"""
return self._minpos[1]

def get_points(self):
Expand Down
10 changes: 8 additions & 2 deletions src/_path_wrapper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,8 @@ static PyObject *Py_update_path_extents(PyObject *self, PyObject *args, PyObject
"NNi", outextents.pyobj(), outminpos.pyobj(), changed);
}

const char *Py_get_path_collection_extents__doc__ = "get_path_collection_extents(";
const char *Py_get_path_collection_extents__doc__ = "get_path_collection_extents("
"master_transform, paths, transforms, offsets, offset_transform)";

static PyObject *Py_get_path_collection_extents(PyObject *self, PyObject *args, PyObject *kwds)
{
Expand Down Expand Up @@ -295,7 +296,12 @@ static PyObject *Py_get_path_collection_extents(PyObject *self, PyObject *args,
extents(1, 0) = e.x1;
extents(1, 1) = e.y1;

return extents.pyobj();
npy_intp minposdims[] = { 2 };
numpy::array_view<double, 1> minpos(minposdims);
minpos(0) = e.xm;
minpos(1) = e.ym;

return Py_BuildValue("NN", extents.pyobj(), minpos.pyobj());
}

const char *Py_point_in_path_collection__doc__ =
Expand Down