From 25ff2ed09ff36596a144d3692f1739b4abe72c7a Mon Sep 17 00:00:00 2001 From: Jody Klymak Date: Fri, 3 Dec 2021 06:00:30 -0800 Subject: [PATCH] Backport PR #21818: Fix collections coerce float --- lib/matplotlib/collections.py | 6 ++++-- lib/matplotlib/tests/test_collections.py | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/collections.py b/lib/matplotlib/collections.py index 562362ab0c37..1a20e66e0239 100644 --- a/lib/matplotlib/collections.py +++ b/lib/matplotlib/collections.py @@ -559,10 +559,12 @@ def set_offsets(self, offsets): ---------- offsets : (N, 2) or (2,) array-like """ - offsets = np.asanyarray(offsets, float) + offsets = np.asanyarray(offsets) if offsets.shape == (2,): # Broadcast (2,) -> (1, 2) but nothing else. offsets = offsets[None, :] - self._offsets = offsets + self._offsets = np.column_stack( + (np.asarray(self.convert_xunits(offsets[:, 0]), 'float'), + np.asarray(self.convert_yunits(offsets[:, 1]), 'float'))) self.stale = True def get_offsets(self): diff --git a/lib/matplotlib/tests/test_collections.py b/lib/matplotlib/tests/test_collections.py index 9f92206e51cb..bc837f8db51d 100644 --- a/lib/matplotlib/tests/test_collections.py +++ b/lib/matplotlib/tests/test_collections.py @@ -1084,3 +1084,23 @@ def test_set_offset_transform(): late.set_offset_transform(skew) assert skew == init.get_offset_transform() == late.get_offset_transform() + + +def test_set_offset_units(): + # passing the offsets in initially (i.e. via scatter) + # should yield the same results as `set_offsets` + x = np.linspace(0, 10, 5) + y = np.sin(x) + d = x * np.timedelta64(24, 'h') + np.datetime64('2021-11-29') + + sc = plt.scatter(d, y) + off0 = sc.get_offsets() + sc.set_offsets(list(zip(d, y))) + np.testing.assert_allclose(off0, sc.get_offsets()) + + # try the other way around + fig, ax = plt.subplots() + sc = ax.scatter(y, d) + off0 = sc.get_offsets() + sc.set_offsets(list(zip(y, d))) + np.testing.assert_allclose(off0, sc.get_offsets())