Skip to content

Commit

Permalink
Raise TypeError if plotting empty data (pydata#7228)
Browse files Browse the repository at this point in the history
* 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 <dcherian@users.noreply.github.com>
  • Loading branch information
headtr1ck and dcherian authored Oct 28, 2022
1 parent f32d354 commit 51d37d1
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
2 changes: 2 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ Bug fixes
now reopens the file from scratch for h5netcdf and scipy netCDF backends,
rather than reusing a cached version (:issue:`4240`, :issue:`4862`).
By `Stephan Hoyer <https://github.com/shoyer>`_.
- Raise a TypeError when trying to plot empty data (:issue:`7156`, :pull:`7228`).
By `Michael Niklas <https://github.com/headtr1ck>`_.

Documentation
~~~~~~~~~~~~~
Expand Down
20 changes: 19 additions & 1 deletion xarray/plot/dataarray_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,10 @@ def plot(
ndims = len(plot_dims)

plotfunc: Callable
if ndims in [1, 2]:

if ndims == 0 or darray.size == 0:
raise TypeError("No numeric data to plot.")
if ndims in (1, 2):
if row or col:
kwargs["subplot_kws"] = subplot_kws
kwargs["row"] = row
Expand Down Expand Up @@ -483,6 +486,9 @@ def line(
return _easy_facetgrid(darray, line, kind="line", **allargs)

ndims = len(darray.dims)
if ndims == 0 or darray.size == 0:
# TypeError to be consistent with pandas
raise TypeError("No numeric data to plot.")
if ndims > 2:
raise ValueError(
"Line plots are for 1- or 2-dimensional DataArrays. "
Expand Down Expand Up @@ -699,6 +705,10 @@ def hist(
"""
assert len(args) == 0

if darray.ndim == 0 or darray.size == 0:
# TypeError to be consistent with pandas
raise TypeError("No numeric data to plot.")

ax = get_axis(figsize, size, aspect, ax)

no_nan = np.ravel(darray.to_numpy())
Expand Down Expand Up @@ -899,6 +909,10 @@ def newplotfunc(

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

if darray.ndim == 0 or darray.size == 0:
# TypeError to be consistent with pandas
raise TypeError("No numeric data to plot.")

# The allargs dict passed to _easy_facetgrid above contains args
if args == ():
args = kwargs.pop("args", ())
Expand Down Expand Up @@ -1496,6 +1510,10 @@ def newplotfunc(
allargs["plotfunc"] = globals()[plotfunc.__name__]
return _easy_facetgrid(darray, kind="dataarray", **allargs)

if darray.ndim == 0 or darray.size == 0:
# TypeError to be consistent with pandas
raise TypeError("No numeric data to plot.")

plt = import_matplotlib_pyplot()

if (
Expand Down
25 changes: 25 additions & 0 deletions xarray/tests/test_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -3180,6 +3180,31 @@ def test_assert_valid_xy() -> None:
_assert_valid_xy(darray=darray, xy="error_now", name="x")


@requires_matplotlib
@pytest.mark.parametrize(
"val", [pytest.param([], id="empty"), pytest.param(0, id="scalar")]
)
@pytest.mark.parametrize(
"method",
[
"__call__",
"line",
"step",
"contour",
"contourf",
"hist",
"imshow",
"pcolormesh",
"scatter",
"surface",
],
)
def test_plot_empty_raises(val: list | float, method: str) -> None:
da = xr.DataArray(val)
with pytest.raises(TypeError, match="No numeric data"):
getattr(da.plot, method)()


@requires_matplotlib
def test_facetgrid_axes_raises_deprecation_warning():
with pytest.warns(
Expand Down

0 comments on commit 51d37d1

Please sign in to comment.