Introduction to Exploratory Analysis with Xarray
Introduction to Exploratory Analysis with Xarray¶
Overview¶
This notebook will introduce the basics of gridded, labeled data with Xarray. Since Xarray introduces additional abstractions on top of plain arrays of data, our goal is to show why these abstractions are useful and how they frequently lead to simpler, more robust code.
We’ll cover these topics:
- Create a
DataArray
, one of the core object types in Xarray - Understand how to use named coordinates and metadata in a
DataArray
- Combine individual
DataArrays
into aDataset
, the other core object type in Xarray - Subset, slice, and interpolate the data using named coordinates
- Open netCDF data using XArray
- Basic subsetting and aggregation of a
Dataset
- Brief introduction to plotting with Xarray
Prerequisites¶
Concepts | Importance | Notes |
---|---|---|
NumPy Basics | Necessary | |
Intermediate NumPy | Helpful | Familiarity with indexing and slicing arrays |
NumPy Broadcasting | Helpful | Familiar with array arithmetic and broadcasting |
Introduction to Pandas | Helpful | Familiarity with labeled data |
Datetime | Helpful | Familiarity with time formats and the timedelta object |
Understanding of NetCDF | Helpful | Familiarity with metadata structure |
- Time to learn: 30 minutes
Imports¶
Simmilar to numpy
, np
; pandas
, pd
; you may often encounter xarray
imported within a shortened namespace as xr
.
from datetime import timedelta
import act
import numpy as np
import pandas as pd
import xarray as xr
from bokeh.models.formatters import DatetimeTickFormatter
import hvplot.xarray
import holoviews as hv
hv.extension("bokeh")
Introducing the DataArray
and Dataset
¶
Xarray expands on the capabilities on NumPy arrays, providing a lot of streamlined data manipulation. It is similar in that respect to Pandas, but whereas Pandas excels at working with tabular data, Xarray is focused on N-dimensional arrays of data (i.e. grids). Its interface is based largely on the netCDF data model (variables, attributes, and dimensions), but it goes beyond the traditional netCDF interfaces to provide functionality similar to netCDF-java’s Common Data Model (CDM).
Creation of a DataArray
object¶
The DataArray
is one of the basic building blocks of Xarray (see docs here). It provides a numpy.ndarray
-like object that expands to provide two critical pieces of functionality:
- Coordinate names and values are stored with the data, making slicing and indexing much more powerful
- It has a built-in container for attributes
Here we’ll initialize a DataArray
object by wrapping a plain NumPy array, and explore a few of its properties.
Generate a random numpy array¶
For our first example, we’ll just create a random array of “temperature” data in units of Kelvin:
data = 283 + 5 * np.random.randn(5, 3, 4)
data
array([[[280.49034602, 289.54027519, 284.90655811, 284.31047258],
[275.70250107, 290.261588 , 277.769484 , 284.05690993],
[287.1508349 , 286.77287813, 282.00067199, 290.75701206]],
[[278.65070817, 276.33802113, 277.46975656, 282.68908609],
[289.43731285, 286.58258032, 284.84620581, 292.77605571],
[283.35137003, 280.10646213, 279.02542904, 276.0029519 ]],
[[284.19759813, 280.16773186, 279.50205068, 280.29024231],
[288.17120017, 281.55684328, 276.64253371, 281.16874247],
[282.5182534 , 277.90430444, 284.27414367, 269.35867572]],
[[281.07565467, 283.11833003, 281.03212614, 287.5456723 ],
[287.05433492, 288.95866567, 279.16242516, 287.31560099],
[275.78686409, 280.78870682, 279.31226614, 281.14050152]],
[[285.39457491, 286.41972907, 288.31908821, 280.12521887],
[287.98458881, 296.59766794, 288.38541017, 289.43993741],
[284.40721534, 281.45802395, 280.16106033, 276.44172452]]])
Wrap the array: first attempt¶
Now we create a basic DataArray
just by passing our plain data
as input:
temp = xr.DataArray(data)
temp
Note two things:
- Xarray generates some basic dimension names for us (
dim_0
,dim_1
,dim_2
). We’ll improve this with better names in the next example. - Wrapping the numpy array in a
DataArray
gives us a rich display in the notebook! (Try clicking the array symbol to expand or collapse the view)
Assign dimension names¶
Much of the power of Xarray comes from making use of named dimensions. So let’s add some more useful names! We can do that by passing an ordered list of names using the keyword argument dims
:
temp = xr.DataArray(data, dims=['time', 'lat', 'lon'])
temp
This is already improved upon from a NumPy array, because we have names for each of the dimensions (or axes in NumPy parlance). Even better, we can take arrays representing the values for the coordinates for each of these dimensions and associate them with the data when we create the DataArray
. We’ll see this in the next example.
Create a DataArray
with named Coordinates¶
Make time and space coordinates¶
Here we will use Pandas to create an array of datetime data, which we will then use to create a DataArray
with a named coordinate time
.
times = pd.date_range('2018-01-01', periods=5)
times
DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',
'2018-01-05'],
dtype='datetime64[ns]', freq='D')
We’ll also create arrays to represent sample longitude and latitude:
lons = np.linspace(-120, -60, 4)
lats = np.linspace(25, 55, 3)
Initialize the DataArray
with complete coordinate info¶
When we create the DataArray
instance, we pass in the arrays we just created:
temp = xr.DataArray(data, coords=[times, lats, lons], dims=['time', 'lat', 'lon'])
temp
Set useful attributes¶
...and while we’re at it, we can also set some attribute metadata:
temp.attrs['units'] = 'kelvin'
temp.attrs['standard_name'] = 'air_temperature'
temp
Attributes are not preserved by default!¶
Notice what happens if we perform a mathematical operaton with the DataArray
: the coordinate values persist, but the attributes are lost. This is done because it is very challenging to know if the attribute metadata is still correct or appropriate after arbitrary arithmetic operations.
To illustrate this, we’ll do a simple unit conversion from Kelvin to Celsius:
temp_in_celsius = temp - 273.15
temp_in_celsius
For an in-depth discussion of how Xarray handles metadata, start in the Xarray docs here.
The Dataset
: a container for DataArray
s with shared coordinates¶
Along with DataArray
, the other key object type in Xarray is the Dataset
: a dictionary-like container that holds one or more DataArray
s, which can also optionally share coordinates (see docs here).
The most common way to create a Dataset
object is to load data from a file (see below). Here, instead, we will create another DataArray
and combine it with our temp
data.
This will illustrate how the information about common coordinate axes is used.
Create a pressure DataArray
using the same coordinates¶
This code mirrors how we created the temp
object above.
pressure_data = 1000.0 + 5 * np.random.randn(5, 3, 4)
pressure = xr.DataArray(
pressure_data, coords=[times, lats, lons], dims=['time', 'lat', 'lon']
)
pressure.attrs['units'] = 'hPa'
pressure.attrs['standard_name'] = 'air_pressure'
pressure
Create a Dataset
object¶
Each DataArray
in our Dataset
needs a name!
The most straightforward way to create a Dataset
with our temp
and pressure
arrays is to pass a dictionary using the keyword argument data_vars
:
ds = xr.Dataset(data_vars={'Temperature': temp, 'Pressure': pressure})
ds
Notice that the Dataset
object ds
is aware that both data arrays sit on the same coordinate axes.
Access Data variables and Coordinates in a Dataset
¶
We can pull out any of the individual DataArray
objects in a few different ways.
Using the “dot” notation:
ds.Pressure
... or using dictionary access like this:
ds['Pressure']
We’ll return to the Dataset
object when we start loading data from files.
Subsetting and selection by coordinate values¶
Much of the power of labeled coordinates comes from the ability to select data based on coordinate names and values, rather than array indices. We’ll explore this briefly here.
NumPy-like selection¶
Suppose we want to extract all the spatial data for one single date: January 2, 2018. It’s possible to achieve that with NumPy-like index selection:
indexed_selection = temp[1, :, :] # Index 1 along axis 0 is the time slice we want...
indexed_selection
HOWEVER, notice that this requires us (the user / programmer) to have detailed knowledge of the order of the axes and the meaning of the indices along those axes!
Named coordinates free us from this burden...
Selecting with .sel()
¶
We can instead select data based on coordinate values using the .sel()
method, which takes one or more named coordinate(s) as keyword argument:
named_selection = temp.sel(time='2018-01-02')
named_selection
We got the same result, but
- we didn’t have to know anything about how the array was created or stored
- our code is agnostic about how many dimensions we are dealing with
- the intended meaning of our code is much clearer!
Approximate selection and interpolation¶
With time and space data, we frequently want to sample “near” the coordinate points in our dataset. Here are a few simple ways to achieve that.
Nearest-neighbor sampling¶
Suppose we want to sample the nearest datapoint within 2 days of date 2018-01-07
. Since the last day on our time
axis is 2018-01-05
, this is well-posed.
.sel
has the flexibility to perform nearest neighbor sampling, taking an optional tolerance:
temp.sel(time='2018-01-07', method='nearest', tolerance=timedelta(days=2))
where we see that .sel
indeed pulled out the data for date 2018-01-05
.
Interpolation¶
Suppose we want to extract a timeseries for Boulder (40°N, 105°W). Since lon=-105
is not a point on our longitude axis, this requires interpolation between data points.
The .interp()
method (see the docs here) works similarly to .sel()
. Using .interp()
, we can interpolate to any latitude/longitude location:
temp.interp(lon=-105, lat=40)
Info
Xarray's interpolation functionality requires the SciPy package!Slicing along coordinates¶
Frequently we want to select a range (or slice) along one or more coordinate(s). We can achieve this by passing a Python slice object to .sel()
, as follows:
temp.sel(
time=slice('2018-01-01', '2018-01-03'), lon=slice(-110, -70), lat=slice(25, 45)
)
Info
The calling sequence forslice
always looks like slice(start, stop[, step])
, where step
is optional.Notice how the length of each coordinate axis has changed due to our slicing.
One more selection method: .loc
¶
All of these operations can also be done within square brackets on the .loc
attribute of the DataArray
:
temp.loc['2018-01-02']
This is sort of in between the NumPy-style selection
temp[1,:,:]
and the fully label-based selection using .sel()
With .loc
, we make use of the coordinate values, but lose the ability to specify the names of the various dimensions. Instead, the slicing must be done in the correct order:
temp.loc['2018-01-01':'2018-01-03', 25:45, -110:-70]
One advantage of using .loc
is that we can use NumPy-style slice notation like 25:45
, rather than the more verbose slice(25,45)
. But of course that also works:
temp.loc['2018-01-01':'2018-01-03', slice(25, 45), -110:-70]
What doesn’t work is passing the slices in a different order:
# This will generate an error
# temp.loc[-110:-70, 25:45,'2018-01-01':'2018-01-03']
Opening netCDF data¶
With its close ties to the netCDF data model, Xarray also supports netCDF as a first-class file format. This means it has easy support for opening netCDF datasets, so long as they conform to some of Xarray’s limitations (such as 1-dimensional coordinates).
Access netCDF data with xr.open_dataset
¶
username = 'mgrover4'
token = '176e1559b67be630'
# Let's download three hours of vertically pointing cloud radar data from the CAPE-k field site
results = act.discovery.download_arm_data(username,
token,
'kcgkazrcfrcorgeM1.c0',
'2025-01-01T00:00:00',
'2025-01-01T04:00:00')
[DOWNLOADING] kcgkazrcfrcorgeM1.c0.20250101.000000.nc
If you use these data to prepare a publication, please cite:
Toto, T., & Giangrande, S. Ka-Band ARM Zenith RADAR (KAZR) CF-Radial, Corrected
VAP (KAZRCFRCORGE), 2025-01-01 to 2025-01-01, ARM Mobile Facility (KCG),
kennaook ⁄ Cape Grim, Tasmania, Australia; AMF2 (main site for CAPE-k) (M1).
Atmospheric Radiation Measurement (ARM) User Facility.
https://doi.org/10.5439/1560129
Once we have a valid path to a data file that Xarray knows how to read, we can open it like this:
ds = xr.open_mfdataset(results)
Subsetting the Dataset
¶
Our call to xr.open_dataset()
above returned a Dataset
object that we’ve decided to call ds
. We can then pull out individual fields:
ds.reflectivity
(recall that we can also use dictionary syntax like ds['isobaric1']
to do the same thing)
Dataset
s also support much of the same subsetting operations as DataArray
, but will perform the operation on all data:
subset = ds.sel(time=slice('2025-01-01T00:00:00',
'2025-01-01T04:00:00'))
subset
And further subsetting to a single DataArray
:
subset.reflectivity
Aggregation operations¶
Not only can you use the named dimensions for manual slicing and indexing of data, but you can also use it to control aggregation operations, like std
(standard deviation):
reflectivity = subset['reflectivity']
reflectivity.std(dim=['range'])
Info
Aggregation methods for Xarray objects operate over the named coordinate dimension(s) specified by keyword argumentdim
. Compare to NumPy, where aggregations operate over specified numbered axes
.Using the sample dataset, we can calculate the temperature profile across our time period!
temps = subset.temp
temps_lowest_5000m = temps.sel(range=slice(0., 5000))
prof = temps_lowest_5000m.mean(dim="time")
prof
Plotting with Xarray¶
Another major benefit of using labeled data structures is that they enable automated plotting with sensible axis labels.
Simple visualization with .plot()
¶
Much like we saw in Pandas, Xarray includes an interface to Matplotlib that we can access through the .plot()
method of every DataArray
.
For quick and easy data exploration, we can just call .plot()
without any modifiers:
prof.plot();

Here Xarray has generated a line plot of the temperature data against the coordinate variable isobaric
. Also the metadata are used to auto-generate axis labels and units.
Customizing the plot¶
As in Pandas, the .plot()
method is mostly just a wrapper to Matplotlib, so we can customize our plot in familiar ways.
In this air temperature profile example, we would like to make two changes:
- swap the axes so that we have isobaric levels on the y (vertical) axis of the figure
- make pressure decrease upward in the figure, so that up is up
A few keyword arguments to our .plot()
call will take care of this:
prof.plot(y="range")

Plotting 2D data¶
In the example above, the .plot()
method produced a line plot.
What if we call .plot()
on a 2D array?
temps.sel(range=slice(0, 5000)).plot(y='range', cmap='Spectral_r');

We can also make this interactive!
temps.sel(range=slice(0, 5000)).hvplot(x='time',
y='range',
cmap='Spectral_r',)
subset.reflectivity.sel(range=slice(0, 5000)).plot(y='range', cmap='Spectral_r');

subset.reflectivity.sel(range=slice(0, 5000)).hvplot(x='time',
y='range',
cmap='Spectral_r',
clabel='Reflectivity (dBZ)')
Customize our Interactive Plots¶
Our time axis doesn’t tell us much... we can change that! Also note that we add additional parameters to customize our view of the field.
formatter = DatetimeTickFormatter(hours="%d %b %Y \n %H:%M UTC")
reflectivity_plot = subset.reflectivity.sel(range=slice(0, 5000)).hvplot(x='time',
y='range',
cmap='Spectral_r',
xformatter=formatter,
clim=(-20, 40),
clabel='Reflectivity (dBZ)')
reflectivity_plot
And the same for velocity...
velocity_plot = subset.mean_doppler_velocity.sel(range=slice(0, 5000)).hvplot(x='time',
y='range',
cmap='seismic',
xformatter=formatter,
clim=(-5, 5),
clabel='Mean Doppler Velocity (m/s)')
velocity_plot
Combine our Plots¶
Now that we have our interactive plots, we can combine them using +
reflectivity_plot + velocity_plot
Or stacked on top of each other...
(reflectivity_plot + velocity_plot).cols(1)
Xarray has recognized that the DataArray
object calling the plot method has two coordinate variables, and generates a 2D plot using the pcolormesh
method from Matplotlib.
In this case, we are looking at air temperatures on the 1000 hPa isobaric surface over North America. We could of course improve this figure by using Cartopy to handle the map projection and geographic features!
Summary¶
Xarray brings the joy of Pandas-style labeled data operations to N-dimensional data. As such, it has become a central workhorse in the geoscience community for the analysis of gridded datasets. Xarray allows us to open self-describing NetCDF files and make full use of the coordinate axes, labels, units, and other metadata. By making use of labeled coordinates, our code is often easier to write, easier to read, and more robust.
We also covered some interactive plots using xarray and hvPlot!
What’s next?¶
Additional notebooks to appear in this section will go into more detail about
- arithemtic and broadcasting with Xarray data structures
- using “group by” operations
- remote data access with OpenDAP
- more advanced visualization including map integration with Cartopy
Resources and references¶
This notebook was adapated from material in Unidata’s Python Training.
The best resource for Xarray is the Xarray documentation. See in particular
Another excellent resource is this Xarray Tutorial collection.