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
xarray.DataArray
objects.
To plot xarray.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.
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 byHoloviews
orGeoviews
) by adding ahvplot
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')
In [6]: airtemps
Out[6]:
<xarray.Dataset>
Dimensions: (lat: 25, lon: 53, time: 2920)
Coordinates:
* lat (lat) float32 75.0 72.5 70.0 67.5 65.0 ... 25.0 22.5 20.0 17.5 15.0
* lon (lon) float32 200.0 202.5 205.0 207.5 ... 322.5 325.0 327.5 330.0
* time (time) datetime64[ns] 2013-01-01 ... 2014-12-31T18:00:00
Data variables:
air (time, lat, lon) float32 ...
Attributes:
Conventions: COARDS
title: 4x daily NMC reanalysis (1948)
description: Data is from NMC initialized reanalysis\n(4x/day). These a...
platform: Model
references: http://www.esrl.noaa.gov/psd/data/gridded/data.ncep.reanaly...
# Convert to celsius
In [7]: air = airtemps.air - 273.15
# copy attributes to get nice figure labels and change Kelvin to Celsius
In [8]: air.attrs = airtemps.air.attrs
In [9]: air.attrs['units'] = 'deg C'
Note
Until GH1614 is solved, you might need to copy over the metadata in attrs
to get informative figure labels (as was done above).
One Dimension¶
Simple Example¶
The simplest way to make a plot is to call the xarray.DataArray.plot()
method.
In [10]: air1d = air.isel(lat=10, lon=10)
In [11]: air1d.plot()
Out[11]: [<matplotlib.lines.Line2D at 0x7fae34ff6e10>]
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
Out[12]:
OrderedDict([('long_name', '4xDaily Air temperature at sigma level 995'),
('units', 'deg C'),
('precision', 2),
('GRIB_id', 11),
('GRIB_name', 'TMP'),
('var_desc', 'Air temperature'),
('dataset', 'NMC Reanalysis'),
('level_desc', 'Surface'),
('statistic', 'Individual Obs'),
('parent_stat', 'Other'),
('actual_range', array([185.16, 322.1 ], dtype=float32))])
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-^')
Out[13]: [<matplotlib.lines.Line2D at 0x7fae35552d30>]
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')
Out[14]: [<matplotlib.lines.Line2D at 0x7fae352a5f60>]
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([<matplotlib.axes._subplots.AxesSubplot object at 0x7fae3527a128>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7fae3500ca58>], dtype=object)
In [17]: air1d.plot(ax=axes[0])