Skip to content

2d plots may fail for some choices of x and y #5097

Closed
@johnomotani

Description

@johnomotani

What happened:
When making a 2d plot with a 1d x argument and a 2d y, if the two dimensions have the same size and are in the wrong order, no plot is produced - the third plot in the MCVE is blank.

What you expected to happen:
All three plots in the MCVE should be identical.

Minimal Complete Verifiable Example:

from matplotlib import pyplot as plt
import numpy as np
import xarray as xr

ds = xr.Dataset({"z": (["x", "y"], np.random.rand(4,4))})

x2d, y2d = np.meshgrid(ds["x"], ds["y"])

ds = ds.assign_coords(x2d=(["x", "y"], x2d.T), y2d=(["x", "y"], y2d.T))

fig, axes = plt.subplots(1,3)

h0 = ds["z"].plot.pcolormesh(x="y2d", y="x2d", ax=axes[0])
h1 = ds["z"].plot.pcolormesh(x="y", y="x", ax=axes[1])
h2 = ds["z"].plot.pcolormesh(x="y", y="x2d", ax=axes[2])

plt.show()

result:
test2d

Anything else we need to know?:

The bug is present in both the 0.17.0 release and current master.

I came across this while starting to work on #5084. I think the problem is here

xarray/xarray/plot/plot.py

Lines 678 to 684 in ddc352f

# check if we need to broadcast one dimension
if xval.ndim < yval.ndim:
dims = darray[ylab].dims
if xval.shape[0] == yval.shape[0]:
xval = np.broadcast_to(xval[:, np.newaxis], yval.shape)
else:
xval = np.broadcast_to(xval[np.newaxis, :], yval.shape)

as the check xval.shape[0] == yval.shape[0] doesn't work if the single dimension of x is actually the second dimension of y, but happened to have the same size as the first dimension of y? I think it needs to check the actual dimensions of x and y.

Why don't we just do something like

xval = xval.broadcast_like(darray)
yval = yval.broadcast_like(darray)

if either coordinate is 2d before using .values to convert to numpy arrays?

Environment:

Output of xr.show_versions()

INSTALLED VERSIONS

commit: None
python: 3.8.6 | packaged by conda-forge | (default, Oct 7 2020, 19:08:05)
[GCC 7.5.0]
python-bits: 64
OS: Linux
OS-release: 5.4.0-70-generic
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_GB.UTF-8
LOCALE: en_GB.UTF-8
libhdf5: 1.10.6
libnetcdf: 4.7.4

xarray: 0.17.0
pandas: 1.1.5
numpy: 1.19.4
scipy: 1.5.3
netCDF4: 1.5.5.1
pydap: None
h5netcdf: None
h5py: 3.1.0
Nio: None
zarr: None
cftime: 1.3.0
nc_time_axis: None
PseudoNetCDF: None
rasterio: None
cfgrib: None
iris: None
bottleneck: None
dask: 2020.12.0
distributed: 2020.12.0
matplotlib: 3.3.3
cartopy: None
seaborn: None
numbagg: None
pint: 0.16.1
setuptools: 49.6.0.post20201009
pip: 20.3.3
conda: 4.9.2
pytest: 6.2.1
IPython: 7.19.0
sphinx: 3.4.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions