You can run this notebook in a live session Binder or view it on Github.

Working with Multidimensional Coordinates#

Author: Ryan Abernathey

Many datasets have physical coordinates which differ from their logical coordinates. Xarray provides several ways to plot and analyze such datasets.

[1]:
%matplotlib inline
importnumpyasnp
importpandasaspd
importxarrayasxr
importcartopy.crsasccrs
frommatplotlibimport pyplot as plt

As an example, consider this dataset from the xarray-data repository.

[2]:
ds = xr.tutorial.open_dataset("rasm").load()
ds
[2]:
<xarray.Dataset> Size: 17MB
Dimensions: (time: 36, y: 205, x: 275)
Coordinates:
 * time (time) object 288B 1980年09月16日 12:00:00 ... 1983年08月17日 00:00:00
 xc (y, x) float64 451kB 189.2 189.4 189.6 189.7 ... 17.4 17.15 16.91
 yc (y, x) float64 451kB 16.53 16.78 17.02 17.27 ... 28.01 27.76 27.51
Dimensions without coordinates: y, x
Data variables:
 Tair (time, y, x) float64 16MB nan nan nan nan ... 28.66 28.19 28.21
Attributes:
 title: /workspace/jhamman/processed/R1002RBRxaaa01a/l...
 institution: U.W.
 source: RACM R1002RBRxaaa01a
 output_frequency: daily
 output_mode: averaged
 convention: CF-1.4
 references: Based on the initial model of Liang et al., 19...
 comment: Output from the Variable Infiltration Capacity...
 nco_openmp_thread_number: 1
 NCO: netCDF Operators version 4.7.9 (Homepage = htt...
 history: Fri Aug 7 17:57:38 2020: ncatted -a bounds,,d...
xarray.Dataset
    • time: 36
    • y: 205
    • x: 275
    • time
      (time)
      object
      1980年09月16日 12:00:00 ... 1983-08-...
      long_name :
      time
      type_preferred :
      int
      array([cftime.DatetimeNoLeap(1980, 9, 16, 12, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1980, 10, 17, 0, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1980, 11, 16, 12, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1980, 12, 17, 0, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1981, 1, 17, 0, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1981, 2, 15, 12, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1981, 3, 17, 0, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1981, 4, 16, 12, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1981, 5, 17, 0, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1981, 6, 16, 12, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1981, 7, 17, 0, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1981, 8, 17, 0, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1981, 9, 16, 12, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1981, 10, 17, 0, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1981, 11, 16, 12, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1981, 12, 17, 0, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1982, 1, 17, 0, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1982, 2, 15, 12, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1982, 3, 17, 0, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1982, 4, 16, 12, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1982, 5, 17, 0, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1982, 6, 16, 12, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1982, 7, 17, 0, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1982, 8, 17, 0, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1982, 9, 16, 12, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1982, 10, 17, 0, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1982, 11, 16, 12, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1982, 12, 17, 0, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1983, 1, 17, 0, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1983, 2, 15, 12, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1983, 3, 17, 0, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1983, 4, 16, 12, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1983, 5, 17, 0, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1983, 6, 16, 12, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1983, 7, 17, 0, 0, 0, 0, has_year_zero=True),
       cftime.DatetimeNoLeap(1983, 8, 17, 0, 0, 0, 0, has_year_zero=True)],
       dtype=object)
    • xc
      (y, x)
      float64
      189.2 189.4 189.6 ... 17.15 16.91
      long_name :
      longitude of grid cell center
      units :
      degrees_east
      array([[189.22293223, 189.38990916, 189.55836619, ..., 293.77906088,
       294.0279241 , 294.27439931],
       [188.96836986, 189.13470591, 189.30253733, ..., 294.05584005,
       294.30444387, 294.55065969],
       [188.71234264, 188.87800731, 189.04515208, ..., 294.335053 ,
       294.58337453, 294.8292928 ],
       ...,
       [124.04724025, 123.88362026, 123.71852016, ..., 16.83171831,
       16.58436953, 16.33949649],
       [123.78686428, 123.62254238, 123.45672512, ..., 17.11814486,
       16.87043749, 16.62518298],
       [123.52798366, 123.36295986, 123.1964407 , ..., 17.40209947,
       17.1540526 , 16.90845095]], shape=(205, 275))
    • yc
      (y, x)
      float64
      16.53 16.78 17.02 ... 27.76 27.51
      long_name :
      latitude of grid cell center
      units :
      degrees_north
      array([[16.53498637, 16.7784556 , 17.02222429, ..., 27.36301592,
       27.11811045, 26.87289026],
       [16.69397341, 16.93865381, 17.18364512, ..., 27.5847719 ,
       27.33821848, 27.0913656 ],
       [16.85219179, 17.09808909, 17.34430872, ..., 27.80584314,
       27.55764558, 27.30915621],
       ...,
       [17.31179033, 17.56124674, 17.81104646, ..., 28.4502485 ,
       28.19718339, 27.94384744],
       [17.15589701, 17.40414034, 17.65272318, ..., 28.23129632,
       27.97989251, 27.72821596],
       [16.99919497, 17.24622904, 17.49358736, ..., 28.01160028,
       27.76185586, 27.51182726]], shape=(205, 275))
    • Tair
      (time, y, x)
      float64
      nan nan nan ... 28.66 28.19 28.21
      units :
      C
      long_name :
      Surface air temperature
      type_preferred :
      double
      time_rep :
      instantaneous
      array([[[ nan, nan, nan, ..., nan,
       nan, nan],
       [ nan, nan, nan, ..., nan,
       nan, nan],
       [ nan, nan, nan, ..., nan,
       nan, nan],
       ...,
       [ nan, nan, nan, ..., 27.03290153,
       27.03125761, 27.33531541],
       [ nan, nan, nan, ..., 27.2784053 ,
       26.80261869, 27.08603517],
       [ nan, nan, nan, ..., 27.02344402,
       26.56473862, 26.73064933]],
       [[ nan, nan, nan, ..., nan,
       nan, nan],
       [ nan, nan, nan, ..., nan,
       nan, nan],
       [ nan, nan, nan, ..., nan,
       nan, nan],
      ...
       [ nan, nan, nan, ..., 27.8597472 ,
       27.82928439, 28.09249224],
       [ nan, nan, nan, ..., 27.89704094,
       27.31104941, 27.67387171],
       [ nan, nan, nan, ..., 27.46837113,
       27.0088944 , 27.23017976]],
       [[ nan, nan, nan, ..., nan,
       nan, nan],
       [ nan, nan, nan, ..., nan,
       nan, nan],
       [ nan, nan, nan, ..., nan,
       nan, nan],
       ...,
       [ nan, nan, nan, ..., 28.95929072,
       28.87672039, 29.04890862],
       [ nan, nan, nan, ..., 29.036132 ,
       28.42273578, 28.68721201],
       [ nan, nan, nan, ..., 28.66381585,
       28.18595533, 28.20753022]]], shape=(36, 205, 275))
  • title :
    /workspace/jhamman/processed/R1002RBRxaaa01a/lnd/temp/R1002RBRxaaa01a.vic.ha.1979年09月01日.nc
    institution :
    U.W.
    source :
    RACM R1002RBRxaaa01a
    output_frequency :
    daily
    output_mode :
    averaged
    convention :
    CF-1.4
    references :
    Based on the initial model of Liang et al., 1994, JGR, 99, 14,415- 14,429.
    comment :
    Output from the Variable Infiltration Capacity (VIC) model.
    nco_openmp_thread_number :
    1
    NCO :
    netCDF Operators version 4.7.9 (Homepage = http://nco.sf.net, Code = http://github.com/nco/nco)
    history :
    Fri Aug 7 17:57:38 2020: ncatted -a bounds,,d,, rasm.nc Tue Dec 27 14:15:22 2016: ncatted -a dimensions,,d,, rasm.nc rasm.nc Tue Dec 27 13:38:40 2016: ncks -3 rasm.nc rasm.nc history deleted for brevity

In this example, the logical coordinates are x and y, while the physical coordinates are xc and yc, which represent the longitudes and latitudes of the data.

[3]:
print(ds.xc.attrs)
print(ds.yc.attrs)
{'long_name': 'longitude of grid cell center', 'units': 'degrees_east'}
{'long_name': 'latitude of grid cell center', 'units': 'degrees_north'}

Plotting#

Let’s examine these coordinate variables by plotting them.

[4]:
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(14, 4))
ds.xc.plot(ax=ax1)
ds.yc.plot(ax=ax2)
[4]:
<matplotlib.collections.QuadMesh at 0x7cc67f17f750>
../_images/examples_multidimensional-coords_7_1.png

Note that the variables xc (longitude) and yc (latitude) are two-dimensional scalar fields.

If we try to plot the data variable Tair, by default we get the logical coordinates.

[5]:
ds.Tair[0].plot()
[5]:
<matplotlib.collections.QuadMesh at 0x7cc6743adf90>
../_images/examples_multidimensional-coords_9_1.png

In order to visualize the data on a conventional latitude-longitude grid, we can take advantage of xarray’s ability to apply cartopy map projections.

[6]:
plt.figure(figsize=(14, 6))
ax = plt.axes(projection=ccrs.PlateCarree())
ax.set_global()
ds.Tair[0].plot.pcolormesh(
 ax=ax, transform=ccrs.PlateCarree(), x="xc", y="yc", add_colorbar=False
)
ax.coastlines()
ax.set_ylim([0, 90]);
../_images/examples_multidimensional-coords_11_0.png

Multidimensional Groupby#

The above example allowed us to visualize the data on a regular latitude-longitude grid. But what if we want to do a calculation that involves grouping over one of these physical coordinates (rather than the logical coordinates), for example, calculating the mean temperature at each latitude. This can be achieved using xarray’s groupby function, which accepts multidimensional variables. By default, groupby will use every unique value in the variable, which is probably not what we want. Instead, we can use the groupby_bins function to specify the output coordinates of the group.

[7]:
# define two-degree wide latitude bins
lat_bins = np.arange(0, 91, 2)
# define a label for each bin corresponding to the central latitude
lat_center = np.arange(1, 90, 2)
# group according to those bins and take the mean
Tair_lat_mean = ds.Tair.groupby_bins("yc", lat_bins, labels=lat_center).mean(
 dim=xr.ALL_DIMS
)
# plot the result
Tair_lat_mean.plot()
[7]:
[<matplotlib.lines.Line2D at 0x7cc67416b8c0>]
../_images/examples_multidimensional-coords_13_1.png

The resulting coordinate for the groupby_bins operation got the _bins suffix appended: yc_bins. This help us distinguish it from the original multidimensional variable yc.

Note: This group-by-latitude approach does not take into account the finite-size geometry of grid cells. It simply bins each value according to the coordinates at the cell center. Xarray has no understanding of grid cells and their geometry. More precise geographic regridding for xarray data is available via the xesmf package.