Skip to content

Download the Jupyter notebook

Lab 05: Raster Data and Environmental Covariates

BIO597 Spatial Analysis of Biodiversity

This lab introduces raster data using WorldClim climate layers and Maine amphibian occurrences. We will inspect raster structure, clip global rasters to Maine, extract climate values at occurrence locations, and document the predictors we created.

Goals

By the end of this lab, you should be able to:

  • explain how raster cells represent environmental variation
  • inspect raster CRS, resolution, extent, dimensions, and NoData values
  • check whether rasters are aligned
  • clip a raster with a polygon boundary
  • extract raster values at occurrence points
  • combine occurrence and environmental data in one analysis table
  • document the source, units, and ecological meaning of predictors

Data used in this lab

The climate files are WorldClim 2.1 bioclimatic variables at 2.5 arc-minute resolution. They summarize climate during 1970–2000.

WorldClim derives 19 bioclimatic variables from monthly temperature and precipitation. These variables describe annual averages, seasonality, and climatic extremes. See the WorldClim historical climate page and bioclimatic variable definitions.

Today we will use:

  • BIO1: annual mean temperature in degrees Celsius
  • BIO5: maximum temperature of the warmest month in degrees Celsius
  • BIO6: minimum temperature of the coldest month in degrees Celsius
  • BIO12: annual precipitation in millimeters

The Maine state boundary comes from the Maine GeoLibrary. The occurrence records are the same GBIF amphibian data used in earlier exercises.

Raster and vector data

A vector layer stores separate geometries such as points, lines, and polygons. A raster divides space into a regular grid of cells. Each raster cell stores a value for the area it covers.

For these climate rasters, one cell stores one climate estimate. A species occurrence point can be assigned the value of the cell containing or nearest to that point.

0. Install needed packages

rioxarray is a Python library built on GDAL for reading, writing, and analyzing gridded raster data like GeoTIFFs, satellite images, and digital elevation models

pip install rioxarray

1. Import packages

We will use:

  • geopandas for the Maine boundary and occurrence points
  • rioxarray for opening and clipping rasters
  • xarray for selecting raster values at many points
  • pathlib is useful for manipulating filesystem paths
import geopandas as gpd
import rioxarray as rxr
import xarray as xr
from pathlib import Path

2. Load the Maine state boundary

This shapefile contains many polygons because Maine has many coastal islands. Display its size and CRS before simplifying it for clipping.

The authoritative state boundary polygon for Maine mapped at the 1:24,000 scale.

maine_boundary = gpd.read_file("ME_ShapeFiles/Maine_State_Boundary.shp")

print(maine_boundary.shape)
print(maine_boundary.crs)

3. Combine the boundary polygons

dissolve() combines all Maine polygons into one multipart geometry. This makes the clipping step easier to understand and avoids carrying unnecessary attributes.

maine_boundary = maine_boundary.dissolve()

maine_boundary
maine_boundary.explore()

4. Open annual mean temperature

rxr.open_rasterio() opens a GeoTIFF as an xarray.DataArray. The option masked=True converts the raster's NoData values to missing values.

At this point we are only opening the raster. We have not clipped it or extracted any values.

# Create the Path to the bioclim data directory, then below you can
# join the directory to a specific file in a straightforward way
bioclim_path = Path("/home/jovyan/shared-readwrite/bioclim")

bio1 = rxr.open_rasterio(
    bioclim_path / "wc2.1_2.5m_bio_1.tif",
    masked=True,
)

bio1
bio1.squeeze().plot()

5. Inspect raster dimensions

The raster has one band, 4,320 rows, and 8,640 columns. The x and y coordinates identify cell locations.

print("Dimensions:", bio1.dims)
print("Shape:", bio1.shape)
print("Data type:", bio1.dtype)

6. Inspect CRS, resolution, extent, and NoData

These properties determine where the raster is located and how its cells line up.

The resolution is expressed in degrees because this raster uses longitude and latitude. A 2.5 arc-minute cell is 0.04167 degree tall and wide. Its physical width changes with latitude.

print("CRS:", bio1.rio.crs)
print("Resolution:", bio1.rio.resolution())
print("Bounds:", bio1.rio.bounds())
print("NoData:", bio1.rio.nodata)

7. Clip annual mean temperature to Maine

The global raster is much larger than our study area. rio.clip() keeps cells within the Maine boundary.

from_disk=True reads only the required part of the large raster. This avoids loading the full global grid into memory.

bio1_maine = bio1.rio.clip(
    maine_boundary.geometry,
    maine_boundary.crs,
    drop=True,
    from_disk=True,
)

bio1_maine = bio1_maine.squeeze()

8. Compare the global and clipped raster sizes

Clipping changes the extent and number of cells. It does not change the CRS or cell resolution.

print("Global shape:", bio1.shape)
print("Maine shape:", bio1_maine.shape)
print("Maine bounds:", bio1_maine.rio.bounds())
print("Maine resolution:", bio1_maine.rio.resolution())

9. Plot the clipped raster

The plot shows one color for each annual mean temperature value. Blank areas are NoData, including ocean cells and places outside the Maine polygon.

bio1_maine.plot(cmap="coolwarm")

10. Open annual precipitation

BIO12 represents annual precipitation in millimeters. Open it before checking whether it aligns with BIO1.

bio12 = rxr.open_rasterio(
    bioclim_path / "wc2.1_2.5m_bio_12.tif",
    masked=True,
)

11. Check raster alignment

Two rasters are aligned when their CRS, dimensions, resolution, and cell locations agree. Alignment matters because the same row and column should refer to the same place.

These WorldClim files were created as one aligned set.

print("Same CRS:", bio1.rio.crs == bio12.rio.crs)
print("Same shape:", bio1.shape == bio12.shape)
print("Same resolution:", bio1.rio.resolution() == bio12.rio.resolution())
print("Same bounds:", bio1.rio.bounds() == bio12.rio.bounds())

12. Clip annual precipitation

Use the same Maine boundary and the same clipping settings.

bio12_maine = bio12.rio.clip(
    maine_boundary.geometry,
    maine_boundary.crs,
    drop=True,
    from_disk=True,
)

bio12_maine = bio12_maine.squeeze()
bio12_maine.plot(cmap="Blues")

13. Load two temperature-extreme variables

BIO5 and BIO6 describe warmest-month and coldest-month temperature extremes. These may be more biologically meaningful than annual mean temperature for species limited by summer heat or winter cold.

bio5 = rxr.open_rasterio(
    bioclim_path / "wc2.1_2.5m_bio_5.tif",
    masked=True,
)

bio6 = rxr.open_rasterio(
    bioclim_path / "wc2.1_2.5m_bio_6.tif",
    masked=True,
)

14. Clip BIO5 and BIO6

Repeat the same clipping workflow. Repetition is useful here because every predictor should receive the same geographic preprocessing.

bio5_maine = bio5.rio.clip(
    maine_boundary.geometry,
    maine_boundary.crs,
    drop=True,
    from_disk=True,
)

bio5_maine = bio5_maine.squeeze()
bio6_maine = bio6.rio.clip(
    maine_boundary.geometry,
    maine_boundary.crs,
    drop=True,
    from_disk=True,
)

bio6_maine = bio6_maine.squeeze()

15. Confirm the clipped rasters are aligned

The four clipped rasters should have the same shape and coordinates. This allows values from the same cell locations to be compared.

print(bio1_maine.shape)
print(bio5_maine.shape)
print(bio6_maine.shape)
print(bio12_maine.shape)

16. Load the amphibian occurrence records

Read the tab-delimited GBIF file and retain the fields needed for this exercise.

amphibians_gdf = gpd.read_file(
    "../assignments/Amphibians_ME/Amphibians_ME.csv",
    x_possible_names="decimalLongitude",
    y_possible_names="decimalLatitude",
).set_crs("EPSG:4326")

print(amphibians_gdf.shape)
## Remove rows without species labels
amphibians_gdf = amphibians_gdf[amphibians_gdf["species"] != ""]
amphibians_gdf.shape

17. Select only the relevant columns

Just to reduce the amount of clutter we'll subset the columns to keep only the few that are relevant (notice that we are also explicitly keeping the 'geometry' column).

columns_to_keep = [
    "gbifID",
    "species",
    "decimalLongitude",
    "decimalLatitude",
    "year",
    "geometry",
]

amphibians_gdf = amphibians_gdf[columns_to_keep]

amphibians_gdf.head()

18. Verify agreement in CRS for occurences and bio1

The occurrence coordinates and climate rasters both use EPSG:4326. Matching coordinate systems are required before extracting raster values.

print(amphibians_gdf.crs)
print(bio1_maine.rio.crs)

19. Prepare point coordinates for raster extraction

xarray can select values for many coordinates at once. Create one array of occurrence longitudes and one array of occurrence latitudes.

point_x = xr.DataArray(
    amphibians_gdf.geometry.x.to_numpy(),
    dims="record",
)

point_y = xr.DataArray(
    amphibians_gdf.geometry.y.to_numpy(),
    dims="record",
)

20. Extract annual mean temperature

sel() selects raster cells using their coordinates. method="nearest" selects the center of the cell nearest each occurrence coordinate.

Every occurrence assigned to the same raster cell receives the same climate value.

bio1_values = bio1_maine.sel(
    x=point_x,
    y=point_y,
    method="nearest",
)

amphibians_gdf["bio1_mean_temp_c"] = bio1_values
amphibians_gdf.head()

21. Check missing extracted values

An extracted value can be missing when a point is nearest to a NoData cell. This is common near coastlines because raster cells are much larger and less detailed than the state boundary.

Do not automatically replace missing climate values with zero. Zero degrees or zero precipitation would be real environmental values, not missing-data codes.

amphibians_gdf["bio1_mean_temp_c"].isna().value_counts()

For the sake of simplicity we will just remove any cells without environmental data

amphibians_gdf = amphibians_gdf.dropna()

22. Extract the other climate variables

Use the same point coordinates for each aligned raster.

bio5_values = bio5_maine.sel(x=point_x, y=point_y, method="nearest")
amphibians_gdf["bio5_warmest_max_c"] = bio5_values
bio6_values = bio6_maine.sel(x=point_x, y=point_y, method="nearest")
amphibians_gdf["bio6_coldest_min_c"] = bio6_values
bio12_values = bio12_maine.sel(x=point_x, y=point_y, method="nearest")
amphibians_gdf["bio12_annual_precip_mm"] = bio12_values
amphibians_gdf.explore()

23. Create the occurrence-environment table

The geometry column is useful for spatial analysis but is not needed in an ordinary analysis table. Drop it while keeping species, coordinates, year, and environmental covariates.

occurrence_environment = amphibians_gdf.drop(columns="geometry")

occurrence_environment.head()

24. Summarize climate values by species

These are summaries of the environments represented by occurrence records. They are not unbiased estimates of a species' full climatic niche because sampling locations are uneven.

predictor_columns = [
    "bio1_mean_temp_c",
    "bio5_warmest_max_c",
    "bio6_coldest_min_c",
    "bio12_annual_precip_mm",
]

for species, samples in occurrence_environment.groupby("species"):
    print(species, len(samples), "\n", samples[bioclim_labels].mean())

25. Check relationships among predictors

Environmental predictors can contain similar information. A correlation table is a simple first check for redundancy. High correlation does not prove that one variable should be removed, but it should inform predictor selection and interpretation.

occurrence_environment[predictor_columns].corr().round(2)

26. Save the analysis table

Saving the table separates the expensive spatial preparation from later statistical analysis. Missing raster values remain missing in the CSV.

occurrence_environment.to_csv(
    "Lab05_environmental_values.csv",
    index=False,
)

27. Save the geodataframe

Saving your geodataframe to a file allows you to load it back in at a future time without needing to redo all the analysis. geojson is a text-based file format based on JSON used to encode geographic data structures and non-spatial attributes.

amphibians_gdf.to_file("Lab05_amphibians_gdf.geojson")

Discussion questions

  1. How did clipping change raster extent and shape? What properties stayed the same?
  2. Why must rasters and occurrence points use compatible coordinate systems?
  3. Why should missing extracted values remain missing instead of being replaced by zero?
  4. What would be some alternative strategies for dealing with No Data values when extracting environmental data?
  5. Which is more biologically meaningful for an amphibian: annual mean temperature, summer maximum temperature, or winter minimum temperature? Why might the answer differ among species?
  6. What important fine-scale environmental variation is missed by a 2.5 arc-minute climate raster?

Submit your work to GitHub

Run the notebook from top to bottom. Save it, then add, commit, and push the notebook from a terminal.

git add docs/labs/Lab05-RasterData.ipynb
git commit -m "Complete raster data lab"
git push