Skip to content

FIX: Handle no-offsets in collection datalim (alternative) #22946

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 2 commits into from
May 1, 2022
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
64 changes: 31 additions & 33 deletions lib/matplotlib/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ class Collection(artist.Artist, cm.ScalarMappable):
mappable will be used to set the ``facecolors`` and ``edgecolors``,
ignoring those that were manually passed in.
"""
_offsets = np.zeros((0, 2))
#: Either a list of 3x3 arrays or an Nx3x3 array (representing N
#: transforms), suitable for the `all_transforms` argument to
#: `~matplotlib.backend_bases.RendererBase.draw_path_collection`;
Expand Down Expand Up @@ -193,15 +192,12 @@ def __init__(self,
else:
self._joinstyle = None

# default to zeros
self._offsets = np.zeros((1, 2))

if offsets is not None:
offsets = np.asanyarray(offsets, float)
# Broadcast (2,) -> (1, 2) but nothing else.
if offsets.shape == (2,):
offsets = offsets[None, :]
self._offsets = offsets
self._offsets = offsets

self._offset_transform = offset_transform

Expand Down Expand Up @@ -263,9 +259,12 @@ def get_datalim(self, transData):
# if the offsets are in some coords other than data,
# then don't use them for autoscaling.
return transforms.Bbox.null()
offsets = self._offsets
offsets = self.get_offsets()

paths = self.get_paths()
if not len(paths):
# No paths to transform
return transforms.Bbox.null()

if not transform.is_affine:
paths = [transform.transform_path_non_affine(p) for p in paths]
Expand All @@ -274,22 +273,22 @@ def get_datalim(self, transData):
# transforms.get_affine().contains_branch(transData). But later,
# be careful to only apply the affine part that remains.

if isinstance(offsets, np.ma.MaskedArray):
offsets = offsets.filled(np.nan)
# get_path_collection_extents handles nan but not masked arrays

if len(paths) and len(offsets):
if any(transform.contains_branch_seperately(transData)):
# collections that are just in data units (like quiver)
# can properly have the axes limits set by their shape +
# offset. LineCollections that have no offsets can
# also use this algorithm (like streamplot).
return mpath.get_path_collection_extents(
transform.get_affine() - transData, paths,
self.get_transforms(),
offset_trf.transform_non_affine(offsets),
offset_trf.get_affine().frozen())

if any(transform.contains_branch_seperately(transData)):
# collections that are just in data units (like quiver)
# can properly have the axes limits set by their shape +
# offset. LineCollections that have no offsets can
# also use this algorithm (like streamplot).
if isinstance(offsets, np.ma.MaskedArray):
offsets = offsets.filled(np.nan)
# get_path_collection_extents handles nan but not masked arrays
return mpath.get_path_collection_extents(
transform.get_affine() - transData, paths,
self.get_transforms(),
offset_trf.transform_non_affine(offsets),
offset_trf.get_affine().frozen())

# NOTE: None is the default case where no offsets were passed in
if self._offsets is not None:
# this is for collections that have their paths (shapes)
# in physical, axes-relative, or figure-relative units
# (i.e. like scatter). We can't uniquely set limits based on
Expand All @@ -314,7 +313,7 @@ def _prepare_points(self):

transform = self.get_transform()
offset_trf = self.get_offset_transform()
offsets = self._offsets
offsets = self.get_offsets()
paths = self.get_paths()

if self.have_units():
Expand All @@ -325,10 +324,9 @@ def _prepare_points(self):
xs = self.convert_xunits(xs)
ys = self.convert_yunits(ys)
paths.append(mpath.Path(np.column_stack([xs, ys]), path.codes))
if offsets.size:
xs = self.convert_xunits(offsets[:, 0])
ys = self.convert_yunits(offsets[:, 1])
offsets = np.column_stack([xs, ys])
xs = self.convert_xunits(offsets[:, 0])
ys = self.convert_yunits(offsets[:, 1])
offsets = np.column_stack([xs, ys])

if not transform.is_affine:
paths = [transform.transform_path_non_affine(path)
Expand Down Expand Up @@ -557,7 +555,8 @@ def set_offsets(self, offsets):

def get_offsets(self):
"""Return the offsets for the collection."""
return self._offsets
# Default to zeros in the no-offset (None) case
return np.zeros((1, 2)) if self._offsets is None else self._offsets

def _get_default_linewidth(self):
# This may be overridden in a subclass.
Expand Down Expand Up @@ -2154,13 +2153,12 @@ def draw(self, renderer):
renderer.open_group(self.__class__.__name__, self.get_gid())
transform = self.get_transform()
offset_trf = self.get_offset_transform()
offsets = self._offsets
offsets = self.get_offsets()

if self.have_units():
if len(self._offsets):
xs = self.convert_xunits(self._offsets[:, 0])
ys = self.convert_yunits(self._offsets[:, 1])
offsets = np.column_stack([xs, ys])
xs = self.convert_xunits(offsets[:, 0])
ys = self.convert_yunits(offsets[:, 1])
offsets = np.column_stack([xs, ys])

self.update_scalarmappable()

Expand Down
12 changes: 12 additions & 0 deletions lib/matplotlib/tests/test_collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import matplotlib.pyplot as plt
import matplotlib.collections as mcollections
import matplotlib.colors as mcolors
import matplotlib.path as mpath
import matplotlib.transforms as mtransforms
from matplotlib.collections import (Collection, LineCollection,
EventCollection, PolyCollection)
Expand Down Expand Up @@ -291,6 +292,17 @@ def test_null_collection_datalim():
mtransforms.Bbox.null().get_points())


def test_no_offsets_datalim():
# A collection with no offsets and a non transData
# transform should return a null bbox
ax = plt.axes()
coll = mcollections.PathCollection([mpath.Path([(0, 0), (1, 0)])])
ax.add_collection(coll)
coll_data_lim = coll.get_datalim(mtransforms.IdentityTransform())
assert_array_equal(coll_data_lim.get_points(),
mtransforms.Bbox.null().get_points())


def test_add_collection():
# Test if data limits are unchanged by adding an empty collection.
# GitHub issue #1490, pull #1497.
Expand Down