Reputation: 41
I'm a newbie here and also to xarray.
I have xarray datasets (dimension: time,lat,lon) which contain several data variables (e.g. ModelA, ModelB) that have identical dimensions&coordinates and I want to make multipanel plots over all variables of e.g. the first timestep.
For this, I'm trying to use the xarray facet plotting utility. After trial/error, I'm getting this done, but only in an extremely inelegant/inefficient manner, and I would very much appreciate any advice how to do his better.
I particularly wonder how combine two xarray DataArrays so that they appear as two separate data variables in an new xarray DataArray/DataSet, and how to tell xarray-plot() that it should take the data variables as "col" argument for facet plotting.
Thanks a lot for any help! Regards A.
My code looks as follows:
import numpy as np
import xarray as xr
import pandas as pd
from datetime import datetime
import nc_time_axis
import cftime
#(1) == Create dummy data, dimensions and coordinates
ntimes, nlat, nlon = 3, 8, 5
lat = np.linspace(-10,10,nlat)
lon = np.linspace(-20,20,nlon)
year, month, daystart = 2016, 3, 1
dayend = daystart + ntimes
datestart = str(year).zfill(2)+'-'+str(month).zfill(2)+'-'+str(daystart).zfill(2)
cfdates = xr.cftime_range(datestart, periods=ntimes, freq='1D', calendar='noleap')
data = np.random.randn(ntimes, len(lat),len(lon))
#(2) == Create template 3dim xarray dataarray (xrda) called varA
xrda3D = xr.DataArray(data,
coords=[cfdates, lat, lon],
dims=['time', 'lat','lon'])
#(3) == Create xarray dataset (xrds) with two data variables called "varA" and "varB"
xrds3D2var = xr.Dataset({'varA': xrda3D, 'varB': xrda3D*1.5})
#--> failed prior attempts, both leading to TypeError: unhashable type: 'DataArray' (?????)
#(a) xrda3D.name = "varA"; xrda2add=(xrda3D*1.5).rename("varB"); xrds3D2var = xr.Dataset(xrda3D,xrda2add)
#(b) xrds3D2var= xr.Dataset({'varA': xrda3D, 'varB': xrda2add} ) #
#(4) == create xrda with data variables encoded in additional dimensions "vardim"
# == like this, facet plotting can be used with name="vardim"
ovarname = '4Ddata'
arrlist = []
for varname in xrds3D2var.keys():
tmp = xrds3D2var[varname] #-- select xrda of individual data variables
arrlist.append(tmp) #-- append to list
xrda4D = xr.concat(arrlist, pd.Index(list(xrds3D2var.keys()), name='vardim'))
xrda4Dt = xrda4D.isel(time=0)
xrda4Dt.plot(col="vardim")
[xarray facet plot over data variables produced from code][1]
[1]: https://i.sstatic.net/ldMuT.png
Upvotes: 4
Views: 841
Reputation: 503
You should check .to_array()
. Then your code would be like the following
xrds3D2var.to_array().isel(time=0).plot(col = 'variable')
Upvotes: 2