Skip to content

Expand ScalarMappable.set_array to accept array-like inputs #18870

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
May 13, 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
13 changes: 11 additions & 2 deletions lib/matplotlib/cm.py
Original file line number Diff line number Diff line change
Expand Up @@ -361,12 +361,21 @@ def to_rgba(self, x, alpha=None, bytes=False, norm=True):

def set_array(self, A):
"""
Set the image array from numpy array *A*.
Set the image array from array-like *A*.

Parameters
----------
A : ndarray or None
A : array-like or None
"""
if A is None:
self._A = None
return

A = cbook.safe_masked_invalid(A, copy=True)
if not np.can_cast(A.dtype, float, "same_kind"):
raise TypeError(f"Image data of dtype {A.dtype} cannot be "
"converted to float")

self._A = A

def get_array(self):
Expand Down
3 changes: 1 addition & 2 deletions lib/matplotlib/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -1346,8 +1346,7 @@ def make_image(self, renderer, magnification=1.0, unsampled=False):

def set_data(self, A):
"""Set the image array."""
cm.ScalarMappable.set_array(self,
cbook.safe_masked_invalid(A, copy=True))
cm.ScalarMappable.set_array(self, A)
self.stale = True


Expand Down
16 changes: 16 additions & 0 deletions lib/matplotlib/tests/test_collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,22 @@ def test_collection_set_verts_array():
assert np.array_equal(ap._codes, atp._codes)


def test_collection_set_array():
vals = [*range(10)]

# Test set_array with list
c = Collection()
c.set_array(vals)

# Test set_array with wrong dtype
with pytest.raises(TypeError, match="^Image data of dtype"):
c.set_array("wrong_input")

# Test if array kwarg is copied
vals[5] = 45
assert np.not_equal(vals, c.get_array()).any()


def test_blended_collection_autolim():
a = [1, 2, 4]
height = .2
Expand Down