Plotting (original) (raw)
Introduction#
Labeled data enables expressive computations. These same labels can also be used to easily create informative plots.
Xarray’s plotting capabilities are centered aroundDataArray 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 popularmatplotlib 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 containingcftime.datetime
objectsnc-time-axis v1.3.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.
- HoloViewsand 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.
import cartopy.crs as ccrs import matplotlib.pyplot as plt import numpy as np import pandas as pd import xarray as xr
For these examples we’ll use the North American air temperature dataset.
airtemps = xr.tutorial.open_dataset("air_temperature") airtemps
<xarray.Dataset> Size: 31MB Dimensions: (lat: 25, time: 2920, lon: 53) Coordinates:
lat (lat) float32 100B 75.0 72.5 70.0 67.5 65.0 ... 22.5 20.0 17.5 15.0
lon (lon) float32 212B 200.0 202.5 205.0 207.5 ... 325.0 327.5 330.0
time (time) datetime64[ns] 23kB 2013-01-01 ... 2014-12-31T18:00:00 Data variables: air (time, lat, lon) float64 31MB ... 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...
Dimensions:
- lat: 25
- time: 2920
- lon: 53
Coordinates: (3)
- lat
(lat)
float32
75.0 72.5 70.0 ... 20.0 17.5 15.0
standard_name :
latitude
long_name :
Latitude
units :
degrees_north
axis :
Y
array([75. , 72.5, 70. , 67.5, 65. , 62.5, 60. , 57.5, 55. , 52.5, 50. , 47.5,
45. , 42.5, 40. , 37.5, 35. , 32.5, 30. , 27.5, 25. , 22.5, 20. , 17.5,
15. ], dtype=float32) - lon
(lon)
float32
200.0 202.5 205.0 ... 327.5 330.0
standard_name :
longitude
long_name :
Longitude
units :
degrees_east
axis :
X
array([200. , 202.5, 205. , 207.5, 210. , 212.5, 215. , 217.5, 220. , 222.5,
225. , 227.5, 230. , 232.5, 235. , 237.5, 240. , 242.5, 245. , 247.5,
250. , 252.5, 255. , 257.5, 260. , 262.5, 265. , 267.5, 270. , 272.5,
275. , 277.5, 280. , 282.5, 285. , 287.5, 290. , 292.5, 295. , 297.5,
300. , 302.5, 305. , 307.5, 310. , 312.5, 315. , 317.5, 320. , 322.5,
325. , 327.5, 330. ], dtype=float32) - time
(time)
datetime64[ns]
2013-01-01 ... 2014-12-31T18:00:00
standard_name :
time
long_name :
Time
array(['2013-01-01T00:00:00.000000000', '2013-01-01T06:00:00.000000000',
'2013-01-01T12:00:00.000000000', ..., '2014-12-31T06:00:00.000000000',
'2014-12-31T12:00:00.000000000', '2014-12-31T18:00:00.000000000'],
shape=(2920,), dtype='datetime64[ns]')
- lat
Data variables: (1)
- air
(time, lat, lon)
float64
...
long_name :
4xDaily Air temperature at sigma level 995
units :
degK
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 ]
[3869000 values with dtype=float64]
- air
Indexes: (3)
- PandasIndex
PandasIndex(Index([75.0, 72.5, 70.0, 67.5, 65.0, 62.5, 60.0, 57.5, 55.0, 52.5, 50.0, 47.5,
45.0, 42.5, 40.0, 37.5, 35.0, 32.5, 30.0, 27.5, 25.0, 22.5, 20.0, 17.5,
15.0],
dtype='float32', name='lat')) - PandasIndex
PandasIndex(Index([200.0, 202.5, 205.0, 207.5, 210.0, 212.5, 215.0, 217.5, 220.0, 222.5,
225.0, 227.5, 230.0, 232.5, 235.0, 237.5, 240.0, 242.5, 245.0, 247.5,
250.0, 252.5, 255.0, 257.5, 260.0, 262.5, 265.0, 267.5, 270.0, 272.5,
275.0, 277.5, 280.0, 282.5, 285.0, 287.5, 290.0, 292.5, 295.0, 297.5,
300.0, 302.5, 305.0, 307.5, 310.0, 312.5, 315.0, 317.5, 320.0, 322.5,
325.0, 327.5, 330.0],
dtype='float32', name='lon')) - PandasIndex
PandasIndex(DatetimeIndex(['2013-01-01 00:00:00', '2013-01-01 06:00:00',
'2013-01-01 12:00:00', '2013-01-01 18:00:00',
'2013-01-02 00:00:00', '2013-01-02 06:00:00',
'2013-01-02 12:00:00', '2013-01-02 18:00:00',
'2013-01-03 00:00:00', '2013-01-03 06:00:00',
...
'2014-12-29 12:00:00', '2014-12-29 18:00:00',
'2014-12-30 00:00:00', '2014-12-30 06:00:00',
'2014-12-30 12:00:00', '2014-12-30 18:00:00',
'2014-12-31 00:00:00', '2014-12-31 06:00:00',
'2014-12-31 12:00:00', '2014-12-31 18:00:00'],
dtype='datetime64[ns]', name='time', length=2920, freq=None))
- PandasIndex
Attributes: (5)
Conventions :
COARDS
title :
4x daily NMC reanalysis (1948)
description :
Data is from NMC initialized reanalysis (4x/day). These are the 0.9950 sigma level values.
platform :
Model
references :
http://www.esrl.noaa.gov/psd/data/gridded/data.ncep.reanalysis.html
Convert to celsius
air = airtemps.air - 273.15
copy attributes to get nice figure labels and change Kelvin to Celsius
air.attrs = airtemps.air.attrs 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 DataArray.plot() method.
air1d = air.isel(lat=10, lon=10) air1d.plot();
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 theCF-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
.
{'long_name': '4xDaily Air temperature at sigma level 995', 'units': 'deg C', 'precision': np.int16(2), 'GRIB_id': np.int16(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() callsmatplotlib.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:
air1d[:200].plot.line("b-^");
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.
air1d[:200].plot.line(color="purple", marker="o");
Adding to Existing Axis#
To add the plot to an existing axis pass in the axis as a keyword argumentax
. This works for all xarray plotting methods. In this example axs
is an array consisting of the left and right axes created by plt.subplots
.
fig, axs = plt.subplots(ncols=2)
print(axs)
air1d.plot(ax=axs[0]) air1d.plot.hist(ax=axs[1]);
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)
:
air1d.plot(aspect=2, size=3);
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.
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:
decimal_day = (air1d.time - air1d.time[0]) / pd.Timedelta("1d") air1d_multi = air1d.assign_coords(decimal_day=("time", decimal_day.data)) air1d_multi
<xarray.DataArray 'air' (time: 2920)> Size: 23kB array([7.64, 7.85, 8.05, ..., 9.34, 9.34, 9.54], shape=(2920,)) Coordinates: lat float32 4B 50.0 lon float32 4B 225.0
time (time) datetime64[ns] 23kB 2013-01-01 ... 2014-12-31T18:00:00 decimal_day (time) float64 23kB 0.0 0.25 0.5 0.75 ... 729.2 729.5 729.8 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 ]
7.64 7.85 8.05 7.85 7.95 7.14 7.45 ... 9.24 9.64 9.24 9.34 9.34 9.54
array([7.64, 7.85, 8.05, ..., 9.34, 9.34, 9.54], shape=(2920,))Coordinates: (4)
- lat
()
float32
50.0
standard_name :
latitude
long_name :
Latitude
units :
degrees_north
axis :
Y
array(50., dtype=float32) - lon
()
float32
225.0
standard_name :
longitude
long_name :
Longitude
units :
degrees_east
axis :
X
array(225., dtype=float32) - time
(time)
datetime64[ns]
2013-01-01 ... 2014-12-31T18:00:00
standard_name :
time
long_name :
Time
array(['2013-01-01T00:00:00.000000000', '2013-01-01T06:00:00.000000000',
'2013-01-01T12:00:00.000000000', ..., '2014-12-31T06:00:00.000000000',
'2014-12-31T12:00:00.000000000', '2014-12-31T18:00:00.000000000'],
shape=(2920,), dtype='datetime64[ns]') - decimal_day
(time)
float64
0.0 0.25 0.5 ... 729.2 729.5 729.8
array([0.0000e+00, 2.5000e-01, 5.0000e-01, ..., 7.2925e+02, 7.2950e+02,
7.2975e+02], shape=(2920,))
- lat
Indexes: (1)
- PandasIndex
PandasIndex(DatetimeIndex(['2013-01-01 00:00:00', '2013-01-01 06:00:00',
'2013-01-01 12:00:00', '2013-01-01 18:00:00',
'2013-01-02 00:00:00', '2013-01-02 06:00:00',
'2013-01-02 12:00:00', '2013-01-02 18:00:00',
'2013-01-03 00:00:00', '2013-01-03 06:00:00',
...
'2014-12-29 12:00:00', '2014-12-29 18:00:00',
'2014-12-30 00:00:00', '2014-12-30 06:00:00',
'2014-12-30 12:00:00', '2014-12-30 18:00:00',
'2014-12-31 00:00:00', '2014-12-31 06:00:00',
'2014-12-31 12:00:00', '2014-12-31 18:00:00'],
dtype='datetime64[ns]', name='time', length=2920, freq=None))
- PandasIndex
Attributes: (11)
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 ]
To use 'decimal_day'
as x coordinate it must be explicitly specified:
air1d_multi.plot(x="decimal_day");
Creating a new MultiIndex named 'date'
from 'time'
and 'decimal_day'
, it is also possible to use a MultiIndex level as x-axis:
air1d_multi = air1d_multi.set_index(date=("time", "decimal_day")) air1d_multi.plot(x="decimal_day");
Finally, if a dataset does not have any coordinates it enumerates all data points:
air1d_multi = air1d_multi.drop_vars(["date", "time", "decimal_day"]) air1d_multi.plot();
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:
air.isel(lon=10, lat=[19, 21, 22]).plot.line(x="time");
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.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.
air.isel(time=10, lon=[10, 11]).plot(y="lat", hue="lon");
Step plots#
As an alternative, also a step plot similar to matplotlib’s plt.step
can be made using 1D data.
air1d[:20].plot.step(where="mid");
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().
air_grp = air.mean(["time", "lon"]).groupby_bins("lat", [0, 23.5, 66.5, 90]) air_mean = air_grp.mean() air_std = air_grp.std() air_mean.plot.step() (air_mean + air_std).plot.step(ls=":") (air_mean - air_std).plot.step(ls=":") plt.ylim(-20, 30) plt.title("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.
air.isel(time=10, lon=[10, 11]).plot.line( y="lat", hue="lon", xincrease=False, yincrease=False );
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 ax.set_(x,y)scale()
,ax.set_(x,y)ticks()
, ax.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.
air2d = air.isel(time=500) air2d.plot();
All 2d plots in xarray allow the use of the keyword arguments yincrease
and xincrease
.
air2d.plot(yincrease=False);
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.
bad_air2d = air2d.copy() bad_air2d[dict(lat=slice(0, 10), lon=slice(0, 25))] = np.nan bad_air2d.plot();
Nonuniform Coordinates#
It’s not necessary for the coordinates to be evenly spaced. Bothxarray.plot.pcolormesh() (default) and xarray.plot.contourf() can produce plots with nonuniform coordinates.
b = air2d.copy()
Apply a nonlinear transformation to one of the coords
b.coords["lat"] = np.log(b.coords["lat"])
b.plot();
Other types of plot#
There are several other options for plotting 2D data.
Contour plot using DataArray.plot.contour()
Filled contour plot using DataArray.plot.contourf()
Surface plot using DataArray.plot.surface()
transpose just to make the example look a bit nicer
air2d.T.plot.surface();
Calling Matplotlib#
Since this is a thin wrapper around matplotlib, all the functionality of matplotlib is available.
air2d.plot(cmap=plt.cm.Blues) plt.title("These colors prove North America\nhas fallen in the ocean") plt.ylabel("latitude") plt.xlabel("longitude");
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, sinced_ylog.plot()
updates the xlabel.
plt.xlabel("Never gonna see this.") air2d.plot();
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:
airtemps.air.isel(time=0).plot();
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.
air_outliers = airtemps.air.isel(time=0).copy() air_outliers[0, 0] = 100 air_outliers[-1, -1] = 400
air_outliers.plot();
This plot shows that we have outliers. The easy way to visualize the data without the outliers is to pass the parameterrobust=True
. This will use the 2nd and 98th percentiles of the data to compute the color limits.
air_outliers.plot(robust=True);
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. Thelevels
keyword argument can be used to generate plots with discrete colormaps. For example, to make a plot with 8 discrete color intervals:
It is also possible to use a list of levels to specify the boundaries of the discrete colormap:
air2d.plot(levels=[0, 12, 18, 30]);
You can also specify a list of discrete colors through the colors
argument:
flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"] air2d.plot(levels=[0, 12, 18, 30], colors=flatui);
Finally, if you have Seaborninstalled, 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).
air2d.plot(levels=10, cmap="husl");
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 or 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.
t = air.isel(time=slice(0, 365 * 4, 250)) t.coords
Coordinates:
- lat (lat) float32 100B 75.0 72.5 70.0 67.5 65.0 ... 22.5 20.0 17.5 15.0
- lon (lon) float32 212B 200.0 202.5 205.0 207.5 ... 325.0 327.5 330.0
- time (time) datetime64[ns] 48B 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 axarray.plot.FacetGrid object.
g_simple = t.plot(x="lon", y="lat", col="time", col_wrap=3);
Faceting also works for line plots.
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.
t2 = t.isel(time=slice(0, 2)) t4d = xr.concat([t2, t2 + 40], pd.Index(["normal", "hot"], name="fourth_dim"))
This is a 4d array
t4d.coords
t4d.plot(x="lon", y="lat", col="time", row="fourth_dim");
Other features#
Faceted plotting supports other arguments common to xarray 2d plots.
hasoutliers = t.isel(time=slice(0, 5)).copy() hasoutliers[0, 0, 0] = -100 hasoutliers[-1, -1, -1] = 400
g = hasoutliers.plot.pcolormesh( x="lon", y="lat", col="time", col_wrap=3, robust=True, cmap="viridis", cbar_kwargs={"label": "this has outliers"}, )
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 axs
and name_dicts
attributes, both 2d NumPy object arrays.
array([[<Axes: title={'center': 'time = 2013-01-01'}, ylabel='Latitude [degrees_north]'>, <Axes: title={'center': 'time = 2013-03-04T12:00:00'}>, <Axes: title={'center': 'time = 2013-05-06'}>], [<Axes: title={'center': 'time = 2013-07-07T12:00:00'}, xlabel='Longitude [degrees_east]', ylabel='Latitude [degrees_north]'>, <Axes: title={'center': 'time = 2013-09-08'}, xlabel='Longitude [degrees_east]'>, <Axes: xlabel='Longitude [degrees_east]'>]], dtype=object)
array([[{'time': np.datetime64('2013-01-01T00:00:00.000000000')}, {'time': np.datetime64('2013-03-04T12:00:00.000000000')}, {'time': np.datetime64('2013-05-06T00:00:00.000000000')}], [{'time': np.datetime64('2013-07-07T12:00:00.000000000')}, {'time': np.datetime64('2013-09-08T00:00:00.000000000')}, None]], dtype=object)
It’s possible to select the xarray.DataArray orxarray.Dataset corresponding to the FacetGrid through thename_dicts
.
g.data.loc[g.name_dicts[0, 0]]
<xarray.DataArray 'air' (lat: 25, lon: 53)> Size: 11kB 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]], shape=(25, 53)) Coordinates:
lat (lat) float32 100B 75.0 72.5 70.0 67.5 65.0 ... 22.5 20.0 17.5 15.0
lon (lon) float32 212B 200.0 202.5 205.0 207.5 ... 325.0 327.5 330.0 time datetime64[ns] 8B 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 ]
-100.0 -30.65 -29.65 -29.15 -29.05 ... 24.64 24.45 23.75 23.64 23.45
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]],
shape=(25, 53))Coordinates: (3)
- lat
(lat)
float32
75.0 72.5 70.0 ... 20.0 17.5 15.0
standard_name :
latitude
long_name :
Latitude
units :
degrees_north
axis :
Y
array([75. , 72.5, 70. , 67.5, 65. , 62.5, 60. , 57.5, 55. , 52.5, 50. , 47.5,
45. , 42.5, 40. , 37.5, 35. , 32.5, 30. , 27.5, 25. , 22.5, 20. , 17.5,
15. ], dtype=float32) - lon
(lon)
float32
200.0 202.5 205.0 ... 327.5 330.0
standard_name :
longitude
long_name :
Longitude
units :
degrees_east
axis :
X
array([200. , 202.5, 205. , 207.5, 210. , 212.5, 215. , 217.5, 220. , 222.5,
225. , 227.5, 230. , 232.5, 235. , 237.5, 240. , 242.5, 245. , 247.5,
250. , 252.5, 255. , 257.5, 260. , 262.5, 265. , 267.5, 270. , 272.5,
275. , 277.5, 280. , 282.5, 285. , 287.5, 290. , 292.5, 295. , 297.5,
300. , 302.5, 305. , 307.5, 310. , 312.5, 315. , 317.5, 320. , 322.5,
325. , 327.5, 330. ], dtype=float32) - time
()
datetime64[ns]
2013-01-01
standard_name :
time
long_name :
Time
array('2013-01-01T00:00:00.000000000', dtype='datetime64[ns]')
- lat
Indexes: (2)
- PandasIndex
PandasIndex(Index([75.0, 72.5, 70.0, 67.5, 65.0, 62.5, 60.0, 57.5, 55.0, 52.5, 50.0, 47.5,
45.0, 42.5, 40.0, 37.5, 35.0, 32.5, 30.0, 27.5, 25.0, 22.5, 20.0, 17.5,
15.0],
dtype='float32', name='lat')) - PandasIndex
PandasIndex(Index([200.0, 202.5, 205.0, 207.5, 210.0, 212.5, 215.0, 217.5, 220.0, 222.5,
225.0, 227.5, 230.0, 232.5, 235.0, 237.5, 240.0, 242.5, 245.0, 247.5,
250.0, 252.5, 255.0, 257.5, 260.0, 262.5, 265.0, 267.5, 270.0, 272.5,
275.0, 277.5, 280.0, 282.5, 285.0, 287.5, 290.0, 292.5, 295.0, 297.5,
300.0, 302.5, 305.0, 307.5, 310.0, 312.5, 315.0, 317.5, 320.0, 322.5,
325.0, 327.5, 330.0],
dtype='float32', name='lon'))
- PandasIndex
Attributes: (11)
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.
g = t.plot.imshow(x="lon", y="lat", col="time", col_wrap=3, robust=True)
for i, ax in enumerate(g.axs.flat): ax.set_title("Air Temperature %d" % i)
bottomright = g.axs[-1, -1] bottomright.annotate("bottom right", (240, 40));
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() andset_ticks() for more information. Plotting functions can be applied to each subset of the data by callingmap_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
ds = xr.tutorial.scatter_example_dataset(seed=42) ds
<xarray.Dataset> Size: 9kB Dimensions: (x: 3, y: 11, z: 4, w: 4) Coordinates:
x (x) int64 24B 0 1 2
y (y) float64 88B 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 32B 0 1 2 3
w (w) <U5 80B 'one' 'two' 'three' 'five' Data variables: A (x, y, z, w) float64 4kB 0.03047 -0.104 ... 4.512e-05 0.01906 B (x, y, z, w) float64 4kB 0.0 0.0 0.0 0.0 ... 1.369 1.423 1.428
Dimensions:
- x: 3
- y: 11
- z: 4
- w: 4
Coordinates: (4)
- x
(x)
int64
0 1 2 - y
(y)
float64
0.0 0.1 0.2 0.3 ... 0.7 0.8 0.9 1.0
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ]) - z
(z)
int64
0 1 2 3 - w
(w)
<U5
'one' 'two' 'three' 'five'
array(['one', 'two', 'three', 'five'], dtype='<U5')
- x
Data variables: (2)
- A
(x, y, z, w)
float64
0.03047 -0.104 ... 0.01906
array([[[[ 3.04717080e-02, -1.03998411e-01, 7.50451196e-02,
9.40564716e-02],
[ 3.04717080e-02, -1.03998411e-01, 7.50451196e-02,
9.40564716e-02],
[ 3.04717080e-02, -1.03998411e-01, 7.50451196e-02,
9.40564716e-02],
[ 3.04717080e-02, -1.03998411e-01, 7.50451196e-02,
9.40564716e-02]],
[[ 5.04717080e-02, -8.39984106e-02, 9.50451196e-02,
1.14056472e-01],
[ 4.71383746e-02, -8.73317440e-02, 9.17117862e-02,
1.10723138e-01],
[ 4.47574223e-02, -8.97126963e-02, 8.93308339e-02,
1.08342186e-01],
[ 4.29717080e-02, -9.14984106e-02, 8.75451196e-02,
1.06556472e-01]],
[[ 7.04717080e-02, -6.39984106e-02, 1.15045120e-01,
1.34056472e-01],
...
[-6.95282920e-02, -2.03998411e-01, -2.49548804e-02,
-5.94352836e-03]],
[[ 1.04717080e-02, -1.23998411e-01, 5.50451196e-02,
7.40564716e-02],
[-1.95282920e-02, -1.53998411e-01, 2.50451196e-02,
4.40564716e-02],
[-4.09568635e-02, -1.75426982e-01, 3.61654815e-03,
2.26279002e-02],
[-5.70282920e-02, -1.91498411e-01, -1.24548804e-02,
6.55647164e-03]],
[[ 3.04717080e-02, -1.03998411e-01, 7.50451196e-02,
9.40564716e-02],
[-2.86162536e-03, -1.37331744e-01, 4.17117862e-02,
6.07231383e-02],
[-2.66711492e-02, -1.61141268e-01, 1.79022624e-02,
3.69136145e-02],
[-4.45282920e-02, -1.78998411e-01, 4.51195806e-05,
1.90564716e-02]]]])- B
(x, y, z, w)
float64
0.0 0.0 0.0 ... 1.369 1.423 1.428
array([[[[ 0. , 0. , 0. , 0. ],
[ 0.00304717, -0.01039984, 0.00750451, 0.00940565],
[ 0.00609434, -0.02079968, 0.01500902, 0.01881129],
[ 0.00914151, -0.03119952, 0.02251354, 0.02821694]],
[[ 0.00316228, 0.00316228, 0.00316228, 0.00316228],
[ 0.00620945, -0.00723756, 0.01066679, 0.01256792],
[ 0.00925662, -0.0176374 , 0.0181713 , 0.02197357],
[ 0.01230379, -0.02803725, 0.02567581, 0.03137922]],
[[ 0.01788854, 0.01788854, 0.01788854, 0.01788854],
[ 0.02093571, 0.0074887 , 0.02539306, 0.02729419],
[ 0.02398289, -0.00291114, 0.03289757, 0.03669984],
[ 0.02703006, -0.01331098, 0.04040208, 0.04610549]],
[[ 0.04929503, 0.04929503, 0.04929503, 0.04929503],
[ 0.0523422 , 0.03889519, 0.05679954, 0.05870068],
[ 0.05538937, 0.02849535, 0.06430405, 0.06810632],
[ 0.05843654, 0.01809551, 0.07180857, 0.07751197]],
...
[[ 0.80996341, 0.80996341, 0.80996341, 0.80996341],
[ 0.81301058, 0.79956357, 0.81746792, 0.81936906],
[ 0.81605775, 0.78916373, 0.82497244, 0.82877471],
[ 0.81910493, 0.77876389, 0.83247695, 0.83818035]],
[[ 0.9724334 , 0.9724334 , 0.9724334 , 0.9724334 ],
[ 0.97548057, 0.96203356, 0.97993791, 0.98183905],
[ 0.97852774, 0.95163372, 0.98744243, 0.9912447 ],
[ 0.98157491, 0.94123388, 0.99494694, 1.00065034]],
[[ 1.16843347, 1.16843347, 1.16843347, 1.16843347],
[ 1.17148064, 1.15803363, 1.17593798, 1.17783912],
[ 1.17452781, 1.14763379, 1.1834425 , 1.18724477],
[ 1.17757498, 1.13723395, 1.19094701, 1.19665041]],
[[ 1.4 , 1.4 , 1.4 , 1.4 ],
[ 1.40304717, 1.38960016, 1.40750451, 1.40940565],
[ 1.40609434, 1.37920032, 1.41500902, 1.41881129],
[ 1.40914151, 1.36880048, 1.42251354, 1.42821694]]]])- A
Indexes: (4)
- PandasIndex
PandasIndex(Index([0, 1, 2], dtype='int64', name='x')) - PandasIndex
PandasIndex(Index([ 0.0, 0.1, 0.2,
0.30000000000000004, 0.4, 0.5,
0.6000000000000001, 0.7000000000000001, 0.8,
0.9, 1.0],
dtype='float64', name='y')) - PandasIndex
PandasIndex(Index([0, 1, 2, 3], dtype='int64', name='z')) - PandasIndex
PandasIndex(Index(['one', 'two', 'three', 'five'], dtype='object', name='w'))
- PandasIndex
Attributes: (0)
Scatter#
Let’s plot the A
DataArray as a function of the y
coord
with xr.set_options(display_expand_data=False): display(ds.A)
<xarray.DataArray 'A' (x: 3, y: 11, z: 4, w: 4)> Size: 4kB 0.03047 -0.104 0.07505 0.09406 0.03047 ... -0.04453 -0.179 4.512e-05 0.01906 Coordinates:
x (x) int64 24B 0 1 2
y (y) float64 88B 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 32B 0 1 2 3
w (w) <U5 80B 'one' 'two' 'three' 'five' Attributes: units: Aunits
0.03047 -0.104 0.07505 0.09406 ... -0.04453 -0.179 4.512e-05 0.01906
array([[[[ 3.04717080e-02, -1.03998411e-01, 7.50451196e-02,
9.40564716e-02],
[ 3.04717080e-02, -1.03998411e-01, 7.50451196e-02,
9.40564716e-02],
[ 3.04717080e-02, -1.03998411e-01, 7.50451196e-02,
9.40564716e-02],
[ 3.04717080e-02, -1.03998411e-01, 7.50451196e-02,
9.40564716e-02]],
[[ 5.04717080e-02, -8.39984106e-02, 9.50451196e-02,
1.14056472e-01],
[ 4.71383746e-02, -8.73317440e-02, 9.17117862e-02,
1.10723138e-01],
[ 4.47574223e-02, -8.97126963e-02, 8.93308339e-02,
1.08342186e-01],
[ 4.29717080e-02, -9.14984106e-02, 8.75451196e-02,
1.06556472e-01]],
[[ 7.04717080e-02, -6.39984106e-02, 1.15045120e-01,
1.34056472e-01],
...
[-6.95282920e-02, -2.03998411e-01, -2.49548804e-02,
-5.94352836e-03]],
[[ 1.04717080e-02, -1.23998411e-01, 5.50451196e-02,
7.40564716e-02],
[-1.95282920e-02, -1.53998411e-01, 2.50451196e-02,
4.40564716e-02],
[-4.09568635e-02, -1.75426982e-01, 3.61654815e-03,
2.26279002e-02],
[-5.70282920e-02, -1.91498411e-01, -1.24548804e-02,
6.55647164e-03]],
[[ 3.04717080e-02, -1.03998411e-01, 7.50451196e-02,
9.40564716e-02],
[-2.86162536e-03, -1.37331744e-01, 4.17117862e-02,
6.07231383e-02],
[-2.66711492e-02, -1.61141268e-01, 1.79022624e-02,
3.69136145e-02],
[-4.45282920e-02, -1.78998411e-01, 4.51195806e-05,
1.90564716e-02]]]])
- Coordinates: (4)
- x
(x)
int64
0 1 2 - y
(y)
float64
0.0 0.1 0.2 0.3 ... 0.7 0.8 0.9 1.0
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ]) - z
(z)
int64
0 1 2 3 - w
(w)
<U5
'one' 'two' 'three' 'five'
array(['one', 'two', 'three', 'five'], dtype='<U5')
- x
- Indexes: (4)
- PandasIndex
PandasIndex(Index([0, 1, 2], dtype='int64', name='x')) - PandasIndex
PandasIndex(Index([ 0.0, 0.1, 0.2,
0.30000000000000004, 0.4, 0.5,
0.6000000000000001, 0.7000000000000001, 0.8,
0.9, 1.0],
dtype='float64', name='y')) - PandasIndex
PandasIndex(Index([0, 1, 2, 3], dtype='int64', name='z')) - PandasIndex
PandasIndex(Index(['one', 'two', 'three', 'five'], dtype='object', name='w'))
- PandasIndex
- Attributes: (1)
ds.A.plot.scatter(x="y");
Same plot can be displayed using the dataset:
ds.plot.scatter(x="y", y="A");
Now suppose we want to scatter the A
DataArray against the B
DataArray
ds.plot.scatter(x="A", y="B");
The hue
kwarg lets you vary the color by variable value
ds.plot.scatter(x="A", y="B", hue="w");
You can force a legend instead of a colorbar by setting add_legend=True, add_colorbar=False
.
ds.plot.scatter(x="A", y="B", hue="w", add_legend=True, add_colorbar=False);
ds.plot.scatter(x="A", y="B", hue="w", add_legend=False, add_colorbar=True);
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.
ds.plot.scatter(x="A", y="B", hue="y", markersize="z");
The z
kwarg lets you plot the data along the z-axis as well.
ds.plot.scatter(x="A", y="B", z="z", hue="y", markersize="x");
Faceting is also possible
ds.plot.scatter(x="A", y="B", hue="y", markersize="x", row="x", col="w");
And adding the z-axis
ds.plot.scatter(x="A", y="B", z="z", hue="y", markersize="x", row="x", col="w");
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:
ds.isel(w=1, z=1).plot.quiver(x="x", y="y", u="A", v="B");
where u
and v
denote the x and y direction components of the arrow vectors. Again, faceting is also possible:
ds.plot.quiver(x="x", y="y", u="A", v="B", col="w", row="z", scale=4);
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:
ds.isel(w=1, z=1).plot.streamplot(x="x", y="y", u="A", v="B");
where u
and v
denote the x and y direction components of the vectors tangent to the streamlines. Again, faceting is also possible:
ds.plot.streamplot(x="x", y="y", u="A", v="B", col="w", row="z");
Maps#
To follow this section you’ll need to have Cartopy installed and working.
This script will plot the air temperature on a map.
air = xr.tutorial.open_dataset("air_temperature").air
p = air.isel(time=0).plot( subplot_kws=dict(projection=ccrs.Orthographic(-80, 35), facecolor="gray"), transform=ccrs.PlateCarree(), ) p.axes.set_global()
p.axes.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
:
p = air.isel(time=[0, 4]).plot( transform=ccrs.PlateCarree(), col="time", subplot_kws={"projection": ccrs.Orthographic(-80, 35)}, ) for ax in p.axs.flat: ax.coastlines() ax.gridlines()
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.
da = xr.DataArray(range(5)) fig, axs = plt.subplots(ncols=2, nrows=2) da.plot(ax=axs[0, 0]) da.plot.line(ax=axs[0, 1]) xr.plot.plot(da, ax=axs[1, 0]) xr.plot.line(da, ax=axs[1, 1]);
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:
Coordinates#
If you’d like to find out what’s really going on in the coordinate system, read on.
a0 = xr.DataArray(np.zeros((4, 3, 2)), dims=("y", "x", "z"), name="temperature") a0[0, 0, 0] = 1 a = a0.isel(z=0) a
<xarray.DataArray 'temperature' (y: 4, x: 3)> Size: 96B array([[1., 0., 0.], [0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]) Dimensions without coordinates: y, x
- 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
array([[1., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]]) - Coordinates: (0)
- Indexes: (0)
- Attributes: (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.
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:
lon, lat = np.meshgrid(np.linspace(-20, 20, 5), np.linspace(0, 30, 4)) lon += lat / 10 lat += lon / 10 da = xr.DataArray( np.arange(20).reshape(4, 5), dims=["y", "x"], coords={"lat": (("y", "x"), lat), "lon": (("y", "x"), lon)}, )
da.plot.pcolormesh(x="lon", y="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:
ax = plt.subplot(projection=ccrs.PlateCarree()) da.plot.pcolormesh(x="lon", y="lat", ax=ax) ax.scatter(lon, lat, transform=ccrs.PlateCarree()) ax.coastlines() ax.gridlines(draw_labels=True);
/home/docs/checkouts/readthedocs.org/user_builds/xray/conda/stable/lib/python3.13/site-packages/cartopy/io/init.py:241: DownloadWarning: Downloading: https://naturalearth.s3.amazonaws.com/50m_physical/ne_50m_coastline.zip warnings.warn(f'Downloading: {url}', DownloadWarning)
You can however decide to infer the cell boundaries and use theinfer_intervals
keyword:
ax = plt.subplot(projection=ccrs.PlateCarree()) da.plot.pcolormesh(x="lon", y="lat", ax=ax, infer_intervals=True) ax.scatter(lon, lat, transform=ccrs.PlateCarree()) ax.coastlines() ax.gridlines(draw_labels=True);
Note
The data model of xarray does not support datasets with cell boundariesyet. 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.
f, ax = plt.subplots(2, 1) da.plot.line(x="lon", hue="y", ax=ax[0]) da.plot.line(x="lon", hue="x", ax=ax[1]);