Skip to content
Open
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
10 changes: 10 additions & 0 deletions lib/matplotlib/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -630,6 +630,16 @@ def set_offsets(self, offsets):
offsets = np.asanyarray(offsets)
if offsets.shape == (2,): # Broadcast (2,) -> (1, 2) but nothing else.
offsets = offsets[None, :]
if offsets.ndim != 2 or offsets.shape[1] != 2:
if offsets.shape == (2, 0):
raise ValueError(
"offsets must have shape (N, 2), got (2, 0). "
"If you want an empty collection, use "
"np.column_stack([[], []]) or np.empty((0, 2))."
)
raise ValueError(
f"offsets must have shape (N, 2), or (2,) got {offsets.shape}."
)
cstack = (np.ma.column_stack if isinstance(offsets, np.ma.MaskedArray)
else np.column_stack)
self._offsets = cstack(
Expand Down
34 changes: 34 additions & 0 deletions lib/matplotlib/tests/test_collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -1314,6 +1314,40 @@ def test_set_offset_units():
np.testing.assert_allclose(off0, sc.get_offsets())


def test_set_offset_empty():
# Test with (0, 2) shaped array (the correct empty shape per (N, 2) docs)
# Using np.zeros((0, 2))
modified = mcollections.Collection(offsets=np.column_stack([[0, 1], [0, 1]]))
modified.set_offsets(np.zeros((0, 2)))
assert modified.get_offsets().shape == (0, 2)

# Using np.column_stack([[], []])
modified2 = mcollections.Collection(offsets=np.column_stack([[0, 1], [0, 1]]))
modified2.set_offsets(np.column_stack([[], []]))
assert modified2.get_offsets().shape == (0, 2)


def test_set_offset_wrong_shape_error():
# Test that arrays with wrong shape raise an error
coll = mcollections.Collection(offsets=np.column_stack([[0, 1], [0, 1]]))

# Wrong ndim
with pytest.raises(ValueError, match=r"offsets must have shape \(N, 2\)"):
coll.set_offsets([1, 2, 3]) # (3,) - wrong ndim
with pytest.raises(ValueError, match=r"offsets must have shape \(N, 2\)"):
coll.set_offsets([[[1, 2]]]) # (1, 1, 2) - 3D array

# Wrong second dimension
with pytest.raises(ValueError, match=r"use np.column_stack"):
coll.set_offsets([[], []]) # (2, 0) - special error with suggestion
with pytest.raises(ValueError, match=r"offsets must have shape \(N, 2\)"):
coll.set_offsets([[1], [2]]) # (2, 1)
with pytest.raises(ValueError, match=r"offsets must have shape \(N, 2\)"):
coll.set_offsets([[1, 2, 3], [4, 5, 6]]) # (2, 3)
with pytest.raises(ValueError, match=r"offsets must have shape \(N, 2\)"):
coll.set_offsets([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # (3, 3)


@image_comparison(baseline_images=["test_check_masked_offsets"],
extensions=["png"], remove_text=True, style="mpl20")
def test_check_masked_offsets():
Expand Down
Loading