Skip to content

Add widths, heights and angles setter to EllipseCollection #26375

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 6 commits into from
Apr 1, 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
40 changes: 40 additions & 0 deletions doc/users/next_whats_new/add_EllipseCollection_setters.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
Add ``widths``, ``heights`` and ``angles`` setter to ``EllipseCollection``
--------------------------------------------------------------------------

The ``widths``, ``heights`` and ``angles`` values of the `~matplotlib.collections.EllipseCollection`
can now be changed after the collection has been created.

.. plot::
:include-source: true

import matplotlib.pyplot as plt
from matplotlib.collections import EllipseCollection
import numpy as np

rng = np.random.default_rng(0)

widths = (2, )
heights = (3, )
angles = (45, )
offsets = rng.random((10, 2)) * 10

fig, ax = plt.subplots()

ec = EllipseCollection(
widths=widths,
heights=heights,
angles=angles,
offsets=offsets,
units='x',
offset_transform=ax.transData,
)

ax.add_collection(ec)
ax.set_xlim(-2, 12)
ax.set_ylim(-2, 12)

new_widths = rng.random((10, 2)) * 2
new_heights = rng.random((10, 2)) * 3
new_angles = rng.random((10, 2)) * 180

ec.set(widths=new_widths, heights=new_heights, angles=new_angles)
33 changes: 30 additions & 3 deletions lib/matplotlib/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -1745,9 +1745,9 @@ def __init__(self, widths, heights, angles, *, units='points', **kwargs):
Forwarded to `Collection`.
"""
super().__init__(**kwargs)
self._widths = 0.5 * np.asarray(widths).ravel()
self._heights = 0.5 * np.asarray(heights).ravel()
self._angles = np.deg2rad(angles).ravel()
self.set_widths(widths)
self.set_heights(heights)
self.set_angles(angles)
self._units = units
self.set_transform(transforms.IdentityTransform())
self._transforms = np.empty((0, 3, 3))
Expand Down Expand Up @@ -1795,6 +1795,33 @@ def _set_transforms(self):
m[:2, 2:] = 0
self.set_transform(_affine(m))

def set_widths(self, widths):
"""Set the lengths of the first axes (e.g., major axis)."""
self._widths = 0.5 * np.asarray(widths).ravel()
self.stale = True

def set_heights(self, heights):
"""Set the lengths of second axes (e.g., minor axes)."""
self._heights = 0.5 * np.asarray(heights).ravel()
self.stale = True

def set_angles(self, angles):
"""Set the angles of the first axes, degrees CCW from the x-axis."""
self._angles = np.deg2rad(angles).ravel()
self.stale = True

def get_widths(self):
"""Get the lengths of the first axes (e.g., major axis)."""
return self._widths * 2

def get_heights(self):
"""Set the lengths of second axes (e.g., minor axes)."""
return self._heights * 2

def get_angles(self):
"""Get the angles of the first axes, degrees CCW from the x-axis."""
return np.rad2deg(self._angles)

@artist.allow_rasterization
def draw(self, renderer):
self._set_transforms()
Expand Down
6 changes: 6 additions & 0 deletions lib/matplotlib/collections.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,12 @@ class EllipseCollection(Collection):
] = ...,
**kwargs
) -> None: ...
def set_widths(self, widths: ArrayLike) -> None: ...
def set_heights(self, heights: ArrayLike) -> None: ...
def set_angles(self, angles: ArrayLike) -> None: ...
def get_widths(self) -> ArrayLike: ...
def get_heights(self) -> ArrayLike: ...
def get_angles(self) -> ArrayLike: ...

class PatchCollection(Collection):
def __init__(
Expand Down
43 changes: 43 additions & 0 deletions lib/matplotlib/tests/test_collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,49 @@ def test_EllipseCollection():
ax.autoscale_view()


def test_EllipseCollection_setter_getter():
# Test widths, heights and angle setter
rng = np.random.default_rng(0)

widths = (2, )
heights = (3, )
angles = (45, )
offsets = rng.random((10, 2)) * 10

fig, ax = plt.subplots()

ec = mcollections.EllipseCollection(
widths=widths,
heights=heights,
angles=angles,
offsets=offsets,
units='x',
offset_transform=ax.transData,
)

assert_array_almost_equal(ec._widths, np.array(widths).ravel() * 0.5)
assert_array_almost_equal(ec._heights, np.array(heights).ravel() * 0.5)
assert_array_almost_equal(ec._angles, np.deg2rad(angles).ravel())
Comment on lines +431 to +433
Copy link
Member

Choose a reason for hiding this comment

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

Do we need to check internals now that we have the getters?

Copy link
Member Author

Choose a reason for hiding this comment

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

These check that the internal values are correct (multiplication of 0.5) and these are different from the values returned by the getter, so I would say that this is still worth checking these values?

Copy link
Member

Choose a reason for hiding this comment

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

Testing internals is not ideal, but OTOH these tests do not impose a big liability. It's unlikely that we will refactor the internals and if so, the tests can be easily adapted.

Alternatives would be an image comparison (not favored) or checking the bounding box of an EllipseCollection with a single entry.

Copy link
Member Author

Choose a reason for hiding this comment

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

If this is find to keep to check as it is I would prefer that option because it is straighforward and more simple than the bounding box alternative.


assert_array_almost_equal(ec.get_widths(), widths)
assert_array_almost_equal(ec.get_heights(), heights)
assert_array_almost_equal(ec.get_angles(), angles)

ax.add_collection(ec)
ax.set_xlim(-2, 12)
ax.set_ylim(-2, 12)

new_widths = rng.random((10, 2)) * 2
new_heights = rng.random((10, 2)) * 3
new_angles = rng.random((10, 2)) * 180

ec.set(widths=new_widths, heights=new_heights, angles=new_angles)

assert_array_almost_equal(ec.get_widths(), new_widths.ravel())
assert_array_almost_equal(ec.get_heights(), new_heights.ravel())
assert_array_almost_equal(ec.get_angles(), new_angles.ravel())


@image_comparison(['polycollection_close.png'], remove_text=True, style='mpl20')
def test_polycollection_close():
from mpl_toolkits.mplot3d import Axes3D # type: ignore
Expand Down