Repository: pydata/xarray

Issue:
Plotting accessor error for datasets with Dimension name matches coordinate names
### What happened?

I am working with NetCDF files produced from the [Model Evaluation Tools (MET)](https://[dtcenter.org](https://dtcenter.org/community-code/model-evaluation-tools-met)/community-code/model-evaluation-tools-met).

This feature in xarray v2023.8.0 

> allows reading of datasets where a dimension name is associated with a multidimensional variable

lets me read the file where the dimension names `lat` and `lon` match the coordinate names `lat` `lon` (see https://github.com/dtcenter/MET/issues/1246). This is wonderful! Thank you for this 🎉🙌🏻

```python
import urllib
import xarray as xr

# download a sample MET file
urllib.request.urlretrieve(
    "https://github.com/dtcenter/MET/raw/main_v11.1/data/poly/NCEP_masks/WEST_mask.nc",
    "WEST_mask.nc",
)

# open MET file
ds = xr.open_dataset(
    "WEST_mask.nc",
    engine="netcdf4",
)
ds
```
![image](https://github.com/pydata/xarray/assets/6249613/01b7bdf2-7c99-4a80-b994-418770113b82)



However, one issue I've run into is that the plotting accessor doesn't seem to work for this case

```python
ds.WEST.plot()

OUT:
ValueError: coordinate 'lat' is a DataArray dimension, but it has shape (110, 147) rather than expected shape 110 matching the dimension size
```

To overcome this, I had to rename the dims

```python
ds.rename_dims({"lat": "y", "lon": "x"}).WEST.plot()
```
![image](https://github.com/pydata/xarray/assets/6249613/5d95dcb1-390a-42be-b03e-ad6cb102aa50)


### What did you expect to happen?

I expected the plot accessor to work without needing to rename the dimensions.

### Minimal Complete Verifiable Example

```Python
import urllib
import xarray as xr

# download a sample MET file
urllib.request.urlretrieve(
    "https://github.com/dtcenter/MET/raw/main_v11.1/data/poly/NCEP_masks/WEST_mask.nc",
    "WEST_mask.nc",
)

ds = xr.open_dataset(
    "WEST_mask.nc",
    engine="netcdf4",
)
ds.WEST.plot()
```


### MVCE confirmation

- [X] Minimal example — the example is as focused as reasonably possible to demonstrate the underlying issue in xarray.
- [X] Complete example — the example is self-contained, including all data and the text of any traceback.
- [X] Verifiable example — the example copy & pastes into an IPython prompt or [Binder notebook](https://mybinder.org/v2/gh/pydata/xarray/main?urlpath=lab/tree/doc/examples/blank_template.ipynb), returning the result.
- [X] New issue — a search of GitHub Issues suggests this is not a duplicate.

### Relevant log output

_No response_

### Anything else we need to know?

_No response_

### Environment

<details>

INSTALLED VERSIONS
------------------
commit: None
python: 3.11.4 | packaged by conda-forge | (main, Jun 10 2023, 18:08:17) [GCC 12.2.0]
python-bits: 64
OS: Linux
OS-release: 3.10.0-1160.53.1.el7.x86_64
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: ('en_US', 'UTF-8')
libhdf5: 1.12.2
libnetcdf: 4.9.1

xarray: 2023.8.0
pandas: 2.0.3
numpy: 1.25.2
scipy: 1.11.2
netCDF4: 1.6.3
pydap: None
h5netcdf: 1.2.0
h5py: 3.8.0
Nio: None
zarr: None
cftime: 1.6.2
nc_time_axis: None
PseudoNetCDF: None
iris: None
bottleneck: None
dask: 2023.8.1
distributed: 2023.8.1
matplotlib: 3.7.2
cartopy: 0.22.0
seaborn: 0.12.2
numbagg: None
fsspec: 2023.6.0
cupy: None
pint: 0.22
sparse: None
flox: None
numpy_groupies: None
setuptools: 68.1.2
pip: 23.2.1
conda: None
pytest: 7.4.0
mypy: None
IPython: 8.7.0
sphinx: 4.5.0
/p/home/blaylock/miniconda3/envs/flight/lib/python3.11/site-packages/_distutils_hack/__init__.py:33: UserWarning: Setuptools is replacing distutils.
  warnings.warn("Setuptools is replacing distutils.")

</details>

Discussion:

Patch:
diff --git a/xarray/core/dataarray.py b/xarray/core/dataarray.py
index 73464c07..724a5fc2 100644
--- a/xarray/core/dataarray.py
+++ b/xarray/core/dataarray.py
@@ -128,7 +128,7 @@ def _check_coords_dims(shape, coords, dims):
                 f"dimensions {dims}"
             )
 
-        for d, s in zip(v.dims, v.shape):
+        for d, s in v.sizes.items():
             if s != sizes[d]:
                 raise ValueError(
                     f"conflicting sizes for dimension {d!r}: "
@@ -136,13 +136,6 @@ def _check_coords_dims(shape, coords, dims):
                     f"coordinate {k!r}"
                 )
 
-        if k in sizes and v.shape != (sizes[k],):
-            raise ValueError(
-                f"coordinate {k!r} is a DataArray dimension, but "
-                f"it has shape {v.shape!r} rather than expected shape {sizes[k]!r} "
-                "matching the dimension size"
-            )
-
 
 def _infer_coords_and_dims(
     shape, coords, dims


Test patch:
diff --git a/xarray/tests/test_dataarray.py b/xarray/tests/test_dataarray.py
index 76dc4345..11ebc4da 100644
--- a/xarray/tests/test_dataarray.py
+++ b/xarray/tests/test_dataarray.py
@@ -38,6 +38,7 @@ from xarray.core.coordinates import Coordinates
 from xarray.core.indexes import Index, PandasIndex, filter_indexes_from_coords
 from xarray.core.types import QueryEngineOptions, QueryParserOptions
 from xarray.core.utils import is_scalar
+from xarray.testing import _assert_internal_invariants
 from xarray.tests import (
     InaccessibleArray,
     ReturnItem,
@@ -415,9 +416,6 @@ class TestDataArray:
         with pytest.raises(ValueError, match=r"conflicting MultiIndex"):
             DataArray(np.random.rand(4, 4), [("x", self.mindex), ("level_1", range(4))])
 
-        with pytest.raises(ValueError, match=r"matching the dimension size"):
-            DataArray(data, coords={"x": 0}, dims=["x", "y"])
-
     def test_constructor_from_self_described(self) -> None:
         data = [[-0.1, 21], [0, 2]]
         expected = DataArray(
@@ -7112,3 +7110,35 @@ class TestStackEllipsis:
         da = DataArray([[1, 2], [1, 2]], dims=("x", "y"))
         with pytest.raises(ValueError):
             da.stack(flat=...)  # type: ignore
+
+
+def test_nD_coord_dataarray() -> None:
+    # should succeed
+    da = DataArray(
+        np.ones((2, 4)),
+        dims=("x", "y"),
+        coords={
+            "x": (("x", "y"), np.arange(8).reshape((2, 4))),
+            "y": ("y", np.arange(4)),
+        },
+    )
+    _assert_internal_invariants(da, check_default_indexes=True)
+
+    da2 = DataArray(np.ones(4), dims=("y"), coords={"y": ("y", np.arange(4))})
+    da3 = DataArray(np.ones(4), dims=("z"))
+
+    _, actual = xr.align(da, da2)
+    assert_identical(da2, actual)
+
+    expected = da.drop_vars("x")
+    _, actual = xr.broadcast(da, da2)
+    assert_identical(expected, actual)
+
+    actual, _ = xr.broadcast(da, da3)
+    expected = da.expand_dims(z=4, axis=-1)
+    assert_identical(actual, expected)
+
+    da4 = DataArray(np.ones((2, 4)), coords={"x": 0}, dims=["x", "y"])
+    _assert_internal_invariants(da4, check_default_indexes=True)
+    assert "x" not in da4.xindexes
+    assert "x" in da4.coords