Home > OS >  How to control the order of facet gird rows and/or columns in xarray?
How to control the order of facet gird rows and/or columns in xarray?

Time:02-11

I am trying to change the order of variables I use to make a facet grid in xarray. For example, I have [a,b,c,d] as column names. I want to reorder it to [c,d,a,b]. Unfortunately, unlike enter image description here

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr
ds = xr.tutorial.open_dataset("air_temperature.nc").rename({"air": "Tair"})

# we will add a gradient field with appropriate attributes
ds["dTdx"] = ds.Tair.differentiate("lon") / 110e3 / np.cos(ds.lat * np.pi / 180)
ds["dTdy"] = ds.Tair.differentiate("lat") / 105e3
ds.dTdx.attrs = {"long_name": "$∂T/∂x$", "units": "°C/m"}
ds.dTdy.attrs = {"long_name": "$∂T/∂y$", "units": "°C/m"}
monthly_means = ds.groupby("time.month").mean()
# xarray's groupby reductions drop attributes. Let's assign them back so we get nice labels.
monthly_means.Tair.attrs = ds.Tair.attrs
fg = monthly_means.Tair.plot(
    col="month",
    col_wrap=4,  # each row has a maximum of 4 columns
)
plt.show()

Any help is highly appreciated.

CodePudding user response:

xarray will respect the shape of your data, so you can rearrange the data prior to plotting:

In [2]: ds = xr.tutorial.open_dataset("air_temperature.nc")

In [3]: ds_mon = ds.groupby("time.month").mean()

In [4]: # order the data by month, descending
   ...: ds_mon.air.sel(month=list(range(12, 0, -1))).plot(
   ...:     col="month", col_wrap=4,
   ...: )

Out[4]: <xarray.plot.facetgrid.FacetGrid at 0x16b9a7700>

plot with monthly average air temperatures arranged in descending order

  • Related