Repository: pydata/xarray

Issue:
plot.line fails when plot axis is a 1D coordinate
#### MCVE Code Sample
<!-- In order for the maintainers to efficiently understand and prioritize issues, we ask you post a "Minimal, Complete and Verifiable Example" (MCVE): http://matthewrocklin.com/blog/work/2018/02/28/minimal-bug-reports -->

```python
import xarray as xr
import numpy as np

x_coord = xr.DataArray(data=[0.1, 0.2], dims=['x'])
t_coord = xr.DataArray(data=[10, 20], dims=['t'])

da = xr.DataArray(data=np.array([[0, 1], [5, 9]]), dims=['x', 't'],
                  coords={'x': x_coord, 'time': t_coord})
print(da)

da.transpose('time', 'x')
```
Output:
```
<xarray.DataArray (x: 2, t: 2)>
array([[0, 1],
       [5, 9]])
Coordinates:
  * x        (x) float64 0.1 0.2
    time     (t) int64 10 20

Traceback (most recent call last):
  File "mwe.py", line 22, in <module>
    da.transpose('time', 'x')
  File "/home/tegn500/Documents/Work/Code/xarray/xarray/core/dataarray.py", line 1877, in transpose
    "permuted array dimensions (%s)" % (dims, tuple(self.dims))
ValueError: arguments to transpose (('time', 'x')) must be permuted array dimensions (('x', 't'))
```

As `'time'` is a coordinate with only one dimension, this is an unambiguous operation that I want to perform. However, because `.transpose()` currently only accepts dimensions, this fails with that error.


This causes bug in other parts of the code - for example I found this by trying to plot this type of dataarray:
```python
da.plot(x='time', hue='x')
```
which gives the same error. 

(You can get a similar error also with `da.plot(y='time', hue='x')`.)

If the [code which explicitly checks](https://github.com/pydata/xarray/pull/2556/files?file-filters%5B%5D=.py#diff-ffd3597671590bab245b3193affa62b8R1437) that the arguments to transpose are dims and not just coordinate dimensions is removed, then both of these examples work as expected.

I would like to generalise the transpose function to also accept dimension coordinates, is there any reason not to do this?



Discussion:

Patch:
diff --git a/doc/whats-new.rst b/doc/whats-new.rst
index d8d33826..828a66db 100644
--- a/doc/whats-new.rst
+++ b/doc/whats-new.rst
@@ -24,6 +24,9 @@ Bug fixes
   reinstated for :class:`DataArray` and :class:`Dataset` objects only. Internal xarray
   objects remain unaddressable by weakref in order to save memory.
   (:issue:`3317`) by `Guido Imperiale <https://github.com/crusaderky>`_.
+- Line plots with the ``x`` or ``y`` argument set to a 1D non-dimensional coord
+  now plot the correct data for 2D DataArrays.
+  (:issue:`3334`). By `Tom Nicholas <http://github.com/TomNicholas>`_.
 
 Documentation
 ~~~~~~~~~~~~~
@@ -544,8 +547,9 @@ Bug fixes
   from higher frequencies to lower frequencies.  Datapoints outside the bounds
   of the original time coordinate are now filled with NaN (:issue:`2197`). By
   `Spencer Clark <https://github.com/spencerkclark>`_.
-- Line plots with the ``x`` argument set to a non-dimensional coord now plot the correct data for 1D DataArrays.
-  (:issue:`27251`). By `Tom Nicholas <http://github.com/TomNicholas>`_.
+- Line plots with the ``x`` argument set to a non-dimensional coord now plot
+  the correct data for 1D DataArrays.
+  (:issue:`2725`). By `Tom Nicholas <http://github.com/TomNicholas>`_.
 - Subtracting a scalar ``cftime.datetime`` object from a
   :py:class:`CFTimeIndex` now results in a :py:class:`pandas.TimedeltaIndex`
   instead of raising a ``TypeError`` (:issue:`2671`).  By `Spencer Clark
diff --git a/xarray/plot/plot.py b/xarray/plot/plot.py
index 8ca62ef5..7938f9b0 100644
--- a/xarray/plot/plot.py
+++ b/xarray/plot/plot.py
@@ -83,7 +83,9 @@ def _infer_line_data(darray, x, y, hue):
                     )
 
             else:
-                yplt = darray.transpose(xname, huename)
+                xdim, = darray[xname].dims
+                huedim, = darray[huename].dims
+                yplt = darray.transpose(xdim, huedim)
 
         else:
             yname, huename = _infer_xy_labels(darray=darray, x=y, y=hue)
@@ -100,7 +102,9 @@ def _infer_line_data(darray, x, y, hue):
                     )
 
             else:
-                xplt = darray.transpose(yname, huename)
+                ydim, = darray[yname].dims
+                huedim, = darray[huename].dims
+                xplt = darray.transpose(ydim, huedim)
 
         huelabel = label_from_attrs(darray[huename])
         hueplt = darray[huename]


Test patch:
diff --git a/xarray/tests/test_plot.py b/xarray/tests/test_plot.py
index 020a49b0..5ce75ad2 100644
--- a/xarray/tests/test_plot.py
+++ b/xarray/tests/test_plot.py
@@ -170,6 +170,23 @@ class TestPlot(PlotTestCase):
         line = current.plot.line()[0]
         assert_array_equal(line.get_xdata(), current.coords["t"].values)
 
+    def test_line_plot_along_1d_coord(self):
+        # Test for bug in GH #3334
+        x_coord = xr.DataArray(data=[0.1, 0.2], dims=["x"])
+        t_coord = xr.DataArray(data=[10, 20], dims=["t"])
+
+        da = xr.DataArray(
+            data=np.array([[0, 1], [5, 9]]),
+            dims=["x", "t"],
+            coords={"x": x_coord, "time": t_coord},
+        )
+
+        line = da.plot(x="time", hue="x")[0]
+        assert_array_equal(line.get_xdata(), da.coords["time"].values)
+
+        line = da.plot(y="time", hue="x")[0]
+        assert_array_equal(line.get_ydata(), da.coords["time"].values)
+
     def test_2d_line(self):
         with raises_regex(ValueError, "hue"):
             self.darray[:, :, 0].plot.line()