Last active
October 7, 2024 14:40
-
-
Save brews/95e167fb7df997864304f07ee321f4fd to your computer and use it in GitHub Desktop.
Demo using cartopy.util.add_cyclic_point with an xarray Dataset to add a cyclic or wrap-around pixel to the `lon` dimension. This can be useful for plotting with `cartopy` or regridding with `xesmf`.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Demo using cartopy.util.add_cyclic_point with an xarray Dataset to | |
add a cyclic or wrap-around pixel to the `lon` dimension. This can be useful | |
for plotting with `cartopy` or regridding with `xesmf`. | |
""" | |
import xarray as xr | |
from cartopy.util import add_cyclic_point | |
def cyclic_wrapper(x, dim="lon"): | |
"""So add_cyclic_point() works on 'dim' via xarray Dataset.map()""" | |
wrap_data, wrap_lon = add_cyclic_point( | |
x.values, | |
coord=x.coords[dim].data, | |
axis=x.dims.index(dim) | |
) | |
return xr.DataArray( | |
wrap_data, | |
coords={dim: wrap_lon, **x.drop(dim).coords}, | |
dims=x.dims | |
) | |
# Whatever data you want to plot or regrid. Needs "lon" dim. | |
raw = xr.open_dataset("somedata.nc") | |
# Add cyclic points. | |
ds = raw.map(cyclic_wrapper, keep_attrs=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment