⚠️ Our 0.1 release refactored several early-development functions for long-term stability, to update your code see here. ⚠️
Future changes will come with deprecation warnings! 🙂

Crop a vector

Crop a vector#

This example demonstrates the cropping of a vector using geoutils.Vector.crop().

We open a raster and vector.

import geoutils as gu

filename_rast = gu.examples.get_path("everest_landsat_b4_cropped")
filename_vect = gu.examples.get_path("everest_rgi_outlines")
rast = gu.Raster(filename_rast)
vect = gu.Vector(filename_vect)

Let’s plot the raster and vector. The raster has smaller extent than the vector.

rast.plot(cmap="Greys_r", alpha=0.7)
vect.plot(ref_crs=rast, fc="none", ec="tab:purple", lw=3)
crop vector

First option: using the raster as a reference to match, we crop the vector. We simply have to pass the Raster as single argument to crop(). See Match-reference functionality for more details.

vect.crop(rast, inplace=True)

Note

By default, crop() is done in-place, replacing vect. This behaviour can be modified by passing inplace=False.

rast.plot(ax="new", cmap="Greys_r", alpha=0.7)
vect.plot(ref_crs=rast, fc="none", ec="tab:purple", lw=3)
crop vector

The crop() keeps all features with geometries intersecting the extent to crop to. We can also force a clipping of the geometries within the bounds using clip=True.

vect.crop(rast, clip=True)
rast.plot(ax="new", cmap="Greys_r", alpha=0.7)
vect.plot(ref_crs=rast, fc="none", ec="tab:purple", lw=3)
crop vector

Second option: we can pass other crop_geom argument to crop(), including another Vector or a simple tuple of bounds.

bounds = rast.get_bounds_projected(out_crs=vect.crs)
vect.crop(
    crop_geom=(bounds.left + 0.5 * (bounds.right - bounds.left), bounds.bottom, bounds.right, bounds.top), inplace=True
)

rast.plot(ax="new", cmap="Greys_r", alpha=0.7)
vect.plot(ref_crs=rast, fc="none", ec="tab:purple", lw=3)
crop vector

Total running time of the script: (0 minutes 0.746 seconds)

Gallery generated by Sphinx-Gallery