Plotting

Introduction

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

Xray’s plotting capabilities are centered around xray.DataArray objects. To plot xray.Dataset objects simply access the relevant DataArrays, ie dset['var1']. 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.

Xray 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 xray can plot.

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: “Composable, declarative data structures for building even complex visualizations easily.” Works for 2d datasets.
  • 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 xray

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

In [5]: airtemps = xray.tutorial.load_dataset('air_temperature')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-dd99824c922a> in <module>()
----> 1 airtemps = xray.tutorial.load_dataset('air_temperature')

/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/tutorial.pyc in load_dataset(name, cache, cache_dir, github_url, **kws)
     53         _urlretrieve(url, localfile)
     54 
---> 55     ds = _open_dataset(localfile, **kws).load()
     56 
     57     if not cache:

/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/backends/api.pyc in open_dataset(filename_or_obj, group, decode_cf, mask_and_scale, decode_times, concat_characters, decode_coords, engine, chunks, lock, drop_variables)
    221             lock = _default_lock(filename_or_obj, engine)
    222         with close_on_error(store):
--> 223             return maybe_decode_store(store, lock)
    224     else:
    225         if engine is not None and engine != 'scipy':

/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/backends/api.pyc in maybe_decode_store(store, lock)
    156             store, mask_and_scale=mask_and_scale, decode_times=decode_times,
    157             concat_characters=concat_characters, decode_coords=decode_coords,
--> 158             drop_variables=drop_variables)
    159 
    160         if chunks is not None:

/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/conventions.pyc in decode_cf(obj, concat_characters, mask_and_scale, decode_times, decode_coords, drop_variables)
    888     vars, attrs, coord_names = decode_cf_variables(
    889         vars, attrs, concat_characters, mask_and_scale, decode_times,
--> 890         decode_coords, drop_variables=drop_variables)
    891     ds = Dataset(vars, attrs=attrs)
    892     ds = ds.set_coords(coord_names.union(extra_coords))

/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/conventions.pyc in decode_cf_variables(variables, attributes, concat_characters, mask_and_scale, decode_times, decode_coords, drop_variables)
    823         new_vars[k] = decode_cf_variable(
    824             v, concat_characters=concat, mask_and_scale=mask_and_scale,
--> 825             decode_times=decode_times)
    826         if decode_coords:
    827             var_attrs = new_vars[k].attrs

/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/conventions.pyc in decode_cf_variable(var, concat_characters, mask_and_scale, decode_times, decode_endianness)
    764             units = pop_to(attributes, encoding, 'units')
    765             calendar = pop_to(attributes, encoding, 'calendar')
--> 766             data = DecodedCFDatetimeArray(data, units, calendar)
    767         elif attributes['units'] in TIME_UNITS:
    768             # timedelta

/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/conventions.pyc in __init__(self, array, units, calendar)
    389             if not PY3:
    390                 msg += ' Full traceback:\n' + traceback.format_exc()
--> 391             raise ValueError(msg)
    392         else:
    393             self._dtype = getattr(result, 'dtype', np.dtype('object'))

ValueError: unable to decode time units u'hours since 1800-01-01' with calendar u'standard'. Try opening your dataset with decode_times=False. Full traceback:
Traceback (most recent call last):
  File "/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/conventions.py", line 382, in __init__
    result = decode_cf_datetime(example_value, units, calendar)
  File "/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/conventions.py", line 146, in decode_cf_datetime
    dates = (pd.to_timedelta(flat_num_dates, delta) + ref_date).values
  File "/usr/lib/python2.7/dist-packages/pandas/tseries/timedeltas.py", line 59, in to_timedelta
    return _convert_listlike(arg, box=box)
  File "/usr/lib/python2.7/dist-packages/pandas/tseries/timedeltas.py", line 46, in _convert_listlike
    value = np.array([ _coerce_scalar_to_timedelta_type(r, unit=unit) for r in arg ])
  File "/usr/lib/python2.7/dist-packages/pandas/tseries/timedeltas.py", line 82, in _coerce_scalar_to_timedelta_type
    return tslib.convert_to_timedelta(r,unit)
  File "tslib.pyx", line 1186, in pandas.tslib.convert_to_timedelta (pandas/tslib.c:20014)
  File "tslib.pyx", line 1241, in pandas.tslib.convert_to_timedelta64 (pandas/tslib.c:20660)
ValueError: Invalid type for timedelta scalar: <type 'numpy.float64'>


In [6]: airtemps
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-6-97bf1d613dea> 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-ddb2b18dbefa> in <module>()
----> 1 air = airtemps.air - 273.15

NameError: name 'airtemps' is not defined

One Dimension

Simple Example

Xray uses the coordinate name to label the x axis.

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

NameError: name 'air' is not defined

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

NameError: name 'air1d' is not defined
_images/plotting_1d_simple.png

Additional Arguments

Additional arguments are passed directly to the matplotlib function which does the work. For example, xray.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 [10]: air1d[:200].plot.line('b-^')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-10-19f2d4f35560> in <module>()
----> 1 air1d[:200].plot.line('b-^')

NameError: name 'air1d' is not defined
_images/plotting_1d_additional_args.png

Note

Not all xray 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 [11]: air1d[:200].plot.line(color='purple', marker='o')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-11-6cf466530841> in <module>()
----> 1 air1d[:200].plot.line(color='purple', marker='o')

NameError: name 'air1d' is not defined
_images/plotting_example_sin3.png

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 xray plotting methods. In this example axes is an array consisting of the left and right axes created by plt.subplots.

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

In [13]: axes
Out[13]: 
array([<matplotlib.axes.AxesSubplot object at 0x7f0130b1bb90>,
       <matplotlib.axes.AxesSubplot object at 0x7f013105cc10>], dtype=object)

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

NameError: name 'air1d' is not defined

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

NameError: name 'air1d' is not defined

In [16]: plt.tight_layout()

In [17]: plt.show()
_images/plotting_example_existing_axes.png

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

Two Dimensions

Simple Example

The default method xray.DataArray.plot() sees that the data is 2 dimensional and calls xray.plot.pcolormesh().

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

NameError: name 'air' is not defined

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

NameError: name 'air2d' is not defined
_images/2d_simple.png

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

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

NameError: name 'air2d' is not defined
_images/2d_simple_yincrease.png

Note

We use xray.plot.pcolormesh() as the default two-dimensional plot method because it is more flexible than xray.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

Xray plots data with Missing values.

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

NameError: name 'air2d' is not defined

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

NameError: name 'bad_air2d' is not defined

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

NameError: name 'bad_air2d' is not defined
_images/plotting_missing_values.png

Nonuniform Coordinates

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

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

NameError: name 'air2d' is not defined

# Apply a nonlinear transformation to one of the coords
In [25]: b.coords['lat'] = np.log(b.coords['lat'])
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-25-498a04a8c870> in <module>()
----> 1 b.coords['lat'] = np.log(b.coords['lat'])

/home/docs/checkouts/readthedocs.org/user_builds/xray/envs/v0.6.1/local/lib/python2.7/site-packages/xray-0.6.1-py2.7.egg/xray/core/coordinates.pyc in __getitem__(self, key)
     49             return self._dataset[key]
     50         else:
---> 51             raise KeyError(key)
     52 
     53     def __setitem__(self, key, value):

KeyError: 'lat'

In [26]: b.plot()
Out[26]: [<matplotlib.lines.Line2D at 0x7f01297d2c50>]
_images/plotting_nonuniform_coords.png

Calling Matplotlib

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

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

NameError: name 'air2d' is not defined

In [28]: plt.title('These colors prove North America\nhas fallen in the ocean')
Out[28]: <matplotlib.text.Text at 0x7f0129dba210>

In [29]: plt.ylabel('latitude')
Out[29]: <matplotlib.text.Text at 0x7f0129ca6950>

In [30]: plt.xlabel('longitude')
Out[30]: <matplotlib.text.Text at 0x7f0129d34950>

In [31]: plt.tight_layout()

In [32]: plt.show()
_images/plotting_2d_call_matplotlib.png

Note

Xray 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 xray’s plot. In the example below, plt.xlabel effectively does nothing, since d_ylog.plot() updates the xlabel.

In [33]: plt.xlabel('Never gonna see this.')
Out[33]: <matplotlib.text.Text at 0x7f0129885f50>

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

NameError: name 'air2d' is not defined

In [35]: plt.show()
_images/plotting_2d_call_matplotlib2.png

Colormaps

Xray 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 [36]: airtemps.air.isel(time=0).plot()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-36-8144c2998176> in <module>()
----> 1 airtemps.air.isel(time=0).plot()

NameError: name 'airtemps' is not defined
_images/plotting_kelvin.png

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 [37]: air_outliers = airtemps.air.isel(time=0).copy()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-37-33d7f88a80d6> in <module>()
----> 1 air_outliers = airtemps.air.isel(time=0).copy()

NameError: name 'airtemps' is not defined

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

NameError: name 'air_outliers' is not defined

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

NameError: name 'air_outliers' is not defined

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

NameError: name 'air_outliers' is not defined
_images/plotting_robust1.png

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 [41]: air_outliers.plot(robust=True)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-41-fab29a3e3a92> in <module>()
----> 1 air_outliers.plot(robust=True)

NameError: name 'air_outliers' is not defined
_images/plotting_robust2.png

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 [42]: air2d.plot(levels=8)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-42-1e5e1bceae75> in <module>()
----> 1 air2d.plot(levels=8)

NameError: name 'air2d' is not defined
_images/plotting_discrete_levels.png

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

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

NameError: name 'air2d' is not defined
_images/plotting_listed_levels.png

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

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

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

NameError: name 'air2d' is not defined
_images/plotting_custom_colors_levels.png

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 [46]: air2d.plot(levels=10, cmap='husl')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-46-f3abd1bcfb90> in <module>()
----> 1 air2d.plot(levels=10, cmap='husl')

NameError: name 'air2d' is not defined
_images/plotting_seaborn_palette.png

Faceting

Faceting here refers to splitting an array along one or two dimensions and plotting each group. Xray’s basic plotting is useful for plotting two dimensional arrays. What about three or four dimensional arrays? That’s where facets become helpful.

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 seperate 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 [47]: t = air.isel(time=slice(0, 365 * 4, 250))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-47-836ac319e2bc> in <module>()
----> 1 t = air.isel(time=slice(0, 365 * 4, 250))

NameError: name 'air' is not defined

In [48]: t.coords
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-48-9e473e044a51> in <module>()
----> 1 t.coords

NameError: name 't' is not defined

Simple Example

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

In [49]: g_simple = t.plot(x='lon', y='lat', col='time', col_wrap=3)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-49-414f9c710f04> in <module>()
----> 1 g_simple = t.plot(x='lon', y='lat', col='time', col_wrap=3)

NameError: name 't' is not defined
_images/plot_facet_dataarray.png

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 [50]: t2 = t.isel(time=slice(0, 2))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-50-60564aec5d20> in <module>()
----> 1 t2 = t.isel(time=slice(0, 2))

NameError: name 't' is not defined

In [51]: t4d = xray.concat([t2, t2 + 40], pd.Index(['normal', 'hot'], name='fourth_dim'))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-51-350a1261ab53> in <module>()
----> 1 t4d = xray.concat([t2, t2 + 40], pd.Index(['normal', 'hot'], name='fourth_dim'))

NameError: name 't2' is not defined

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

NameError: name 't4d' is not defined

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

NameError: name 't4d' is not defined
_images/plot_facet_4d.png

Other features

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

In [54]: hasoutliers = t.isel(time=slice(0, 5)).copy()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-54-86184577316b> in <module>()
----> 1 hasoutliers = t.isel(time=slice(0, 5)).copy()

NameError: name 't' is not defined

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

NameError: name 'hasoutliers' is not defined

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

NameError: name 'hasoutliers' is not defined

In [57]: g = hasoutliers.plot.pcolormesh('lon', 'lat', col='time', col_wrap=3,
   ....:                                 robust=True, cmap='viridis')
   ....: 
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-57-ffeabd3a15e9> in <module>()
----> 1 g = hasoutliers.plot.pcolormesh('lon', 'lat', col='time', col_wrap=3,
      2                                 robust=True, cmap='viridis')

NameError: name 'hasoutliers' is not defined
_images/plot_facet_robust.png

FacetGrid Objects

xray.plot.FacetGrid is used to control the behavior of the multiple plots. It borrows an API and code from Seaborn. The structure is contained within the axes and name_dicts attributes, both 2d Numpy object arrays.

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

NameError: name 'g' is not defined

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

NameError: name 'g' is not defined

It’s possible to select the xray.DataArray corresponding to the FacetGrid through the name_dicts.

In [60]: g.data.loc[g.name_dicts[0, 0]]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-60-22a0c8bff048> 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 [61]: g = t.plot.imshow('lon', 'lat', col='time', col_wrap=3, robust=True)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-61-23d6dac48bc1> in <module>()
----> 1 g = t.plot.imshow('lon', 'lat', col='time', col_wrap=3, robust=True)

NameError: name 't' is not defined

In [62]: for i, ax in enumerate(g.axes.flat):
   ....:     ax.set_title('Air Temperature %d' % i)
   ....: 
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-62-16e93ad56fb7> in <module>()
----> 1 for i, ax in enumerate(g.axes.flat):
      2     ax.set_title('Air Temperature %d' % i)
      3 

NameError: name 'g' is not defined

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

NameError: name 'g' is not defined

In [64]: bottomright.annotate('bottom right', (240, 40))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-64-6872c49f27d5> in <module>()
----> 1 bottomright.annotate('bottom right', (240, 40))

NameError: name 'bottomright' is not defined

In [65]: plt.show()
_images/plot_facet_iterator.png

Maps

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

This script will plot the air temperature on a map.

import xray
import matplotlib.pyplot as plt
import cartopy.crs as ccrs


air = (xray.tutorial
       .load_dataset('air_temperature')
       .air
       .isel(time=0))

ax = plt.axes(projection=ccrs.Orthographic(-80, 35))
ax.set_global()
air.plot.contourf(ax=ax, transform=ccrs.PlateCarree())
ax.coastlines()

plt.savefig('cartopy_example.png')

Here is the resulting image:

_images/cartopy_example.png

Details

Ways to Use

There are three ways to use the xray 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 xray plot submodule.

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

In [66]: import xray.plot as xplt

In [67]: da = xray.DataArray(range(5))

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

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

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

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

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

In [73]: plt.tight_layout()

In [74]: plt.show()
_images/plotting_ways_to_use.png

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

The convenience method xray.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 xray.plot.line()
2 xray.plot.pcolormesh()
Anything else xray.plot.hist()

Coordinates

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

In [75]: a0 = xray.DataArray(np.zeros((4, 3, 2)), dims=('y', 'x', 'z'),
   ....:         name='temperature')
   ....: 

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

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

In [78]: a
Out[78]: 
<xray.DataArray 'temperature' (y: 4, x: 3)>
array([[ 1.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])
Coordinates:
  * x        (x) int64 0 1 2
  * y        (y) int64 0 1 2 3
    z        int64 0

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 [79]: a.plot()
Out[79]: <matplotlib.collections.QuadMesh at 0x7f01297c1b90>
_images/plotting_example_2d_simple.png

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.