Skip to content

Commit 51d37d1

Browse files
headtr1ckdcherian
andauthored
Raise TypeError if plotting empty data (#7228)
* raise TypeError if plotting empty data * add to whats-new * raise TypeError in all DataArray plot methods * maybe fix tests * fix test * fix mypy Co-authored-by: Deepak Cherian <[email protected]>
1 parent f32d354 commit 51d37d1

File tree

3 files changed

+46
-1
lines changed

3 files changed

+46
-1
lines changed

doc/whats-new.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@ Bug fixes
6161
now reopens the file from scratch for h5netcdf and scipy netCDF backends,
6262
rather than reusing a cached version (:issue:`4240`, :issue:`4862`).
6363
By `Stephan Hoyer <https://github.com/shoyer>`_.
64+
- Raise a TypeError when trying to plot empty data (:issue:`7156`, :pull:`7228`).
65+
By `Michael Niklas <https://github.com/headtr1ck>`_.
6466

6567
Documentation
6668
~~~~~~~~~~~~~

xarray/plot/dataarray_plot.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -280,7 +280,10 @@ def plot(
280280
ndims = len(plot_dims)
281281

282282
plotfunc: Callable
283-
if ndims in [1, 2]:
283+
284+
if ndims == 0 or darray.size == 0:
285+
raise TypeError("No numeric data to plot.")
286+
if ndims in (1, 2):
284287
if row or col:
285288
kwargs["subplot_kws"] = subplot_kws
286289
kwargs["row"] = row
@@ -483,6 +486,9 @@ def line(
483486
return _easy_facetgrid(darray, line, kind="line", **allargs)
484487

485488
ndims = len(darray.dims)
489+
if ndims == 0 or darray.size == 0:
490+
# TypeError to be consistent with pandas
491+
raise TypeError("No numeric data to plot.")
486492
if ndims > 2:
487493
raise ValueError(
488494
"Line plots are for 1- or 2-dimensional DataArrays. "
@@ -699,6 +705,10 @@ def hist(
699705
"""
700706
assert len(args) == 0
701707

708+
if darray.ndim == 0 or darray.size == 0:
709+
# TypeError to be consistent with pandas
710+
raise TypeError("No numeric data to plot.")
711+
702712
ax = get_axis(figsize, size, aspect, ax)
703713

704714
no_nan = np.ravel(darray.to_numpy())
@@ -899,6 +909,10 @@ def newplotfunc(
899909

900910
return _easy_facetgrid(darray, kind="plot1d", **allargs)
901911

912+
if darray.ndim == 0 or darray.size == 0:
913+
# TypeError to be consistent with pandas
914+
raise TypeError("No numeric data to plot.")
915+
902916
# The allargs dict passed to _easy_facetgrid above contains args
903917
if args == ():
904918
args = kwargs.pop("args", ())
@@ -1496,6 +1510,10 @@ def newplotfunc(
14961510
allargs["plotfunc"] = globals()[plotfunc.__name__]
14971511
return _easy_facetgrid(darray, kind="dataarray", **allargs)
14981512

1513+
if darray.ndim == 0 or darray.size == 0:
1514+
# TypeError to be consistent with pandas
1515+
raise TypeError("No numeric data to plot.")
1516+
14991517
plt = import_matplotlib_pyplot()
15001518

15011519
if (

xarray/tests/test_plot.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3180,6 +3180,31 @@ def test_assert_valid_xy() -> None:
31803180
_assert_valid_xy(darray=darray, xy="error_now", name="x")
31813181

31823182

3183+
@requires_matplotlib
3184+
@pytest.mark.parametrize(
3185+
"val", [pytest.param([], id="empty"), pytest.param(0, id="scalar")]
3186+
)
3187+
@pytest.mark.parametrize(
3188+
"method",
3189+
[
3190+
"__call__",
3191+
"line",
3192+
"step",
3193+
"contour",
3194+
"contourf",
3195+
"hist",
3196+
"imshow",
3197+
"pcolormesh",
3198+
"scatter",
3199+
"surface",
3200+
],
3201+
)
3202+
def test_plot_empty_raises(val: list | float, method: str) -> None:
3203+
da = xr.DataArray(val)
3204+
with pytest.raises(TypeError, match="No numeric data"):
3205+
getattr(da.plot, method)()
3206+
3207+
31833208
@requires_matplotlib
31843209
def test_facetgrid_axes_raises_deprecation_warning():
31853210
with pytest.warns(

0 commit comments

Comments
 (0)