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']
.
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 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).
DataArrays¶
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 0x7fb616068c50>]
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]:
{'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 0x7fb616789400>]
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 0x7fb616adfd68>]
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 0x7fb616aff588>, <matplotlib.axes._subplots.AxesSubplot object at 0x7fb616bcf1d0>], dtype=object) In [17]: air1d.plot(ax=axes[0]) Out[17]: [<matplotlib.lines.Line2D at 0x7fb616afcbe0>] In [18]: air1d.plot.hist(ax=axes[1]) Out[18]: (array([ 9., 38., 255., 584., 542., 489., 368., 258., 327., 50.]), array([ 0.95 , 2.719, 4.488, ..., 15.102, 16.871, 18.64 ], dtype=float32), <a list of 10 Patch objects>) 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)
Out[21]: [<matplotlib.lines.Line2D at 0x7fb616bc5b00>]
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.
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 [23]: air.isel(lon=10, lat=[19,21,22]).plot.line(x='time')
Out[23]:
[<matplotlib.lines.Line2D at 0x7fb61775c2b0>,
<matplotlib.lines.Line2D at 0x7fb616cd4c18>,
<matplotlib.lines.Line2D at 0x7fb616cd4a20>]
It is required to explicitly specify either
x
: the dimension to be used for the x-axis, orhue
: 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()
as air.isel(lon=10, lat=[19,21,22]).plot(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 [24]: air.isel(time=10, lon=[10, 11]).plot(y='lat', hue='lon')
Out[24]:
[<matplotlib.lines.Line2D at 0x7fb616dbdba8>,
<matplotlib.lines.Line2D at 0x7fb616dbd2e8>]
Step plots¶
As an alternative, also a step plot similar to matplotlib’s plt.step
can be
made using 1D data.
In [25]: air1d[:20].plot.step(where='mid')
Out[25]: [<matplotlib.lines.Line2D at 0x7fb616dde4a8>]
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 xarray.Dataset.groupby_bins()
.
In [26]: air_grp = air.mean(['time','lon']).groupby_bins('lat',[0,23.5,66.5,90]) In [27]: air_mean = air_grp.mean() In [28]: air_std = air_grp.std() In [29]: air_mean.plot.step() Out[29]: [<matplotlib.lines.Line2D at 0x7fb616c6b828>] In [30]: (air_mean + air_std).plot.step(ls=':') Out[30]: [<matplotlib.lines.Line2D at 0x7fb616b145f8>] In [31]: (air_mean - air_std).plot.step(ls=':') Out[31]: [<matplotlib.lines.Line2D at 0x7fb616b14940>] In [32]: plt.ylim(-20,30) Out[32]: (-20, 30) In [33]: plt.title('Zonal mean temperature') Out[33]: Text(0.5,1,'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 [34]: air.isel(time=10, lon=[10, 11]).plot.line(y='lat', hue='lon', xincrease=False, yincrease=False)
Out[34]:
[<matplotlib.lines.Line2D at 0x7fb616e5c358>,
<matplotlib.lines.Line2D at 0x7fb616e5c198>]
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 xarray.DataArray.plot()
calls xarray.plot.pcolormesh()
by default when the data is two-dimensional.
In [35]: air2d = air.isel(time=500)
In [36]: air2d.plot()
Out[36]: <matplotlib.collections.QuadMesh at 0x7fb616e5cc50>
All 2d plots in xarray allow the use of the keyword arguments yincrease
and xincrease
.
In [37]: air2d.plot(yincrease=False)
Out[37]: <matplotlib.collections.QuadMesh at 0x7fb615100828>
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 [38]: bad_air2d = air2d.copy()
In [39]: bad_air2d[dict(lat=slice(0, 10), lon=slice(0, 25))] = np.nan
In [40]: bad_air2d.plot()
Out[40]: <matplotlib.collections.QuadMesh at 0x7fb6150bac18>
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 [41]: b = air2d.copy()
# Apply a nonlinear transformation to one of the coords
In [42]: b.coords['lat'] = np.log(b.coords['lat'])
In [43]: b.plot()
Out[43]: <matplotlib.collections.QuadMesh at 0x7fb61512b0b8>
Calling Matplotlib¶
Since this is a thin wrapper around matplotlib, all the functionality of matplotlib is available.
In [44]: air2d.plot(cmap=plt.cm.Blues) Out[44]: <matplotlib.collections.QuadMesh at 0x7fb614ff9b38> In [45]: plt.title('These colors prove North America\nhas fallen in the ocean') Out[45]: Text(0.5,1,'These colors prove North America\nhas fallen in the ocean') In [46]: plt.ylabel('latitude') Out[46]: Text(0,0.5,'latitude') In [47]: plt.xlabel('longitude') Out[47]: Text(0.5,0,'longitude') In [48]: plt.tight_layout() In [49]: 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 [50]: plt.xlabel('Never gonna see this.') Out[50]: Text(0.5,0,'Never gonna see this.') In [51]: air2d.plot() Out[51]: <matplotlib.collections.QuadMesh at 0x7fb6161c88d0> In [52]: 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 [53]: airtemps.air.isel(time=0).plot()
Out[53]: <matplotlib.collections.QuadMesh at 0x7fb614fa4668>
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 [54]: air_outliers = airtemps.air.isel(time=0).copy()
In [55]: air_outliers[0, 0] = 100
In [56]: air_outliers[-1, -1] = 400
In [57]: air_outliers.plot()
Out[57]: <matplotlib.collections.QuadMesh at 0x7fb614f5db38>
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 [58]: air_outliers.plot(robust=True)
Out[58]: <matplotlib.collections.QuadMesh at 0x7fb614ea07b8>
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 [59]: air2d.plot(levels=8)
Out[59]: <matplotlib.collections.QuadMesh at 0x7fb614e46b00>
It is also possible to use a list of levels to specify the boundaries of the discrete colormap:
In [60]: air2d.plot(levels=[0, 12, 18, 30])
Out[60]: <matplotlib.collections.QuadMesh at 0x7fb616856ba8>
You can also specify a list of discrete colors through the colors
argument:
In [61]: flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"]
In [62]: air2d.plot(levels=[0, 12, 18, 30], colors=flatui)
Out[62]: <matplotlib.collections.QuadMesh at 0x7fb614eaae80>
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 [63]: air2d.plot(levels=10, cmap='husl')
Out[63]: <matplotlib.collections.QuadMesh at 0x7fb616699f60>
In [64]: 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.
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 [65]: t = air.isel(time=slice(0, 365 * 4, 250))
In [66]: t.coords
Out[66]:
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 ... 2013-11-09T12:00:00
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 [67]: g_simple = t.plot(x='lon', y='lat', col='time', col_wrap=3)
Faceting also works for line plots.
In [68]: g_simple_line = t.isel(lat=slice(0,None,4)).plot(x='lon', hue='lat', col='time', col_wrap=3)
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 [69]: t2 = t.isel(time=slice(0, 2)) In [70]: t4d = xr.concat([t2, t2 + 40], pd.Index(['normal', 'hot'], name='fourth_dim')) # This is a 4d array In [71]: t4d.coords Out[71]: Coordinates: * time (time) datetime64[ns] 2013-01-01 2013-03-04T12:00:00 * lon (lon) float32 200.0 202.5 205.0 207.5 ... 325.0 327.5 330.0 * lat (lat) float32 75.0 72.5 70.0 67.5 65.0 ... 22.5 20.0 17.5 15.0 * fourth_dim (fourth_dim) object 'normal' 'hot' In [72]: t4d.plot(x='lon', y='lat', col='time', row='fourth_dim') Out[72]: <xarray.plot.facetgrid.FacetGrid at 0x7fb614af6780>
Other features¶
Faceted plotting supports other arguments common to xarray 2d plots.
In [73]: hasoutliers = t.isel(time=slice(0, 5)).copy()
In [74]: hasoutliers[0, 0, 0] = -100
In [75]: hasoutliers[-1, -1, -1] = 400
In [76]: g = hasoutliers.plot.pcolormesh('lon', 'lat', col='time', col_wrap=3,
....: robust=True, cmap='viridis',
....: cbar_kwargs={'label': 'this has outliers'})
....:
FacetGrid Objects¶
xarray.plot.FacetGrid
is 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 [77]: g.axes Out[77]: array([[<matplotlib.axes._subplots.AxesSubplot object at 0x7fb6148f1c18>, <matplotlib.axes._subplots.AxesSubplot object at 0x7fb614893dd8>, <matplotlib.axes._subplots.AxesSubplot object at 0x7fb61483fe10>], [<matplotlib.axes._subplots.AxesSubplot object at 0x7fb614867e48>, <matplotlib.axes._subplots.AxesSubplot object at 0x7fb614812eb8>, <matplotlib.axes._subplots.AxesSubplot object at 0x7fb6147bdeb8>]], dtype=object) In [78]: g.name_dicts Out[78]: array([[{'time': numpy.datetime64('2013-01-01T00:00:00.000000000')}, {'time': numpy.datetime64('2013-03-04T12:00:00.000000000')}, {'time': numpy.datetime64('2013-05-06T00:00:00.000000000')}], [{'time': numpy.datetime64('2013-07-07T12:00:00.000000000')}, {'time': numpy.datetime64('2013-09-08T00:00:00.000000000')}, None]], dtype=object)
It’s possible to select the xarray.DataArray
or
xarray.Dataset
corresponding to the FacetGrid through the
name_dicts
.
In [79]: g.data.loc[g.name_dicts[0, 0]]
Out[79]:
<xarray.DataArray 'air' (lat: 25, lon: 53)>
array([[-100. , -30.65, -29.65, ..., -40.35, -37.65, -34.55],
[ -29.35, -28.65, -28.45, ..., -40.35, -37.85, -33.85],
[ -23.15, -23.35, -24.26, ..., -39.95, -36.76, -31.45],
...,
[ 23.45, 23.05, 23.25, ..., 22.25, 21.95, 21.55],
[ 22.75, 23.05, 23.64, ..., 22.75, 22.75, 22.05],
[ 23.14, 23.64, 23.95, ..., 23.75, 23.64, 23.45]], dtype=float32)
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 datetime64[ns] 2013-01-01
Attributes:
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: [185.16 322.1 ]
Here is an example of using the lower level API and then modifying the axes after they have been plotted.
In [80]: g = t.plot.imshow('lon', 'lat', col='time', col_wrap=3, robust=True)
In [81]: for i, ax in enumerate(g.axes.flat):
....: ax.set_title('Air Temperature %d' % i)
....:
In [82]: bottomright = g.axes[-1, -1]
In [83]: bottomright.annotate('bottom right', (240, 40))
Out[83]: Text(240,40,'bottom right')
In [84]: plt.draw()
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 [85]: ds = xr.tutorial.scatter_example_dataset()
In [86]: ds
Out[86]:
<xarray.Dataset>
Dimensions: (w: 4, x: 3, y: 11, z: 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.104 0.02719 -0.0425 ... -0.1175 -0.0183
B (x, y, z, w) float64 0.0 0.0 0.0 0.0 ... 1.369 1.408 1.387 1.417
Suppose we want to scatter A
against B
In [87]: ds.plot.scatter(x='A', y='B')
Out[87]: <matplotlib.collections.PathCollection at 0x7fb61465c400>
The hue
kwarg lets you vary the color by variable value
In [88]: ds.plot.scatter(x='A', y='B', hue='w')
Out[88]:
[<matplotlib.collections.PathCollection at 0x7fb6146353c8>,
<matplotlib.collections.PathCollection at 0x7fb614774c18>,
<matplotlib.collections.PathCollection at 0x7fb6147d8710>,
<matplotlib.collections.PathCollection at 0x7fb61482b358>]
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 [89]: ds.w.values = [1, 2, 3, 5]
In [90]: ds.plot.scatter(x='A', y='B', hue='w', hue_style='discrete')
Out[90]:
[<matplotlib.collections.PathCollection at 0x7fb614b4de48>,
<matplotlib.collections.PathCollection at 0x7fb6160517b8>,
<matplotlib.collections.PathCollection at 0x7fb614c6bba8>,
<matplotlib.collections.PathCollection at 0x7fb614c025f8>]
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 [91]: ds.plot.scatter(x='A', y='B', hue='z', hue_style='discrete', markersize='z')
Out[91]:
[<matplotlib.collections.PathCollection at 0x7fb61487d128>,
<matplotlib.collections.PathCollection at 0x7fb614808ef0>,
<matplotlib.collections.PathCollection at 0x7fb616d1a518>,
<matplotlib.collections.PathCollection at 0x7fb614f8bcf8>]
Faceting is also possible
In [92]: ds.plot.scatter(x='A', y='B', col='x', row='z', hue='w', hue_style='discrete')
Out[92]: <xarray.plot.facetgrid.FacetGrid at 0x7fb617781908>
For more advanced scatter plots, we recommend converting the relevant data variables to a pandas DataFrame and using the extensive plotting capabilities of seaborn
.
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 [93]: import cartopy.crs as ccrs
In [94]: air = xr.tutorial.open_dataset('air_temperature').air
In [95]: ax = plt.axes(projection=ccrs.Orthographic(-80, 35))
In [96]: air.isel(time=0).plot.contourf(ax=ax, transform=ccrs.PlateCarree());
In [97]: ax.set_global(); ax.coastlines();
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 [98]: p = air.isel(time=[0, 4]).plot(transform=ccrs.PlateCarree(), col='time',
....: subplot_kws={'projection': ccrs.Orthographic(-80, 35)})
....:
In [99]: for ax in p.axes.flat:
....: ax.coastlines()
....: ax.gridlines()
....:
In [100]: plt.draw();
Details¶
Ways to Use¶
There are three ways to use the xarray plotting functionality:
Use
plot
as a convenience method for a DataArray.Access a specific plotting method from the
plot
attribute of a DataArray.Directly from the xarray plot submodule.
These are provided for user convenience; they all call the same code.
In [101]: import xarray.plot as xplt In [102]: da = xr.DataArray(range(5)) In [103]: fig, axes = plt.subplots(ncols=2, nrows=2) In [104]: da.plot(ax=axes[0, 0]) Out[104]: [<matplotlib.lines.Line2D at 0x7fb614094ac8>] In [105]: da.plot.line(ax=axes[0, 1]) Out[105]: [<matplotlib.lines.Line2D at 0x7fb61409e048>] In [106]: xplt.plot(da, ax=axes[1, 0]) Out[106]: [<matplotlib.lines.Line2D at 0x7fb614130e48>] In [107]: xplt.line(da, ax=axes[1, 1]) Out[107]: [<matplotlib.lines.Line2D at 0x7fb6140dc160>] In [108]: plt.tight_layout() In [109]: 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 |
|
2 |
|
Anything else |
Coordinates¶
If you’d like to find out what’s really going on in the coordinate system, read on.
In [110]: a0 = xr.DataArray(np.zeros((4, 3, 2)), dims=('y', 'x', 'z'),
.....: name='temperature')
.....:
In [111]: a0[0, 0, 0] = 1
In [112]: a = a0.isel(z=0)
In [113]: a
Out[113]:
<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 [114]: a.plot()
Out[114]: <matplotlib.collections.QuadMesh at 0x7fb6140946a0>
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 [115]: lon, lat = np.meshgrid(np.linspace(-20, 20, 5), np.linspace(0, 30, 4))
In [116]: lon += lat/10
In [117]: lat += lon/10
In [118]: da = xr.DataArray(np.arange(20).reshape(4, 5), dims=['y', 'x'],
.....: coords = {'lat': (('y', 'x'), lat),
.....: 'lon': (('y', 'x'), lon)})
.....:
In [119]: da.plot.pcolormesh('lon', 'lat');
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 [120]: import cartopy.crs as ccrs
In [121]: ax = plt.subplot(projection=ccrs.PlateCarree());
In [122]: da.plot.pcolormesh('lon', 'lat', ax=ax);
In [123]: ax.scatter(lon, lat, transform=ccrs.PlateCarree());
In [124]: ax.coastlines(); ax.gridlines(draw_labels=True);
You can however decide to infer the cell boundaries and use the
infer_intervals
keyword:
In [125]: ax = plt.subplot(projection=ccrs.PlateCarree());
In [126]: da.plot.pcolormesh('lon', 'lat', ax=ax, infer_intervals=True);
In [127]: ax.scatter(lon, lat, transform=ccrs.PlateCarree());
In [128]: ax.coastlines(); ax.gridlines(draw_labels=True);
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 [129]: f, ax = plt.subplots(2, 1)
In [130]: da.plot.line(x='lon', hue='y', ax=ax[0]);
In [131]: da.plot.line(x='lon', hue='x', ax=ax[1]);