Skip to content

Instantly share code, notes, and snippets.

@shoyer
Created October 6, 2015 23:27
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save shoyer/0eb96fa8ab683ef078eb to your computer and use it in GitHub Desktop.
Save shoyer/0eb96fa8ab683ef078eb to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@tommylees112
Copy link

Thank you for this!

Is this a correct commenting of your function rasterize()?

def rasterize(shapes, coords, latitude='latitude', longitude='longitude',
              fill=np.nan, **kwargs):
    """Rasterize a list of (geometry, fill_value) tuples onto the given
    xray coordinates. This only works for 1d latitude and longitude
    arrays.

    usage:
    -----
    1. read shapefile to geopandas.GeoDataFrame
          `states = gpd.read_file(shp_dir)`
    2. encode the different shapefiles that capture those lat-lons as different
        numbers i.e. 0.0, 1.0 ... and otherwise np.nan
          `shapes = (zip(states.geometry, range(len(states))))`
    3. Assign this to a new coord in your original xarray.DataArray
          `ds['states'] = rasterize(shapes, ds.coords, longitude='X', latitude='Y')`

    arguments:
    ---------
    : **kwargs (dict): passed to `rasterio.rasterize` function

    attrs:
    -----
    :transform (affine.Affine): how to translate from latlon to ...?
    :raster (numpy.ndarray): use rasterio.features.rasterize fill the values
      outside the .shp file with np.nan
    :spatial_coords (dict): dictionary of {"X":xr.DataArray, "Y":xr.DataArray()}
      with "X", "Y" as keys, and xr.DataArray as values

    returns:
    -------
    :(xr.DataArray): DataArray with `values` of nan for points outside shapefile
      and coords `Y` = latitude, 'X' = longitude.


    """
    transform = transform_from_latlon(coords[latitude], coords[longitude])
    out_shape = (len(coords[latitude]), len(coords[longitude]))
    raster = features.rasterize(shapes, out_shape=out_shape,
                                fill=fill, transform=transform,
                                dtype=float, **kwargs)
    spatial_coords = {latitude: coords[latitude], longitude: coords[longitude]}
    return xr.DataArray(raster, coords=spatial_coords, dims=(latitude, longitude))

@grassland-curing-cfa
Copy link

Thanks for the great work!

Can you please post an example of how to plot lines for multiple states on a single figure for showing variation along a dimension?

@scepeda78
Copy link

Hi someone has tried to do the mask with a time variable to get the filetered netcdf file ?

@shoyer
Copy link
Author

shoyer commented Aug 4, 2019

Salem (https://salem.readthedocs.io) and Region Mask (https://regionmask.readthedocs.io/) more mature versions of this code snippet.

@wangmengyun1998
Copy link

Thank you for your work1 it helps me a lot, now I get the result that the basin boundary has a missing grid, how to set the code to include the whole basin?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment