Skip to content

Commit eac78cc

Browse files
authored
Fix plot.line crash for data of shape (1, N) in _title_for_slice on format_item (#5948)
* 🧪 Add failing test case show casing the error * 🩹 Fix format_item crash when value array of shape (1, ) * 📚 Added change to whats-new.rst
1 parent e0deb9c commit eac78cc

File tree

3 files changed

+10
-2
lines changed

3 files changed

+10
-2
lines changed

doc/whats-new.rst

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@ Deprecations
3434

3535
Bug fixes
3636
~~~~~~~~~
37-
37+
- Fix plot.line crash for data of shape ``(1, N)`` in _title_for_slice on format_item (:pull:`5948`).
38+
By `Sebastian Weigand <https://github.com/s-weigand>`_.
3839

3940
Documentation
4041
~~~~~~~~~~~~~

xarray/core/formatting.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ def format_item(x, timedelta_format=None, quote_strings=True):
143143
elif isinstance(x, (str, bytes)):
144144
return repr(x) if quote_strings else x
145145
elif hasattr(x, "dtype") and np.issubdtype(x.dtype, np.floating):
146-
return f"{x:.4}"
146+
return f"{x.item():.4}"
147147
else:
148148
return str(x)
149149

xarray/tests/test_plot.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -754,6 +754,13 @@ def test_slice_in_title(self):
754754
title = plt.gca().get_title()
755755
assert "d = 10.01" == title
756756

757+
def test_slice_in_title_single_item_array(self):
758+
"""Edge case for data of shape (1, N) or (N, 1)."""
759+
darray = self.darray.expand_dims({"d": np.array([10.009])})
760+
darray.plot.line(x="period")
761+
title = plt.gca().get_title()
762+
assert "d = 10.01" == title
763+
757764

758765
class TestPlotStep(PlotTestCase):
759766
@pytest.fixture(autouse=True)

0 commit comments

Comments
 (0)