# Plotting

## Introduction

Labeled data enables expressive computations. These same labels can also be used to easily create informative plots.

Xarray’s plotting capabilities are centered around `DataArray` objects. To plot `Dataset` objects simply access the relevant DataArrays, i.e. `dset['var1']`. Dataset specific plotting routines are also available (see Datasets). Here we focus mostly on arrays 2d or larger. If your data fits nicely into a pandas DataFrame then you’re better off using one of the more developed tools there.

Xarray plotting functionality is a thin wrapper around the popular matplotlib library. Matplotlib syntax and function names were copied as much as possible, which makes for an easy transition between the two. Matplotlib must be installed before xarray can plot.

To use xarray’s plotting capabilities with time coordinates containing `cftime.datetime` objects nc-time-axis v1.2.0 or later needs to be installed.

For more extensive plotting applications consider the following projects:

- Seaborn: “provides a high-level interface for drawing attractive statistical graphics.” Integrates well with pandas.

- HoloViews and GeoViews: “Composable, declarative data structures for building even complex visualizations easily.” Includes native support for xarray objects.

- hvplot: `hvplot` makes it very easy to produce dynamic plots (backed by `Holoviews` or `Geoviews`) by adding a `hvplot` accessor to DataArrays.

- Cartopy: Provides cartographic tools.

### Imports

The following imports are necessary for all of the examples.

    In [1]: import numpy as np

    In [2]: import pandas as pd

    In [3]: import matplotlib.pyplot as plt

    In [4]: import xarray as xr

For these examples we’ll use the North American air temperature dataset.

    In [5]: airtemps = xr.tutorial.open_dataset("air_temperature")
    ---------------------------------------------------------------------------
    ModuleNotFoundError                       Traceback (most recent call last)
    /build/python-xarray-bL1QJU/python-xarray-0.21.1/xarray/tutorial.py in open_dataset(name, cache, cache_dir, engine, **kws)
        113     try:
    --> 114         import pooch
        115     except ImportError as e:

    ModuleNotFoundError: No module named 'pooch'

    The above exception was the direct cause of the following exception:

    ImportError                               Traceback (most recent call last)
    <ipython-input-5-a81e2080b7fb> in <module>
    ----> 1 airtemps = xr.tutorial.open_dataset("air_temperature")

    /build/python-xarray-bL1QJU/python-xarray-0.21.1/xarray/tutorial.py in open_dataset(name, cache, cache_dir, engine, **kws)
        114         import pooch
        115     except ImportError as e:
    --> 116         raise ImportError(
        117             "tutorial.open_dataset depends on pooch to download and manage datasets."
        118             " To proceed please install pooch."

    ImportError: tutorial.open_dataset depends on pooch to download and manage datasets. To proceed please install pooch.

    In [6]: airtemps
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-6-eb57b540ddce> in <module>
    ----> 1 airtemps

    NameError: name 'airtemps' is not defined

    # Convert to celsius
    In [7]: air = airtemps.air - 273.15
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-7-ca9decd7dd88> in <module>
    ----> 1 air = airtemps.air - 273.15

    NameError: name 'airtemps' is not defined

    # copy attributes to get nice figure labels and change Kelvin to Celsius
    In [8]: air.attrs = airtemps.air.attrs
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-8-0f41191e8013> in <module>
    ----> 1 air.attrs = airtemps.air.attrs

    NameError: name 'airtemps' is not defined

    In [9]: air.attrs["units"] = "deg C"
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-9-2d3ef7780735> in <module>
    ----> 1 air.attrs["units"] = "deg C"

    NameError: name 'air' is not defined

Note

Until GH1614 is solved, you might need to copy over the metadata in `attrs` to get informative figure labels (as was done above).

## DataArrays

### One Dimension

#### Simple Example

The simplest way to make a plot is to call the `DataArray.plot()` method.

    In [10]: air1d = air.isel(lat=10, lon=10)
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-10-e8b74ff84db4> in <module>
    ----> 1 air1d = air.isel(lat=10, lon=10)

    NameError: name 'air' is not defined

    In [11]: air1d.plot()
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-11-f4da044a917f> in <module>
    ----> 1 air1d.plot()

    NameError: name 'air1d' is not defined

Xarray uses the coordinate name along with metadata `attrs.long_name`, `attrs.standard_name`, `DataArray.name` and `attrs.units` (if available) to label the axes. The names `long_name`, `standard_name` and `units` are copied from the CF-conventions spec. When choosing names, the order of precedence is `long_name`, `standard_name` and finally `DataArray.name`. The y-axis label in the above plot was constructed from the `long_name` and `units` attributes of `air1d`.

    In [12]: air1d.attrs
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-12-60f8bca41fc7> in <module>
    ----> 1 air1d.attrs

    NameError: name 'air1d' is not defined

#### Additional Arguments

Additional arguments are passed directly to the matplotlib function which does the work. For example, `xarray.plot.line()` calls matplotlib.pyplot.plot passing in the index and the array values as x and y, respectively. So to make a line plot with blue triangles a matplotlib format string can be used:

    In [13]: air1d[:200].plot.line("b-^")
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-13-fd4a50ef6023> in <module>
    ----> 1 air1d[:200].plot.line("b-^")

    NameError: name 'air1d' is not defined

Note

Not all xarray plotting methods support passing positional arguments to the wrapped matplotlib functions, but they do all support keyword arguments.

Keyword arguments work the same way, and are more explicit.

    In [14]: air1d[:200].plot.line(color="purple", marker="o")
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-14-b193806a3ee8> in <module>
    ----> 1 air1d[:200].plot.line(color="purple", marker="o")

    NameError: name 'air1d' is not defined

#### Adding to Existing Axis

To add the plot to an existing axis pass in the axis as a keyword argument `ax`. This works for all xarray plotting methods. In this example `axes` is an array consisting of the left and right axes created by `plt.subplots`.

    In [15]: fig, axes = plt.subplots(ncols=2)

    In [16]: axes
    Out[16]: array([<AxesSubplot:>, <AxesSubplot:>], dtype=object)

    In [17]: air1d.plot(ax=axes[0])
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-17-47c7fe138f5e> in <module>
    ----> 1 air1d.plot(ax=axes[0])

    NameError: name 'air1d' is not defined

    In [18]: air1d.plot.hist(ax=axes[1])
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-18-41753485ddae> in <module>
    ----> 1 air1d.plot.hist(ax=axes[1])

    NameError: name 'air1d' is not defined

    In [19]: plt.tight_layout()

    In [20]: plt.draw()

On the right is a histogram created by `xarray.plot.hist()`.

#### Controlling the figure size

You can pass a `figsize` argument to all xarray’s plotting methods to control the figure size. For convenience, xarray’s plotting methods also support the `aspect` and `size` arguments which control the size of the resulting image via the formula `figsize = (aspect * size, size)`:

    In [21]: air1d.plot(aspect=2, size=3)
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-21-5fbaeea09bd8> in <module>
    ----> 1 air1d.plot(aspect=2, size=3)

    NameError: name 'air1d' is not defined

    In [22]: plt.tight_layout()

This feature also works with Faceting. For facet plots, `size` and `aspect` refer to a single panel (so that `aspect * size` gives the width of each facet in inches), while `figsize` refers to the entire figure (as for matplotlib’s `figsize` argument).

Note

If `figsize` or `size` are used, a new figure is created, so this is mutually exclusive with the `ax` argument.

Note

The convention used by xarray (`figsize = (aspect * size, size)`) is borrowed from seaborn: it is therefore not equivalent to matplotlib’s.

#### Determine x-axis values

Per default dimension coordinates are used for the x-axis (here the time coordinates). However, you can also use non-dimension coordinates, MultiIndex levels, and dimensions without coordinates along the x-axis. To illustrate this, let’s calculate a ‘decimal day’ (epoch) from the time and assign it as a non-dimension coordinate:

    In [23]: decimal_day = (air1d.time - air1d.time[0]) / pd.Timedelta("1d")
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-23-5895cff3b7f0> in <module>
    ----> 1 decimal_day = (air1d.time - air1d.time[0]) / pd.Timedelta("1d")

    NameError: name 'air1d' is not defined

    In [24]: air1d_multi = air1d.assign_coords(decimal_day=("time", decimal_day.data))
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-24-3d6c6379dd80> in <module>
    ----> 1 air1d_multi = air1d.assign_coords(decimal_day=("time", decimal_day.data))

    NameError: name 'air1d' is not defined

    In [25]: air1d_multi
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-25-8093f205bc0d> in <module>
    ----> 1 air1d_multi

    NameError: name 'air1d_multi' is not defined

To use `'decimal_day'` as x coordinate it must be explicitly specified:

    In [26]: air1d_multi.plot(x="decimal_day")
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-26-62b0a60dbc78> in <module>
    ----> 1 air1d_multi.plot(x="decimal_day")

    NameError: name 'air1d_multi' is not defined

Creating a new MultiIndex named `'date'` from `'time'` and `'decimal_day'`, it is also possible to use a MultiIndex level as x-axis:

    In [27]: air1d_multi = air1d_multi.set_index(date=("time", "decimal_day"))
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-27-595c3f6366f3> in <module>
    ----> 1 air1d_multi = air1d_multi.set_index(date=("time", "decimal_day"))

    NameError: name 'air1d_multi' is not defined

    In [28]: air1d_multi.plot(x="decimal_day")
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-28-62b0a60dbc78> in <module>
    ----> 1 air1d_multi.plot(x="decimal_day")

    NameError: name 'air1d_multi' is not defined

Finally, if a dataset does not have any coordinates it enumerates all data points:

    In [29]: air1d_multi = air1d_multi.drop("date")
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-29-08fd5644d617> in <module>
    ----> 1 air1d_multi = air1d_multi.drop("date")

    NameError: name 'air1d_multi' is not defined

    In [30]: air1d_multi.plot()
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-30-b0dd519cfb30> in <module>
    ----> 1 air1d_multi.plot()

    NameError: name 'air1d_multi' is not defined

The same applies to 2D plots below.

#### Multiple lines showing variation along a dimension

It is possible to make line plots of two-dimensional data by calling `xarray.plot.line()` with appropriate arguments. Consider the 3D variable `air` defined above. We can use line plots to check the variation of air temperature at three different latitudes along a longitude line:

    In [31]: air.isel(lon=10, lat=[19, 21, 22]).plot.line(x="time")
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-31-b834aeff258e> in <module>
    ----> 1 air.isel(lon=10, lat=[19, 21, 22]).plot.line(x="time")

    NameError: name 'air' is not defined

It is required to explicitly specify either

1. `x`: the dimension to be used for the x-axis, or

2. `hue`: the dimension you want to represent by multiple lines.

Thus, we could have made the previous plot by specifying `hue='lat'` instead of `x='time'`. If required, the automatic legend can be turned off using `add_legend=False`. Alternatively, `hue` can be passed directly to `xarray.plot.line()` as air.isel(lon=10, lat=[19,21,22]).plot.line(hue=’lat’).

#### Dimension along y-axis

It is also possible to make line plots such that the data are on the x-axis and a dimension is on the y-axis. This can be done by specifying the appropriate `y` keyword argument.

    In [32]: air.isel(time=10, lon=[10, 11]).plot(y="lat", hue="lon")
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-32-518619a2cae1> in <module>
    ----> 1 air.isel(time=10, lon=[10, 11]).plot(y="lat", hue="lon")

    NameError: name 'air' is not defined

#### Step plots

As an alternative, also a step plot similar to matplotlib’s `plt.step` can be made using 1D data.

    In [33]: air1d[:20].plot.step(where="mid")
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-33-7a6d04d5aa7c> in <module>
    ----> 1 air1d[:20].plot.step(where="mid")

    NameError: name 'air1d' is not defined

The argument `where` defines where the steps should be placed, options are `'pre'` (default), `'post'`, and `'mid'`. This is particularly handy when plotting data grouped with `Dataset.groupby_bins()`.

    In [34]: air_grp = air.mean(["time", "lon"]).groupby_bins("lat", [0, 23.5, 66.5, 90])
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-34-db25ce6e579b> in <module>
    ----> 1 air_grp = air.mean(["time", "lon"]).groupby_bins("lat", [0, 23.5, 66.5, 90])

    NameError: name 'air' is not defined

    In [35]: air_mean = air_grp.mean()
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-35-4361268a2eea> in <module>
    ----> 1 air_mean = air_grp.mean()

    NameError: name 'air_grp' is not defined

    In [36]: air_std = air_grp.std()
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-36-d5a1e0e5c771> in <module>
    ----> 1 air_std = air_grp.std()

    NameError: name 'air_grp' is not defined

    In [37]: air_mean.plot.step()
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-37-4162c0ac1db4> in <module>
    ----> 1 air_mean.plot.step()

    NameError: name 'air_mean' is not defined

    In [38]: (air_mean + air_std).plot.step(ls=":")
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-38-84b392f0a7d9> in <module>
    ----> 1 (air_mean + air_std).plot.step(ls=":")

    NameError: name 'air_mean' is not defined

    In [39]: (air_mean - air_std).plot.step(ls=":")
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-39-f2ef6402a2c4> in <module>
    ----> 1 (air_mean - air_std).plot.step(ls=":")

    NameError: name 'air_mean' is not defined

    In [40]: plt.ylim(-20, 30)
    Out[40]: (-20.0, 30.0)

    In [41]: plt.title("Zonal mean temperature")
    Out[41]: Text(0.5, 1.0, 'Zonal mean temperature')

In this case, the actual boundaries of the bins are used and the `where` argument is ignored.

### Other axes kwargs

The keyword arguments `xincrease` and `yincrease` let you control the axes direction.

    In [42]: air.isel(time=10, lon=[10, 11]).plot.line(
       ....:     y="lat", hue="lon", xincrease=False, yincrease=False
       ....: )
       ....:
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-42-af7734a4bdc7> in <module>
    ----> 1 air.isel(time=10, lon=[10, 11]).plot.line(
          2     y="lat", hue="lon", xincrease=False, yincrease=False
          3 )

    NameError: name 'air' is not defined

In addition, one can use `xscale, yscale` to set axes scaling; `xticks, yticks` to set axes ticks and `xlim, ylim` to set axes limits. These accept the same values as the matplotlib methods `Axes.set_(x,y)scale()`, `Axes.set_(x,y)ticks()`, `Axes.set_(x,y)lim()` respectively.

### Two Dimensions

#### Simple Example

The default method `DataArray.plot()` calls `xarray.plot.pcolormesh()` by default when the data is two-dimensional.

    In [43]: air2d = air.isel(time=500)
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-43-aeb322c2d11c> in <module>
    ----> 1 air2d = air.isel(time=500)

    NameError: name 'air' is not defined

    In [44]: air2d.plot()
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-44-267da278d579> in <module>
    ----> 1 air2d.plot()

    NameError: name 'air2d' is not defined

All 2d plots in xarray allow the use of the keyword arguments `yincrease` and `xincrease`.

    In [45]: air2d.plot(yincrease=False)
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-45-2643e81aa1a9> in <module>
    ----> 1 air2d.plot(yincrease=False)

    NameError: name 'air2d' is not defined

Note

We use `xarray.plot.pcolormesh()` as the default two-dimensional plot method because it is more flexible than `xarray.plot.imshow()`. However, for large arrays, `imshow` can be much faster than `pcolormesh`. If speed is important to you and you are plotting a regular mesh, consider using `imshow`.

#### Missing Values

Xarray plots data with Missing values.

    In [46]: bad_air2d = air2d.copy()
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-46-8362b177be7e> in <module>
    ----> 1 bad_air2d = air2d.copy()

    NameError: name 'air2d' is not defined

    In [47]: bad_air2d[dict(lat=slice(0, 10), lon=slice(0, 25))] = np.nan
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-47-9ea5b3533d69> in <module>
    ----> 1 bad_air2d[dict(lat=slice(0, 10), lon=slice(0, 25))] = np.nan

    NameError: name 'bad_air2d' is not defined

    In [48]: bad_air2d.plot()
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-48-d64f0a79960e> in <module>
    ----> 1 bad_air2d.plot()

    NameError: name 'bad_air2d' is not defined

#### Nonuniform Coordinates

It’s not necessary for the coordinates to be evenly spaced. Both `xarray.plot.pcolormesh()` (default) and `xarray.plot.contourf()` can produce plots with nonuniform coordinates.

    In [49]: b = air2d.copy()
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-49-8ff3ba4430a3> in <module>
    ----> 1 b = air2d.copy()

    NameError: name 'air2d' is not defined

    # Apply a nonlinear transformation to one of the coords
    In [50]: b.coords["lat"] = np.log(b.coords["lat"])
    ---------------------------------------------------------------------------
    KeyError                                  Traceback (most recent call last)
    /build/python-xarray-bL1QJU/python-xarray-0.21.1/xarray/core/dataarray.py in _getitem_coord(self, key)
        725         try:
    --> 726             var = self._coords[key]
        727         except KeyError:

    KeyError: 'lat'

    During handling of the above exception, another exception occurred:

    KeyError                                  Traceback (most recent call last)
    <ipython-input-50-ca9ab8433617> in <module>
    ----> 1 b.coords["lat"] = np.log(b.coords["lat"])

    /build/python-xarray-bL1QJU/python-xarray-0.21.1/xarray/core/coordinates.py in __getitem__(self, key)
        331
        332     def __getitem__(self, key: Hashable) -> "DataArray":
    --> 333         return self._data._getitem_coord(key)
        334
        335     def _update_coords(

    /build/python-xarray-bL1QJU/python-xarray-0.21.1/xarray/core/dataarray.py in _getitem_coord(self, key)
        727         except KeyError:
        728             dim_sizes = dict(zip(self.dims, self.shape))
    --> 729             _, key, var = _get_virtual_variable(
        730                 self._coords, key, self._level_coords, dim_sizes
        731             )

    /build/python-xarray-bL1QJU/python-xarray-0.21.1/xarray/core/dataset.py in _get_virtual_variable(variables, key, level_vars, dim_sizes)
        166         ref_var = dim_var.to_index_variable().get_level_variable(ref_name)
        167     else:
    --> 168         ref_var = variables[ref_name]
        169
        170     if var_name is None:

    KeyError: 'lat'

    In [51]: b.plot()
    Out[51]: [<matplotlib.lines.Line2D at 0x7f3d29af4f10>]

#### Other types of plot

There are several other options for plotting 2D data.

Contour plot using `DataArray.plot.contour()`

    In [52]: air2d.plot.contour()
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-52-31fa384ad4b9> in <module>
    ----> 1 air2d.plot.contour()

    NameError: name 'air2d' is not defined

Filled contour plot using `DataArray.plot.contourf()`

    In [53]: air2d.plot.contourf()
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-53-093fd2c74801> in <module>
    ----> 1 air2d.plot.contourf()

    NameError: name 'air2d' is not defined

Surface plot using `DataArray.plot.surface()`

    # transpose just to make the example look a bit nicer
    In [54]: air2d.T.plot.surface()
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-54-7075a7600822> in <module>
    ----> 1 air2d.T.plot.surface()

    NameError: name 'air2d' is not defined

#### Calling Matplotlib

Since this is a thin wrapper around matplotlib, all the functionality of matplotlib is available.

    In [55]: air2d.plot(cmap=plt.cm.Blues)
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-55-b347cf3a8c47> in <module>
    ----> 1 air2d.plot(cmap=plt.cm.Blues)

    NameError: name 'air2d' is not defined

    In [56]: plt.title("These colors prove North America\nhas fallen in the ocean")
    Out[56]: Text(0.5, 1.0, 'These colors prove North America\nhas fallen in the ocean')

    In [57]: plt.ylabel("latitude")
    Out[57]: Text(0, 0.5, 'latitude')

    In [58]: plt.xlabel("longitude")
    Out[58]: Text(0.5, 0, 'longitude')

    In [59]: plt.tight_layout()

    In [60]: plt.draw()

Note

Xarray methods update label information and generally play around with the axes. So any kind of updates to the plot should be done after the call to the xarray’s plot. In the example below, `plt.xlabel` effectively does nothing, since `d_ylog.plot()` updates the xlabel.

    In [61]: plt.xlabel("Never gonna see this.")
    Out[61]: Text(0.5, 0, 'Never gonna see this.')

    In [62]: air2d.plot()
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-62-267da278d579> in <module>
    ----> 1 air2d.plot()

    NameError: name 'air2d' is not defined

    In [63]: plt.draw()

#### Colormaps

Xarray borrows logic from Seaborn to infer what kind of color map to use. For example, consider the original data in Kelvins rather than Celsius:

    In [64]: airtemps.air.isel(time=0).plot()
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-64-518aaa410d12> in <module>
    ----> 1 airtemps.air.isel(time=0).plot()

    NameError: name 'airtemps' is not defined

The Celsius data contain 0, so a diverging color map was used. The Kelvins do not have 0, so the default color map was used.

#### Robust

Outliers often have an extreme effect on the output of the plot. Here we add two bad data points. This affects the color scale, washing out the plot.

    In [65]: air_outliers = airtemps.air.isel(time=0).copy()
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-65-07230c544b46> in <module>
    ----> 1 air_outliers = airtemps.air.isel(time=0).copy()

    NameError: name 'airtemps' is not defined

    In [66]: air_outliers[0, 0] = 100
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-66-27ab3b18e532> in <module>
    ----> 1 air_outliers[0, 0] = 100

    NameError: name 'air_outliers' is not defined

    In [67]: air_outliers[-1, -1] = 400
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-67-a5788991cda7> in <module>
    ----> 1 air_outliers[-1, -1] = 400

    NameError: name 'air_outliers' is not defined

    In [68]: air_outliers.plot()
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-68-143cc03c2ff6> in <module>
    ----> 1 air_outliers.plot()

    NameError: name 'air_outliers' is not defined

This plot shows that we have outliers. The easy way to visualize the data without the outliers is to pass the parameter `robust=True`. This will use the 2nd and 98th percentiles of the data to compute the color limits.

    In [69]: air_outliers.plot(robust=True)
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-69-cdc0b84add6a> in <module>
    ----> 1 air_outliers.plot(robust=True)

    NameError: name 'air_outliers' is not defined

Observe that the ranges of the color bar have changed. The arrows on the color bar indicate that the colors include data points outside the bounds.

#### Discrete Colormaps

It is often useful, when visualizing 2d data, to use a discrete colormap, rather than the default continuous colormaps that matplotlib uses. The `levels` keyword argument can be used to generate plots with discrete colormaps. For example, to make a plot with 8 discrete color intervals:

    In [70]: air2d.plot(levels=8)
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-70-89bc1504b066> in <module>
    ----> 1 air2d.plot(levels=8)

    NameError: name 'air2d' is not defined

It is also possible to use a list of levels to specify the boundaries of the discrete colormap:

    In [71]: air2d.plot(levels=[0, 12, 18, 30])
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-71-bbd038f02d85> in <module>
    ----> 1 air2d.plot(levels=[0, 12, 18, 30])

    NameError: name 'air2d' is not defined

You can also specify a list of discrete colors through the `colors` argument:

    In [72]: flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"]

    In [73]: air2d.plot(levels=[0, 12, 18, 30], colors=flatui)
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-73-d56a56059dba> in <module>
    ----> 1 air2d.plot(levels=[0, 12, 18, 30], colors=flatui)

    NameError: name 'air2d' is not defined

Finally, if you have Seaborn installed, you can also specify a seaborn color palette to the `cmap` argument. Note that `levels` must be specified with seaborn color palettes if using `imshow` or `pcolormesh` (but not with `contour` or `contourf`, since levels are chosen automatically).

    In [74]: air2d.plot(levels=10, cmap="husl")
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-74-bb3399e74823> in <module>
    ----> 1 air2d.plot(levels=10, cmap="husl")

    NameError: name 'air2d' is not defined

    In [75]: plt.draw()

### Faceting

Faceting here refers to splitting an array along one or two dimensions and plotting each group. Xarray’s basic plotting is useful for plotting two dimensional arrays. What about three or four dimensional arrays? That’s where facets become helpful. The general approach to plotting here is called “small multiples”, where the same kind of plot is repeated multiple times, and the specific use of small multiples to display the same relationship conditioned on one ore more other variables is often called a “trellis plot”.

Consider the temperature data set. There are 4 observations per day for two years which makes for 2920 values along the time dimension. One way to visualize this data is to make a separate plot for each time period.

The faceted dimension should not have too many values; faceting on the time dimension will produce 2920 plots. That’s too much to be helpful. To handle this situation try performing an operation that reduces the size of the data in some way. For example, we could compute the average air temperature for each month and reduce the size of this dimension from 2920 -> 12. A simpler way is to just take a slice on that dimension. So let’s use a slice to pick 6 times throughout the first year.

    In [76]: t = air.isel(time=slice(0, 365 * 4, 250))
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-76-d2310b76d025> in <module>
    ----> 1 t = air.isel(time=slice(0, 365 * 4, 250))

    NameError: name 'air' is not defined

    In [77]: t.coords
    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    <ipython-input-77-22319bc55475> in <module>
    ----> 1 t.coords

    AttributeError: 'numpy.ndarray' object has no attribute 'coords'

#### Simple Example

The easiest way to create faceted plots is to pass in `row` or `col` arguments to the xarray plotting methods/functions. This returns a `xarray.plot.FacetGrid` object.

    In [78]: g_simple = t.plot(x="lon", y="lat", col="time", col_wrap=3)
    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    <ipython-input-78-c7d6afd7f8c5> in <module>
    ----> 1 g_simple = t.plot(x="lon", y="lat", col="time", col_wrap=3)

    AttributeError: 'numpy.ndarray' object has no attribute 'plot'

Faceting also works for line plots.

    In [79]: g_simple_line = t.isel(lat=slice(0, None, 4)).plot(
       ....:     x="lon", hue="lat", col="time", col_wrap=3
       ....: )
       ....:
    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    <ipython-input-79-9f34adcd8fa1> in <module>
    ----> 1 g_simple_line = t.isel(lat=slice(0, None, 4)).plot(
          2     x="lon", hue="lat", col="time", col_wrap=3
          3 )

    AttributeError: 'numpy.ndarray' object has no attribute 'isel'

#### 4 dimensional

For 4 dimensional arrays we can use the rows and columns of the grids. Here we create a 4 dimensional array by taking the original data and adding a fixed amount. Now we can see how the temperature maps would compare if one were much hotter.

    In [80]: t2 = t.isel(time=slice(0, 2))
    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    <ipython-input-80-529e418b1a0d> in <module>
    ----> 1 t2 = t.isel(time=slice(0, 2))

    AttributeError: 'numpy.ndarray' object has no attribute 'isel'

    In [81]: t4d = xr.concat([t2, t2 + 40], pd.Index(["normal", "hot"], name="fourth_dim"))
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-81-59de69f7967f> in <module>
    ----> 1 t4d = xr.concat([t2, t2 + 40], pd.Index(["normal", "hot"], name="fourth_dim"))

    NameError: name 't2' is not defined

    # This is a 4d array
    In [82]: t4d.coords
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-82-30c5897da9ca> in <module>
    ----> 1 t4d.coords

    NameError: name 't4d' is not defined

    In [83]: t4d.plot(x="lon", y="lat", col="time", row="fourth_dim")
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-83-e2f6592e418d> in <module>
    ----> 1 t4d.plot(x="lon", y="lat", col="time", row="fourth_dim")

    NameError: name 't4d' is not defined

#### Other features

Faceted plotting supports other arguments common to xarray 2d plots.

    In [84]: hasoutliers = t.isel(time=slice(0, 5)).copy()
    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    <ipython-input-84-2c58f0b7b3c1> in <module>
    ----> 1 hasoutliers = t.isel(time=slice(0, 5)).copy()

    AttributeError: 'numpy.ndarray' object has no attribute 'isel'

    In [85]: hasoutliers[0, 0, 0] = -100
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-85-610f8fdf815a> in <module>
    ----> 1 hasoutliers[0, 0, 0] = -100

    NameError: name 'hasoutliers' is not defined

    In [86]: hasoutliers[-1, -1, -1] = 400
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-86-faa35bc97fe5> in <module>
    ----> 1 hasoutliers[-1, -1, -1] = 400

    NameError: name 'hasoutliers' is not defined

    In [87]: g = hasoutliers.plot.pcolormesh(
       ....:     "lon",
       ....:     "lat",
       ....:     col="time",
       ....:     col_wrap=3,
       ....:     robust=True,
       ....:     cmap="viridis",
       ....:     cbar_kwargs={"label": "this has outliers"},
       ....: )
       ....:
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-87-37571ad10fcd> in <module>
    ----> 1 g = hasoutliers.plot.pcolormesh(
          2     "lon",
          3     "lat",
          4     col="time",
          5     col_wrap=3,

    NameError: name 'hasoutliers' is not defined

#### FacetGrid Objects

The object returned, `g` in the above examples, is a `FacetGrid` object that links a `DataArray` to a matplotlib figure with a particular structure. This object can be used to control the behavior of the multiple plots. It borrows an API and code from Seaborn’s FacetGrid. The structure is contained within the `axes` and `name_dicts` attributes, both 2d NumPy object arrays.

    In [88]: g.axes
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-88-f75038449fe8> in <module>
    ----> 1 g.axes

    NameError: name 'g' is not defined

    In [89]: g.name_dicts
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-89-2df4766167c7> in <module>
    ----> 1 g.name_dicts

    NameError: name 'g' is not defined

It’s possible to select the `xarray.DataArray` or `xarray.Dataset` corresponding to the FacetGrid through the `name_dicts`.

    In [90]: g.data.loc[g.name_dicts[0, 0]]
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-90-d47bb47790a1> in <module>
    ----> 1 g.data.loc[g.name_dicts[0, 0]]

    NameError: name 'g' is not defined

Here is an example of using the lower level API and then modifying the axes after they have been plotted.

    In [91]: g = t.plot.imshow("lon", "lat", col="time", col_wrap=3, robust=True)
    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    <ipython-input-91-cfa13669851c> in <module>
    ----> 1 g = t.plot.imshow("lon", "lat", col="time", col_wrap=3, robust=True)

    AttributeError: 'numpy.ndarray' object has no attribute 'plot'

    In [92]: for i, ax in enumerate(g.axes.flat):
       ....:     ax.set_title("Air Temperature %d" % i)
       ....:
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-92-5a61f165554e> in <module>
    ----> 1 for i, ax in enumerate(g.axes.flat):
          2     ax.set_title("Air Temperature %d" % i)

    NameError: name 'g' is not defined

    In [93]: bottomright = g.axes[-1, -1]
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-93-1d727aa86050> in <module>
    ----> 1 bottomright = g.axes[-1, -1]

    NameError: name 'g' is not defined

    In [94]: bottomright.annotate("bottom right", (240, 40))
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-94-5266a4458c52> in <module>
    ----> 1 bottomright.annotate("bottom right", (240, 40))

    NameError: name 'bottomright' is not defined

    In [95]: plt.draw()

`FacetGrid` objects have methods that let you customize the automatically generated axis labels, axis ticks and plot titles. See `set_titles()`, `set_xlabels()`, `set_ylabels()` and `set_ticks()` for more information. Plotting functions can be applied to each subset of the data by calling `map_dataarray()` or to each subplot by calling `map()`.

TODO: add an example of using the `map` method to plot dataset variables (e.g., with `plt.quiver`).

## Datasets

Xarray has limited support for plotting Dataset variables against each other. Consider this dataset

    In [96]: ds = xr.tutorial.scatter_example_dataset()

    In [97]: ds
    Out[97]:
    <xarray.Dataset>
    Dimensions:  (x: 3, y: 11, z: 4, w: 4)
    Coordinates:
      * x        (x) int64 0 1 2
      * y        (y) float64 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
      * z        (z) int64 0 1 2 3
      * w        (w) <U5 'one' 'two' 'three' 'five'
    Data variables:
        A        (x, y, z, w) float64 -0.007645 -0.006474 ... -0.05442 0.1955
        B        (x, y, z, w) float64 0.0 0.0 0.0 0.0 ... 1.398 1.398 1.406 1.481

### Scatter

Suppose we want to scatter `A` against `B`

    In [98]: ds.plot.scatter(x="A", y="B")
    Out[98]: <matplotlib.collections.PathCollection at 0x7f3d02f97c40>

The `hue` kwarg lets you vary the color by variable value

    In [99]: ds.plot.scatter(x="A", y="B", hue="w")
    Out[99]:
    [<matplotlib.collections.PathCollection at 0x7f3d02e2bac0>,
     <matplotlib.collections.PathCollection at 0x7f3d02e56b90>,
     <matplotlib.collections.PathCollection at 0x7f3d02e571c0>,
     <matplotlib.collections.PathCollection at 0x7f3d02e578b0>]

When `hue` is specified, a colorbar is added for numeric `hue` DataArrays by default and a legend is added for non-numeric `hue` DataArrays (as above). You can force a legend instead of a colorbar by setting `hue_style='discrete'`. Additionally, the boolean kwarg `add_guide` can be used to prevent the display of a legend or colorbar (as appropriate).

    In [100]: ds = ds.assign(w=[1, 2, 3, 5])

    In [101]: ds.plot.scatter(x="A", y="B", hue="w", hue_style="discrete")
    Out[101]:
    [<matplotlib.collections.PathCollection at 0x7f3d02e8e7d0>,
     <matplotlib.collections.PathCollection at 0x7f3d02e8d360>,
     <matplotlib.collections.PathCollection at 0x7f3d02e8ff70>,
     <matplotlib.collections.PathCollection at 0x7f3d02ebec80>]

The `markersize` kwarg lets you vary the point’s size by variable value. You can additionally pass `size_norm` to control how the variable’s values are mapped to point sizes.

    In [102]: ds.plot.scatter(x="A", y="B", hue="z", hue_style="discrete", markersize="z")
    Out[102]:
    [<matplotlib.collections.PathCollection at 0x7f3d02ef37c0>,
     <matplotlib.collections.PathCollection at 0x7f3d02ef2bc0>,
     <matplotlib.collections.PathCollection at 0x7f3d02ef3c10>,
     <matplotlib.collections.PathCollection at 0x7f3d02ef3820>]

Faceting is also possible

    In [103]: ds.plot.scatter(x="A", y="B", col="x", row="z", hue="w", hue_style="discrete")
    Out[103]: <xarray.plot.facetgrid.FacetGrid at 0x7f3d02ef3b20>

For more advanced scatter plots, we recommend converting the relevant data variables to a pandas DataFrame and using the extensive plotting capabilities of `seaborn`.

### Quiver

Visualizing vector fields is supported with quiver plots:

    In [104]: ds.isel(w=1, z=1).plot.quiver(x="x", y="y", u="A", v="B")
    Out[104]: <matplotlib.quiver.Quiver at 0x7f3d02b124a0>

where `u` and `v` denote the x and y direction components of the arrow vectors. Again, faceting is also possible:

    In [105]: ds.plot.quiver(x="x", y="y", u="A", v="B", col="w", row="z", scale=4)
    Out[105]: <xarray.plot.facetgrid.FacetGrid at 0x7f3d02b3dfc0>

`scale` is required for faceted quiver plots. The scale determines the number of data units per arrow length unit, i.e. a smaller scale parameter makes the arrow longer.

### Streamplot

Visualizing vector fields is also supported with streamline plots:

    In [106]: ds.isel(w=1, z=1).plot.streamplot(x="x", y="y", u="A", v="B")
    Out[106]: <matplotlib.collections.LineCollection at 0x7f3d026af1c0>

where `u` and `v` denote the x and y direction components of the vectors tangent to the streamlines. Again, faceting is also possible:

    In [107]: ds.plot.streamplot(x="x", y="y", u="A", v="B", col="w", row="z")
    Out[107]: <xarray.plot.facetgrid.FacetGrid at 0x7f3d0273ce50>

## Maps

To follow this section you’ll need to have Cartopy installed and working.

This script will plot the air temperature on a map.

    In [108]: import cartopy.crs as ccrs

    In [109]: air = xr.tutorial.open_dataset("air_temperature").air
    ---------------------------------------------------------------------------
    ModuleNotFoundError                       Traceback (most recent call last)
    /build/python-xarray-bL1QJU/python-xarray-0.21.1/xarray/tutorial.py in open_dataset(name, cache, cache_dir, engine, **kws)
        113     try:
    --> 114         import pooch
        115     except ImportError as e:

    ModuleNotFoundError: No module named 'pooch'

    The above exception was the direct cause of the following exception:

    ImportError                               Traceback (most recent call last)
    <ipython-input-109-dae4459a9d05> in <module>
    ----> 1 air = xr.tutorial.open_dataset("air_temperature").air

    /build/python-xarray-bL1QJU/python-xarray-0.21.1/xarray/tutorial.py in open_dataset(name, cache, cache_dir, engine, **kws)
        114         import pooch
        115     except ImportError as e:
    --> 116         raise ImportError(
        117             "tutorial.open_dataset depends on pooch to download and manage datasets."
        118             " To proceed please install pooch."

    ImportError: tutorial.open_dataset depends on pooch to download and manage datasets. To proceed please install pooch.

    In [110]: p = air.isel(time=0).plot(
       .....:     subplot_kws=dict(projection=ccrs.Orthographic(-80, 35), facecolor="gray"),
       .....:     transform=ccrs.PlateCarree(),
       .....: )
       .....:
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-110-3abb1c6d1b71> in <module>
    ----> 1 p = air.isel(time=0).plot(
          2     subplot_kws=dict(projection=ccrs.Orthographic(-80, 35), facecolor="gray"),
          3     transform=ccrs.PlateCarree(),
          4 )

    NameError: name 'air' is not defined

    In [111]: p.axes.set_global()
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-111-c743efa1dcbe> in <module>
    ----> 1 p.axes.set_global()

    NameError: name 'p' is not defined

    In [112]: p.axes.coastlines()
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-112-964fc47f8cb2> in <module>
    ----> 1 p.axes.coastlines()

    NameError: name 'p' is not defined

When faceting on maps, the projection can be transferred to the `plot` function using the `subplot_kws` keyword. The axes for the subplots created by faceting are accessible in the object returned by `plot`:

    In [113]: p = air.isel(time=[0, 4]).plot(
       .....:     transform=ccrs.PlateCarree(),
       .....:     col="time",
       .....:     subplot_kws={"projection": ccrs.Orthographic(-80, 35)},
       .....: )
       .....:
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-113-bcd752624ac8> in <module>
    ----> 1 p = air.isel(time=[0, 4]).plot(
          2     transform=ccrs.PlateCarree(),
          3     col="time",
          4     subplot_kws={"projection": ccrs.Orthographic(-80, 35)},
          5 )

    NameError: name 'air' is not defined

    In [114]: for ax in p.axes.flat:
       .....:     ax.coastlines()
       .....:     ax.gridlines()
       .....:
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-114-a8809283349e> in <module>
    ----> 1 for ax in p.axes.flat:
          2     ax.coastlines()
          3     ax.gridlines()

    NameError: name 'p' is not defined

    In [115]: plt.draw()

## Details

### Ways to Use

There are three ways to use the xarray plotting functionality:

1. Use `plot` as a convenience method for a DataArray.

2. Access a specific plotting method from the `plot` attribute of a DataArray.

3. Directly from the xarray plot submodule.

These are provided for user convenience; they all call the same code.

    In [116]: import xarray.plot as xplt

    In [117]: da = xr.DataArray(range(5))

    In [118]: fig, axes = plt.subplots(ncols=2, nrows=2)

    In [119]: da.plot(ax=axes[0, 0])
    Out[119]: [<matplotlib.lines.Line2D at 0x7f3d02d9cc10>]

    In [120]: da.plot.line(ax=axes[0, 1])
    Out[120]: [<matplotlib.lines.Line2D at 0x7f3d02d9cc70>]

    In [121]: xplt.plot(da, ax=axes[1, 0])
    Out[121]: [<matplotlib.lines.Line2D at 0x7f3d01490490>]

    In [122]: xplt.line(da, ax=axes[1, 1])
    Out[122]: [<matplotlib.lines.Line2D at 0x7f3d01491e40>]

    In [123]: plt.tight_layout()

    In [124]: plt.draw()

Here the output is the same. Since the data is 1 dimensional the line plot was used.

The convenience method `xarray.DataArray.plot()` dispatches to an appropriate plotting function based on the dimensions of the `DataArray` and whether the coordinates are sorted and uniformly spaced. This table describes what gets plotted:

Dimensions | Plotting function
1 | `xarray.plot.line()`
2 | `xarray.plot.pcolormesh()`
Anything else | `xarray.plot.hist()`

### Coordinates

If you’d like to find out what’s really going on in the coordinate system, read on.

    In [125]: a0 = xr.DataArray(np.zeros((4, 3, 2)), dims=("y", "x", "z"), name="temperature")

    In [126]: a0[0, 0, 0] = 1

    In [127]: a = a0.isel(z=0)

    In [128]: a
    Out[128]:
    <xarray.DataArray 'temperature' (y: 4, x: 3)>
    array([[1., 0., 0.],
           [0., 0., 0.],
           [0., 0., 0.],
           [0., 0., 0.]])
    Dimensions without coordinates: y, x

The plot will produce an image corresponding to the values of the array. Hence the top left pixel will be a different color than the others. Before reading on, you may want to look at the coordinates and think carefully about what the limits, labels, and orientation for each of the axes should be.

    In [129]: a.plot()
    Out[129]: <matplotlib.collections.QuadMesh at 0x7f3d0135caf0>

It may seem strange that the values on the y axis are decreasing with -0.5 on the top. This is because the pixels are centered over their coordinates, and the axis labels and ranges correspond to the values of the coordinates.

### Multidimensional coordinates

See also: Working with Multidimensional Coordinates.

You can plot irregular grids defined by multidimensional coordinates with xarray, but you’ll have to tell the plot function to use these coordinates instead of the default ones:

    In [130]: lon, lat = np.meshgrid(np.linspace(-20, 20, 5), np.linspace(0, 30, 4))

    In [131]: lon += lat / 10

    In [132]: lat += lon / 10

    In [133]: da = xr.DataArray(
       .....:     np.arange(20).reshape(4, 5),
       .....:     dims=["y", "x"],
       .....:     coords={"lat": (("y", "x"), lat), "lon": (("y", "x"), lon)},
       .....: )
       .....:

    In [134]: da.plot.pcolormesh("lon", "lat")
    Out[134]: <matplotlib.collections.QuadMesh at 0x7f3d0120a1d0>

Note that in this case, xarray still follows the pixel centered convention. This might be undesirable in some cases, for example when your data is defined on a polar projection (GH781). This is why the default is to not follow this convention when plotting on a map:

    In [135]: import cartopy.crs as ccrs

    In [136]: ax = plt.subplot(projection=ccrs.PlateCarree())

    In [137]: da.plot.pcolormesh("lon", "lat", ax=ax)
    Out[137]: <cartopy.mpl.geocollection.GeoQuadMesh at 0x7f3d0111b850>

    In [138]: ax.scatter(lon, lat, transform=ccrs.PlateCarree())
    Out[138]: <matplotlib.collections.PathCollection at 0x7f3d01179cc0>

    In [139]: ax.coastlines()
    Out[139]: <cartopy.mpl.feature_artist.FeatureArtist at 0x7f3d012d07f0>

    In [140]: ax.gridlines(draw_labels=True)
    Out[140]: <cartopy.mpl.gridliner.Gridliner at 0x7f3d01179fc0>

You can however decide to infer the cell boundaries and use the `infer_intervals` keyword:

    In [141]: ax = plt.subplot(projection=ccrs.PlateCarree())

    In [142]: da.plot.pcolormesh("lon", "lat", ax=ax, infer_intervals=True)
    Out[142]: <cartopy.mpl.geocollection.GeoQuadMesh at 0x7f3d00fce680>

    In [143]: ax.scatter(lon, lat, transform=ccrs.PlateCarree())
    Out[143]: <matplotlib.collections.PathCollection at 0x7f3d00e14d60>

    In [144]: ax.coastlines()
    Out[144]: <cartopy.mpl.feature_artist.FeatureArtist at 0x7f3d0115b280>

    In [145]: ax.gridlines(draw_labels=True)
    Out[145]: <cartopy.mpl.gridliner.Gridliner at 0x7f3d011bf8b0>

Note

The data model of xarray does not support datasets with cell boundaries yet. If you want to use these coordinates, you’ll have to make the plots outside the xarray framework.

One can also make line plots with multidimensional coordinates. In this case, `hue` must be a dimension name, not a coordinate name.

    In [146]: f, ax = plt.subplots(2, 1)

    In [147]: da.plot.line(x="lon", hue="y", ax=ax[0])
    Out[147]:
    [<matplotlib.lines.Line2D at 0x7f3d00ebb370>,
     <matplotlib.lines.Line2D at 0x7f3d00ebb3d0>,
     <matplotlib.lines.Line2D at 0x7f3d00ebb610>,
     <matplotlib.lines.Line2D at 0x7f3d00ebb730>]

    In [148]: da.plot.line(x="lon", hue="x", ax=ax[1])
    Out[148]:
    [<matplotlib.lines.Line2D at 0x7f3d00ee5b10>,
     <matplotlib.lines.Line2D at 0x7f3d00ee5bd0>,
     <matplotlib.lines.Line2D at 0x7f3d00ee5cc0>,
     <matplotlib.lines.Line2D at 0x7f3d00ee5de0>,
     <matplotlib.lines.Line2D at 0x7f3d00ee5f00>]