I’m trying to clip a tiff that has elevation GeoTIFF for North America, available here under Reference Files.
I’d like to clip the dataset so it only contains data relevant to most of Alaska. When plotting, I know I could limit the extent visualized by a figure, but plotting with plt.countourf
takes a long time and I was wondering if clipping would save time when using plt.contourf
.
When I try and clip the xarray dataset, I’m not sure why I’m getting a NoDataInBounds
error message.
# python v 3.12.3
import xarray # 2024.3.0; rioxarray = 0.15.5
import geopandas as gpd # 0.14.4
from shapely.geometry import box # 2.0.3
import matplotlib.pyplot as plt # 3.8.4
import cartopy.crs as ccrs # 0.22.0
# define alaska extent
alaska = gpd.GeoDataFrame(
geometry=[
box(-170, 52, -140, 72)
],
crs="epsg:4326"
)
# read in elevation.tif
geofile = '/path/to/elevation.tif'
x_xim = 'x'
y_dim = 'y'
ds = xarray.open_dataset(geofile)
ds.rio.set_spatial_dims(x_dim=x_dim, y_dim=y_dim, inplace=True)
ds.rio.write_crs("epsg:4326", inplace=True)
# this is where I get an error
ds_clipped = ds.rio.clip(alaska.geometry.values, alaska.crs, drop=True)
# what I'd like to do with the clipped data
layer = 'band_data'
vals = ds_clipped[layer][0, :, :]
lons = ds_clipped[layer][x_dim]
lats = ds_clipped[layer][y_dim]
fig = plt.figure()
ax = plt.axes(projection=ccrs.OSGB())
contours = plt.contourf(
lons,
lats,
vals,
20,
cmap='magma',
transform=ccrs.PlateCarree(),
origin='lower'
)