Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save trondkr/62b6795397420e54f728cf4ab563a14c to your computer and use it in GitHub Desktop.
Save trondkr/62b6795397420e54f728cf4ab563a14c 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`.
"""
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