Skip to content

Commit be27319

Browse files
nbren12shoyer
authored andcommitted
Warn when pcolormesh coordinate is not sorted (#1885)
Raise when pcolormesh coordinate is not sorted
1 parent 2ff7b4c commit be27319

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

xarray/plot/plot.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -745,6 +745,26 @@ def contourf(x, y, z, ax, **kwargs):
745745
return primitive
746746

747747

748+
def _is_monotonic(coord, axis=0):
749+
"""
750+
>>> _is_monotonic(np.array([0, 1, 2]))
751+
True
752+
>>> _is_monotonic(np.array([2, 1, 0]))
753+
True
754+
>>> _is_monotonic(np.array([0, 2, 1]))
755+
False
756+
"""
757+
if coord.shape[axis] < 3:
758+
return True
759+
else:
760+
n = coord.shape[axis]
761+
delta_pos = (coord.take(np.arange(1, n), axis=axis) >=
762+
coord.take(np.arange(0, n-1), axis=axis))
763+
delta_neg = (coord.take(np.arange(1, n), axis=axis) <=
764+
coord.take(np.arange(0, n-1), axis=axis))
765+
return np.all(delta_pos) or np.all(delta_neg)
766+
767+
748768
def _infer_interval_breaks(coord, axis=0):
749769
"""
750770
>>> _infer_interval_breaks(np.arange(5))
@@ -754,6 +774,15 @@ def _infer_interval_breaks(coord, axis=0):
754774
[ 2.5, 3.5, 4.5]])
755775
"""
756776
coord = np.asarray(coord)
777+
778+
if not _is_monotonic(coord, axis=axis):
779+
raise ValueError("The input coordinate is not sorted in increasing "
780+
"order along axis %d. This can lead to unexpected "
781+
"results. Consider calling the `sortby` method on "
782+
"the input DataArray. To plot data with categorical "
783+
"axes, consider using the `heatmap` function from "
784+
"the `seaborn` statistical plotting library." % axis)
785+
757786
deltas = 0.5 * np.diff(coord, axis=axis)
758787
if deltas.size == 0:
759788
deltas = np.array(0.0)

xarray/tests/test_plot.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,10 @@ def test__infer_interval_breaks(self):
178178
np.testing.assert_allclose(xref, x)
179179
np.testing.assert_allclose(yref, y)
180180

181+
# test that warning is raised for non-monotonic inputs
182+
with pytest.raises(ValueError):
183+
_infer_interval_breaks(np.array([0, 2, 1]))
184+
181185
def test_datetime_dimension(self):
182186
nrow = 3
183187
ncol = 4

0 commit comments

Comments
 (0)