Skip to content

Commit 28ae492

Browse files
author
dcherian
committed
plot.line(): Draw multiple lines for 2D DataArrays.
1 parent cb161a1 commit 28ae492

File tree

3 files changed

+26
-10
lines changed

3 files changed

+26
-10
lines changed

doc/whats-new.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,9 @@ Enhancements
3333
- Experimental support for parsing ENVI metadata to coordinates and attributes
3434
in :py:func:`xarray.open_rasterio`.
3535
By `Matti Eskelinen <https://github.com/maaleske>`_.
36+
- :py:func:`~plot.line()` learned to draw multiple lines if provided with a
37+
2D variable.
38+
By `Deepak Cherian <https://github.com/dcherian>`_.
3639

3740
.. _Zarr: http://zarr.readthedocs.io/
3841

xarray/plot/plot.py

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ def plot(darray, row=None, col=None, col_wrap=None, ax=None, rtol=0.01,
156156
# matplotlib format strings
157157
def line(darray, *args, **kwargs):
158158
"""
159-
Line plot of 1 dimensional DataArray index against values
159+
Line plot of DataArray index against values
160160
161161
Wraps :func:`matplotlib:matplotlib.pyplot.plot`
162162
@@ -176,15 +176,19 @@ def line(darray, *args, **kwargs):
176176
ax : matplotlib axes object, optional
177177
Axis on which to plot this figure. By default, use the current axis.
178178
Mutually exclusive with ``size`` and ``figsize``.
179+
x : string, optional
180+
Coordinate for x axis (2D inputs only). If None use darray.dims[1]
181+
add_legend : boolean, optional
182+
Add legend with y axis coordinates (2D inputs only).
179183
*args, **kwargs : optional
180184
Additional arguments to matplotlib.pyplot.plot
181185
182186
"""
183187
plt = import_matplotlib_pyplot()
184188

185189
ndims = len(darray.dims)
186-
if ndims != 1:
187-
raise ValueError('Line plots are for 1 dimensional DataArrays. '
190+
if ndims > 2:
191+
raise ValueError('Line plots are for 1- or 2-dimensional DataArrays. '
188192
'Passed DataArray has {ndims} '
189193
'dimensions'.format(ndims=ndims))
190194

@@ -193,11 +197,19 @@ def line(darray, *args, **kwargs):
193197
aspect = kwargs.pop('aspect', None)
194198
size = kwargs.pop('size', None)
195199
ax = kwargs.pop('ax', None)
200+
x = kwargs.pop('x', None)
201+
add_legend = kwargs.pop('add_legend', True)
196202

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

199-
xlabel, = darray.dims
200-
x = darray.coords[xlabel]
205+
if ndims == 1:
206+
xlabel, = darray.dims
207+
x = darray.coords[xlabel]
208+
209+
else:
210+
xlabel, ylabel = _infer_xy_labels(darray=darray, x=x, y=None)
211+
x = darray.coords[xlabel]
212+
darray = darray.transpose(xlabel, ylabel)
201213

202214
_ensure_plottable(x)
203215

@@ -209,6 +221,9 @@ def line(darray, *args, **kwargs):
209221
if darray.name is not None:
210222
ax.set_ylabel(darray.name)
211223

224+
if darray.ndim == 2 and add_legend:
225+
ax.legend(darray.coords[ylabel].values, title=ylabel)
226+
212227
# Rotate dates on xlabels
213228
if np.issubdtype(x.dtype, np.datetime64):
214229
plt.gcf().autofmt_xdate()

xarray/tests/test_plot.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,9 @@ def setUp(self):
9494
def test1d(self):
9595
self.darray[:, 0, 0].plot()
9696

97+
def test2dline(self):
98+
self.darray[:, :, 0].plot.line()
99+
97100
def test_2d_before_squeeze(self):
98101
a = DataArray(easy_array((1, 5)))
99102
a.plot()
@@ -243,11 +246,6 @@ def test_ylabel_is_data_name(self):
243246
self.darray.plot()
244247
self.assertEqual(self.darray.name, plt.gca().get_ylabel())
245248

246-
def test_wrong_dims_raises_valueerror(self):
247-
twodims = DataArray(easy_array((2, 5)))
248-
with pytest.raises(ValueError):
249-
twodims.plot.line()
250-
251249
def test_format_string(self):
252250
self.darray.plot.line('ro')
253251

0 commit comments

Comments
 (0)