Thanks to visit codestin.com
Credit goes to github.com

Skip to content

FIX: Autoscale support in add_collection3d for Line3DCollection and Poly3DCollection #28403

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
Jun 24, 2024
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
1 change: 0 additions & 1 deletion galleries/examples/mplot3d/polys3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@

poly = Poly3DCollection(verts, alpha=.7)
ax.add_collection3d(poly)
ax.auto_scale_xyz(verts[:, :, 0], verts[:, :, 1], verts[:, :, 2])
ax.set_aspect('equalxy')

plt.show()
29 changes: 27 additions & 2 deletions lib/mpl_toolkits/mplot3d/axes3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -2738,7 +2738,7 @@ def tricontourf(self, *args, zdir='z', offset=None, **kwargs):
self._auto_scale_contourf(X, Y, Z, zdir, levels, had_data)
return cset

def add_collection3d(self, col, zs=0, zdir='z'):
def add_collection3d(self, col, zs=0, zdir='z', autolim=True):
"""
Add a 3D collection object to the plot.

Expand All @@ -2750,8 +2750,21 @@ def add_collection3d(self, col, zs=0, zdir='z'):

- `.PolyCollection`
- `.LineCollection`
- `.PatchCollection`
- `.PatchCollection` (currently not supporting *autolim*)

Parameters
----------
col : `.Collection`
A 2D collection object.
zs : float or array-like, default: 0
The z-positions to be used for the 2D objects.
zdir : {'x', 'y', 'z'}, default: 'z'
The direction to use for the z-positions.
autolim : bool, default: True
Whether to update the data limits.
"""
had_data = self.has_data()

zvals = np.atleast_1d(zs)
zsortval = (np.min(zvals) if zvals.size
else 0) # FIXME: arbitrary default
Expand All @@ -2769,6 +2782,18 @@ def add_collection3d(self, col, zs=0, zdir='z'):
art3d.patch_collection_2d_to_3d(col, zs=zs, zdir=zdir)
col.set_sort_zpos(zsortval)

if autolim:
if isinstance(col, art3d.Line3DCollection):
self.auto_scale_xyz(*np.array(col._segments3d).transpose(),
had_data=had_data)
elif isinstance(col, art3d.Poly3DCollection):
self.auto_scale_xyz(*col._vec[:-1], had_data=had_data)
elif isinstance(col, art3d.Patch3DCollection):
pass
# FIXME: Implement auto-scaling function for Patch3DCollection
# Currently unable to do so due to issues with Patch3DCollection
# See https://github.com/matplotlib/matplotlib/issues/14298 for details
Comment on lines +2786 to +2795
Copy link
Member

@timhoffm timhoffm Jun 18, 2024

Choose a reason for hiding this comment

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

While technically correct, I believe we should move the calculation of data lims down into the artists.

Current logic

Extract all data coordinates xyz from the artist and feed them into auto_scale_xyz().

This updates the xy_dataLim, zz_dataLim BBoxes via .Bbox.update_from_data_xy/x/y(), which in turn creates a Path and calls .Bbox.update_from_path().

This is quite a lot data pushing (and maybe copying) just to update dataLim bboxes.

Proposed logic

Separation of concerns: The Artists should have a function to get their data lims. These limits should be used to update the Bbox. Basically some Bbox.update_from_box, a kind of an in-place Bbox.union, which we don't seem to have.

This whole block should read something like

if autolim:
    self.auto_scale_lim(col.get_data_lims())

Note: "data lim" is intentionally vague as we currently don't have a good structure to describe it (we use two 2D Bboxes, xy_dataLim and zz_dataLim.

The minimal approach - if we don't want to redesign for proper 3d boxes, would be to let get_data_lims() return two BBoxes as well. In that case, I would keep this interface private _get_data_lims() so that we can still change to a single 3D instance later.


Edit: This is basically a generalization of Collection.get_datalim.

def get_datalim(self, transData):
# Calculate the data limits and return them as a `.Bbox`.
#
# This operation depends on the transforms for the data in the
# collection and whether the collection has offsets:
#
# 1. offsets = None, transform child of transData: use the paths for
# the automatic limits (i.e. for LineCollection in streamline).
# 2. offsets != None: offset_transform is child of transData:
#
# a. transform is child of transData: use the path + offset for
# limits (i.e for bar).
# b. transform is not a child of transData: just use the offsets
# for the limits (i.e. for scatter)
#
# 3. otherwise return a null Bbox.
transform = self.get_transform()
offset_trf = self.get_offset_transform()
if not (isinstance(offset_trf, transforms.IdentityTransform)
or offset_trf.contains_branch(transData)):
# if the offsets are in some coords other than data,
# then don't use them for autoscaling.
return transforms.Bbox.null()
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]
# Don't convert transform to transform.get_affine() here because
# we may have transform.contains_branch(transData) but not
# transforms.get_affine().contains_branch(transData). But later,
# be careful to only apply the affine part that remains.
offsets = self.get_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).
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
# those shapes, so we just set the limits based on their
# location.
offsets = (offset_trf - transData).transform(offsets)
# note A-B means A B^{-1}
offsets = np.ma.masked_invalid(offsets)
if not offsets.mask.all():
bbox = transforms.Bbox.null()
bbox.update_from_data_xy(offsets)
return bbox
return transforms.Bbox.null()

Rough outline: We may start minimal with rolling a small

class _Bbox3d:
    def __init__(self, points):
        ((self.xmin, self.xmax),
         (self.ymin, self.ymax),
         (self.zmin, self.zmax)) = points

    def to_bbox_xy(self):
        return Bbox(((self.xmin, self.xmax), (self.ymin, self.ymax)))

    def to_bbox_zz(self):
        # first component contains z, second is unused
        return Bbox(((self.zmin, self.zmax), (0, 0)))

and implement _get_datalim3d() -> _Bbox3d on the 3d collections.

Then

def add_collection(col, autolim=True):
    ...
    if autolim:
        self.auto_scale_lim(col.get_datalim3d())

and

def auto_scale_lim(bbox3d):
     ...
     self.dataLim_xy.update_from_box(bbox3d.to_bbox_xy())
     self.dataLim_zz.update_from_box(bbox3d.to_bbox_zz())

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I like this structure, but could we make that refactor its own issue?


collection = super().add_collection(col)
return collection

Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
34 changes: 30 additions & 4 deletions lib/mpl_toolkits/mplot3d/tests/test_axes3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -1004,8 +1004,8 @@ def test_poly3dcollection_closed():
facecolor=(0.5, 0.5, 1, 0.5), closed=True)
c2 = art3d.Poly3DCollection([poly2], linewidths=3, edgecolor='k',
facecolor=(1, 0.5, 0.5, 0.5), closed=False)
ax.add_collection3d(c1)
ax.add_collection3d(c2)
ax.add_collection3d(c1, autolim=False)
ax.add_collection3d(c2, autolim=False)


def test_poly_collection_2d_to_3d_empty():
Expand Down Expand Up @@ -1038,8 +1038,8 @@ def test_poly3dcollection_alpha():
c2.set_facecolor((1, 0.5, 0.5))
c2.set_edgecolor('k')
c2.set_alpha(0.5)
ax.add_collection3d(c1)
ax.add_collection3d(c2)
ax.add_collection3d(c1, autolim=False)
ax.add_collection3d(c2, autolim=False)


@mpl3d_image_comparison(['add_collection3d_zs_array.png'], style='mpl20')
Expand Down Expand Up @@ -1098,6 +1098,32 @@ def test_add_collection3d_zs_scalar():
ax.set_zlim(0, 2)


def test_line3dCollection_autoscaling():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')

lines = [[(0, 0, 0), (1, 4, 2)],
[(1, 1, 3), (2, 0, 2)],
[(1, 0, 4), (1, 4, 5)]]

lc = art3d.Line3DCollection(lines)
ax.add_collection3d(lc)
assert np.allclose(ax.get_xlim3d(), (-0.041666666666666664, 2.0416666666666665))
assert np.allclose(ax.get_ylim3d(), (-0.08333333333333333, 4.083333333333333))
assert np.allclose(ax.get_zlim3d(), (-0.10416666666666666, 5.104166666666667))


def test_poly3dCollection_autoscaling():
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
poly = np.array([[0, 0, 0], [1, 1, 3], [1, 0, 4]])
col = art3d.Poly3DCollection([poly])
ax.add_collection3d(col)
assert np.allclose(ax.get_xlim3d(), (-0.020833333333333332, 1.0208333333333333))
assert np.allclose(ax.get_ylim3d(), (-0.020833333333333332, 1.0208333333333333))
assert np.allclose(ax.get_zlim3d(), (-0.0833333333333333, 4.083333333333333))


@mpl3d_image_comparison(['axes3d_labelpad.png'],
remove_text=False, style='mpl20')
def test_axes3d_labelpad():
Expand Down
Loading