Monthly precipitation and water balance of ecoregions

Data for this lab.

Download Lab4.zip from the course data archive on Zenodo and unzip it into a folder called data/Lab4/ in your project directory.

Background

Climate governs ecological patterns and processes across scales, from daily variability and local microclimates to millennial change and global conditions. It is hard to overstate the importance of Earth’s climate in governing the distribution of life forms across time and space. Climate can be distilled down to the effects and dynamics of energy and water. At global scales, mean annual temperature and precipitation strongly correlate with the geographic patterns of biomes. At regional and landscape scales, annual and seasonal variability in energy and moisture govern everything from wildlife migrations to wildfire behavior to carbon fluxes. At local scales, energy and moisture can influence daily behavior of wildlife and stomatal conductance of plants.

Whittaker biome diagram showing the relationship between mean annual temperature (x-axis, -30 to 30°C) and mean annual precipitation (y-axis, 0 to 8000 mm) with nine biomes delineated by curved boundaries: Ice and Tundra at cold temperatures with low precipitation, Boreal forest at cold to cool temperatures, Temperate forest and Temperate wet forest at mid temperatures, Grassland/savanna and Desert at warm temperatures with low precipitation, and Tropical dry forest and Tropical wet forest at high temperatures. Gray dots show actual climate data from global weather stations overlaid on the biome boundaries Source: Wikimedia Commons, CC-BY-SA 3.0.

World map showing the global distribution of major terrestrial biomes including tropical rainforest (dark green) in equatorial regions, taiga/boreal forest (dark teal) across northern Canada and Russia, temperate broadleaf forest (yellow-green) in eastern North America, Europe, and East Asia, arid desert and xeric shrubland (brown and red-brown) across the Sahara, Middle East, and central Australia, tropical and subtropical dry forest across sub-Saharan Africa and South America, tundra (light teal) in arctic regions, and temperate steppe and grass savanna across interior continents. Source: Wikimedia Commons, CC-BY-SA 3.0.

Complex feedbacks between atmospheric chemistry, temperature, vegetation productivity and decomposition, rock weathering, and ocean and other geological processes (including long-term carbon storage in carbon-rich rocks like limestone) governed Earth’s climate. Atmospheric carbon strongly influences global temperatures, while temperature, in turn, affects carbon cycling through processes such as decomposition, ocean uptake, and permafrost thaw. Humans are currently enriching the atmosphere with carbon that has been stored in geological layers (e.g., coal, oil, gas) for hundreds of millions of years. The current concentrations of carbon in the atmosphere are higher now (~420 ppm) than in the last 3 to 5 million years. The effects that increasing carbon dioxide concentrations will have on ecosystems, agriculture, and human well-being are the source of much research and concern.

Here, we will focus on the distribution of contemporary patterns of climate and how these patterns shape the distribution of ecosystems and landscapes. Most gridded climate datasets are based on interpolations from weather stations, sometimes aided by remote sensing and physical models (e.g., lapse rates for temperature, orographic effects for precipitation). Because we cannot measure climate everywhere, these products depend on a combination of observations and assumptions.

One widely used climate dataset comes from researchers at Oregon State University called PRISM (Parameter-elevation Relationships on Independent Slopes Model). We will be working with the PRISM climate “normals”, which are the average climate conditions for a 30-year period. For this lab we will ignore inter-annual variability. We will be looking at how average monthly precipitation varies among ecoregions. In mid-latitudes, temperatures always increase in the summer and decrease in the winter. Energy is more limiting during the winter, and organisms have evolved to deal with seasons.

The seasonality of precipitation has a strong effect on patterns of vegetation types. Some places receive most of their precipitation in the winter and some receive most of their precipitation in summer. Some places receive precipitation evenly throughout the year.

Relationships between temperature and precipitation drive “water balance”, which is basically the accounting of water supply and demand. Demand reflects the evaporative force of the atmosphere and is determined by its capacity to absorb water vapor. Supply comes from the delivery (through rain and snow) and storage of water in the soil. Water balance is a good predictor of the types of vegetation that occur across a region (Stephenson 1990). Within landscapes water balance is governed by seasonal precipitation and temperature patterns, as well as influences of topography (as we explored in lab 4 by calculating the heat load index), soil depth, soil texture, elevation, and other factors.

In this lab, you will (1) learn how to manipulate PRISM data in R to create climate summaries for different ecoregions, (2) consider the ecological and socio-economic consequences of variability in climate among different ecoregions, (3) learn about water balance (potential evapotranspiration, actual evapotranspiration, and water deficit) and how it influences patterns of ecosystems, and (4) learn how to make an interactive graph in R.

The last goal for this lab is inspired by von Humboldt’s early innovations in data visualizations: “Graphic delineations of nature, arranged according to systematic views, are not only suited to please the imagination, but may also, when properly considered, indicate the grades of the impressions of which I have spoken.” —Alexander von Humboldt, 1858

How does climate (monthly precipitation) vary among ecoregions in Montana?

We will start out by learning to work with monthly PRISM data. We will create a raster stack of 12 data layers (one for each month), and bring in ecoregion data to summarize monthly patterns of precipitation for selected ecoregions in Montana.

First, we will load the libraries we need. Then, we will direct R to find the monthly precipitation files I downloaded from PRISM. I have set this up so that you don’t have to download the PRISM data, but you can do this directly in R using the prism package and the get_prism_normals() functions. Notice how i use list.files with pattern to tell R what kind of files to look for. I also tell R that I want the full names. This allows me to directly stack the files.

Code
library(terra)
library(tidyverse)
library(sf)
library(patchwork)

# create a full list of the ppt files
# direct R to the folder (not the files)
ppt_files <- list.files("data/Lab4/prism", pattern = "ppt.*\\.bil$", full.names = TRUE, recursive = TRUE)

# Look to see if you have the right files
ppt_files
 [1] "data/Lab4/prism/PRISM_ppt_30yr_normal_4kmM4_01_bil/PRISM_ppt_30yr_normal_4kmM4_01_bil.bil"
 [2] "data/Lab4/prism/PRISM_ppt_30yr_normal_4kmM4_02_bil/PRISM_ppt_30yr_normal_4kmM4_02_bil.bil"
 [3] "data/Lab4/prism/PRISM_ppt_30yr_normal_4kmM4_03_bil/PRISM_ppt_30yr_normal_4kmM4_03_bil.bil"
 [4] "data/Lab4/prism/PRISM_ppt_30yr_normal_4kmM4_04_bil/PRISM_ppt_30yr_normal_4kmM4_04_bil.bil"
 [5] "data/Lab4/prism/PRISM_ppt_30yr_normal_4kmM4_05_bil/PRISM_ppt_30yr_normal_4kmM4_05_bil.bil"
 [6] "data/Lab4/prism/PRISM_ppt_30yr_normal_4kmM4_06_bil/PRISM_ppt_30yr_normal_4kmM4_06_bil.bil"
 [7] "data/Lab4/prism/PRISM_ppt_30yr_normal_4kmM4_07_bil/PRISM_ppt_30yr_normal_4kmM4_07_bil.bil"
 [8] "data/Lab4/prism/PRISM_ppt_30yr_normal_4kmM4_08_bil/PRISM_ppt_30yr_normal_4kmM4_08_bil.bil"
 [9] "data/Lab4/prism/PRISM_ppt_30yr_normal_4kmM4_09_bil/PRISM_ppt_30yr_normal_4kmM4_09_bil.bil"
[10] "data/Lab4/prism/PRISM_ppt_30yr_normal_4kmM4_10_bil/PRISM_ppt_30yr_normal_4kmM4_10_bil.bil"
[11] "data/Lab4/prism/PRISM_ppt_30yr_normal_4kmM4_11_bil/PRISM_ppt_30yr_normal_4kmM4_11_bil.bil"
[12] "data/Lab4/prism/PRISM_ppt_30yr_normal_4kmM4_12_bil/PRISM_ppt_30yr_normal_4kmM4_12_bil.bil"

Make sure there are 12 files listed for each month. Now, we will stack these files up using rast() and plot the stack. Look over the maps of precipitation for each month. Again, these are 30-year “normals” for the years 1991 to 2020.

Code
# you can use rast to create a raster stack of precipitation (ppt)
ppt_stack <- rast(ppt_files)

# plot the stack
# If this works, you will see 12 maps of precipitation for the contiguous U.S., one map for each month.
plot(ppt_stack)

Take a look at the geographic patterns in precipitation and how it varies month-to-month. Looking at the maps is helpful, but let’s graph the patterns and explore how monthly precipitation varies among ecoregions. Please read the background information on EPA’s ecoregions. We’ll bring in ecoregions using vect(), check to see if its coordinate reference system (crs) is the same as our precipitation layers, and project ecoregions to match the crs of the PRISM data.

Code
# load in the ecoregions and check the crs
ecoreg <- vect("data/Lab4/us_eco_l3_state_boundaries.shp")

crs(ecoreg) == crs(ppt_stack)
[1] FALSE
Code
# project ecoregions and check the crs again
ecoreg <- ecoreg %>% project(ppt_stack)

crs(ecoreg) == crs(ppt_stack)
[1] TRUE
Code
# Let's look at the map of ecoregions. 
# If this works, you will see a map of ecoregions in the contiguous U.S.
plot(ecoreg)

We’re going to start by look at precipitation for ecoregions in Montana. We can use a variable in our ecoregion data to subset just the ecoregions in Montana. This is easier if we convert our terra vector data to an sf object. That way we can use tidyverse functions.

Code
# get just the ecoregions for montana, but first let's turn into an sf object
# for easier subsetting using dplyr functions
ecoregSF <- sf::st_as_sf(ecoreg)

# let's look at the names first
names(ecoregSF)
 [1] "US_L3CODE"  "US_L3NAME"  "NA_L3CODE"  "NA_L3NAME"  "NA_L2CODE" 
 [6] "NA_L2NAME"  "NA_L1CODE"  "NA_L1NAME"  "STATE_NAME" "EPA_REGION"
[11] "L3_KEY"     "L2_KEY"     "L1_KEY"     "geometry"  
Code
# Ah! STATE_NAME is a variable. Let's look at what's in that variable
unique(ecoregSF$STATE_NAME)
 [1] "California"           "Oregon"               "Washington"          
 [4] "Idaho"                "Wyoming"              "Nevada"              
 [7] "Utah"                 "Arizona"              "Montana"             
[10] "South Dakota"         "Colorado"             "New Mexico"          
[13] "Texas"                "Kansas"               "Nebraska"            
[16] "Oklahoma"             "Louisiana"            "Arkansas"            
[19] "Missouri"             "Iowa"                 "North Dakota"        
[22] "Alabama"              "Georgia"              "North Carolina"      
[25] "South Carolina"       "Virginia"             "Minnesota"           
[28] "Wisconsin"            "Michigan"             "Illinois"            
[31] "Indiana"              "Ohio"                 "Connecticut"         
[34] "Maine"                "Massachusetts"        "New Hampshire"       
[37] "New Jersey"           "New York"             "Pennsylvania"        
[40] "Vermont"              "Rhode Island"         "Delaware"            
[43] "Maryland"             "District of Columbia" "Florida"             
[46] "Mississippi"          "Tennessee"            "West Virginia"       
[49] "Kentucky"            
Code
# Montana is in there, so let's filter the data for just Montana
MT_ecoSF <- ecoregSF %>% filter(STATE_NAME == "Montana")

# Let's look at Montana ecoregions using two approaches
# If this works, you will see 9 maps of ecoregions in Montana, one map for 9 variables in the data table.
plot(MT_ecoSF)

Code
# If this works, you will see a map of ecoregions in Montana.
ggplot(MT_ecoSF) + geom_sf(aes(fill = NA_L3NAME)) +
  theme_void()

Those colors are pretty bad. Here’s how we can create a custom set of colors for plotting.

Code
# OMG, those colors! Let's edit those.
map_cols <- c(
  "Canadian Rockies"                 = "darkseagreen",
  "Columbia Mountains/Northern Rockies" = "darkgreen",
  "Idaho Batholith"                  = "seagreen",
  "Middle Rockies"                   = "darkseagreen4",
  "Northwestern Glaciated Plains"    = "wheat4",
  "Northwestern Great Plains"        = "darkkhaki",
  "Wyoming Basin"                    = "chocolate")

# Let's try that again using scale_fill_manual to set the colors to those above
# This will come in handy later.
# If this works, you will see a map of ecoregions in Montana with a better color palette. 
ggplot(MT_ecoSF) + geom_sf(aes(fill = NA_L3NAME)) +
  scale_fill_manual(values = map_cols) +
  theme_void()

Now that we have the ecoregions for Montana brought in, we can use terra::extract to summarize the precipitation data for each ecoregion. We’ll need to join names from our dataset with a cbind. This is clunky, but it should work so that you can use the ecoregion names. After we do the extract and get the ecoregion names with cbind, we will look at the names of our data and manually edit those. Then, take a look at your dataframe with View.

Code
# Here we are going to extract the ppt values for each ecoregions and calculate 
# the  mean for each ecoregion.
# It is nice that you can do this all at once using a raster stack
MTeco_ppt <- ppt_stack %>% terra::extract(MT_ecoSF, fun = "mean", na.rm = TRUE)

# one problem is that we lost our ecoregion names. We have to join these back 
# to the dataframe. We can use cbind (column bind) for this
MTeco_ppt <- cbind(MTeco_ppt = MT_ecoSF$US_L3NAME, MTeco_ppt)

# Look at the names of this new dataframe. 
names(MTeco_ppt)
 [1] "MTeco_ppt"                          "ID"                                
 [3] "PRISM_ppt_30yr_normal_4kmM4_01_bil" "PRISM_ppt_30yr_normal_4kmM4_02_bil"
 [5] "PRISM_ppt_30yr_normal_4kmM4_03_bil" "PRISM_ppt_30yr_normal_4kmM4_04_bil"
 [7] "PRISM_ppt_30yr_normal_4kmM4_05_bil" "PRISM_ppt_30yr_normal_4kmM4_06_bil"
 [9] "PRISM_ppt_30yr_normal_4kmM4_07_bil" "PRISM_ppt_30yr_normal_4kmM4_08_bil"
[11] "PRISM_ppt_30yr_normal_4kmM4_09_bil" "PRISM_ppt_30yr_normal_4kmM4_10_bil"
[13] "PRISM_ppt_30yr_normal_4kmM4_11_bil" "PRISM_ppt_30yr_normal_4kmM4_12_bil"
Code
# Notice that the filenames are the column names. 
# Let's improve the names of the columns
names(MTeco_ppt) <- c("ecoregion", "ID", "Jan", "Feb", "Mar", "Apr", "May", 
                      "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")

# Let's look at what we created!
View(MTeco_ppt)

That is a nice-looking dataframe, but it is in the “wide” format. We’ll have more flexibility to work with it if we make it a “long” format.

Code
# That's pretty awesome, but we'll have more flexibility to work with the data
# if we turn it into a "long" dataframe. 
MTppt_long <- MTeco_ppt  %>% pivot_longer(cols = Jan:Dec, names_to = "month", 
                                          values_to = "ppt_mm")

# Look at the new "long" dataframe
View(MTppt_long)

Now, let’s plot precipitation for each month for one ecoregion, closely look at the data again, and make some adjustments (turn month into an ordered factor).

Code
# Let's try to plot this with month on the x-axis and 
# precipitation (ppt) is on the y.
# Let's start with just one ecoregion. We'll pull this one out using "filter".
# If this works, you will see a line graph showing precipitation for each month in the ecoregion called the "Canadian Rockies". However, months are alphabetically arranged.  
MTppt_long %>% filter(ecoregion == "Canadian Rockies") %>% 
  ggplot() + geom_line(aes(x = month, y = ppt_mm, group = 1)) + theme_bw()

Code
# R has alphabetically arranged month! We need to tell R that month is a factor.
MTppt_long$month <- factor(MTppt_long$month, 
                           levels = c("Jan","Feb","Mar","Apr", "May","Jun",
                          "Jul","Aug","Sep","Oct","Nov","Dec"), ordered = TRUE)

# R has a built in sequence of month abbreviations called month.abb,
# run this
month.abb
 [1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
Code
# so you can also do this 
MTppt_long$month <- factor(MTppt_long$month, levels = month.abb, ordered = TRUE)

# Now, replot your data.
# If this works, you will see a line graph showing precipitation for each month in the ecoregion called the "Canadian Rockies". However, months are arranged by chronologically.
MTppt_long %>% filter(ecoregion == "Canadian Rockies") %>% 
  ggplot() + geom_line(aes(x = month, y = ppt_mm, group = 1)) + 
  xlab("Month") + ylab("Precipitation (mm)") +
  theme_bw() 

Now we took care of the months, but we need to do a little more cleaning

Code
# Look at the data, MTppt_long
View(MTppt_long)

Notice that the Middle Rockies is listed multiple times. Why?

Check the map of ecoregions for a clue. Each polygon classified as the Middle Rockies is a unique row. The island ranges in central Montana are all classified as “Middle Rockies”. We will take care of this by averaging all the values for unique ecoregion and month combinations.

Code
# We first have to "group_by" ecoregions and month
# Then, we sumarize and calculate the mean of ppt_mm, ignoring NAs
# groups = "drop" doesn't really do anything here, but is really important
# if you do other analysis with the dataframe

MTppt_long_2 <- MTppt_long %>% group_by(ecoregion, month) %>%
  summarise(ppt_mm = mean(ppt_mm, na.rm = TRUE), .groups = "drop")

# Now, look at the data
View(MTppt_long_2)

Now, we have one ecoregion and month combination. Let’s plot precipitation (y axis) by month (x axis). Let’s make each ecoregion its own line using the color option placed within the parentheses of the aes().

Code
# let's plot monthly precipitation for each ecoregion.
# This plot will show precipitation on the y-axis and month on the x-axis for 7 ecoregions in Montana. Each line represents data for an ecoregion and are colored using default colors. 
ggplot(MTppt_long_2, aes(x = month, y = ppt_mm, group = ecoregion, color = ecoregion)) +    
  geom_line(linewidth = 1) +
  geom_point() +  
  xlab("Month") +  ylab("Precipitation (mm)") +
  theme_bw()

Those colors again! We can use the colors we created above with scale_color_manual().

Code
# This plot will show precipitation on the y-axis and month on the x-axis for 7 ecoregions in Montana. Each line represents data for an ecoregion and are colored using custom colors. 
ggplot(MTppt_long_2, aes(x = month, y = ppt_mm, group = ecoregion, color = ecoregion)) +    
  geom_line(linewidth = 1) +
  geom_point() +  
  scale_color_manual(values = map_cols) +
  xlab("Month") +  ylab("Precipitation (mm)") +
  theme_bw()

Those colors are better. Look at the patterns of precipitation for different ecoregions of Montana. Sometimes having multiple lines on one graph is helpful, but it can also be confusing. Let’s try a different approach and split the data so that each ecoregion gets its own graph using facet_wrap. Then, we’ll make a nice map and combine them all using formatting from the patchwork library in a color-coordinated way.

Code
# That's still kind of messy. Let's 'facet' by ecoregions.
# The figure below showing precipitation on the y-axis and month on the x-axis with 7 panels, one for each ecoregion in Montana. A map of Montana ecoregions is in the lower right. 
plot <- ggplot(MTppt_long_2, aes(x = month, y = ppt_mm, group = ecoregion, color = ecoregion)) +    
  geom_line(linewidth = 1) +
  geom_point() +  
  facet_wrap(~ecoregion) +
  xlab("Month") +  ylab("Precipitation (mm)") +
  theme_bw() + 
  scale_color_manual(values = map_cols) +
  theme(legend.position = "none")  

map <- ggplot(MT_ecoSF) + geom_sf(aes(fill = NA_L3NAME)) +
  scale_fill_manual(values = map_cols) +
  theme_void() + 
  theme(legend.position = "none")  

# this formatting is from patchwork
plot + inset_element(map,
  left   = 0.3,  # distance from left edge of `plot` (0–1)
  bottom = 0,  # distance from bottom
  right  = 1,  # distance from left edge to right edge of inset
  top    = 0.3)   # distance from bottom to top of inset

TASK 1.

Choose another state and plot the monthly patterns of precipitation for ecoregions in the state. Describe the differences in relation to the vegetation and land use patterns of ecoregions with the state you chose.

The effect of water balance on the distribution of broad ecoregions across the U.S.

The concept of water balance focuses on supply and demand of water given the availability of moisture and energy. Here, we will focus on three interrelated measures important for understanding water balance: potential evapotranspiration (PET), actual evapotranspiration (AET), and water deficit. PET is the atmosphere’s “demand” for water, driven by temperature, wind, and humidity. Warmer areas will have higher PET, because the atmosphere can absorb more water vapor. AET is the realized evaporation and transpiration from soils and plants. It is constrained by both the atmospheric demand (PET) and by the availability of water in soils. When PET is greater than AET, water deficit occurs, creating drought stress for vegetation. Therefore, PET – AET = deficit. When considered throughout the year for mid- and high-latitudes, PET increases with increasing temperature with summer. PET then decreases in winter, of course. AET will depend on temperature but also the amount of moisture stored in soils. If precipitation isn’t maintained during the summer months, plants will experience water deficit that some species are better equipped to deal with. These patterns explain the distribution of vegetation types throughout North America and patterns of relative species abundance within communities (e.g., see discussion in Urban 2023 chapter 1 on Ponderosa pine vs. Jeffrey pine in the Sierra Nevada Mountains).

Consider that some places can receive the same amount of precipitation that is delivered in very different times of the year. Why are forests of the Pacific Northwest (PNW) dominated by needle-leaved conifers, but forests of much of the eastern U.S. dominated by broad-leafed hardwoods (angiosperms)? These broad patterns are partly due to the strong seasonality of precipitation in the PNW, where most precipitation falls during the winter months, and relatively little rain falls in the summer months. The eastern U.S., in contrast, receives relatively even distribution of rain throughout the year. Needle-leaved conifers are better equipped to deal with the seasonal drought (i.e., water deficit) than broad-leaved hardwoods. Conifers of the PNW are also evergreen allowing them to photosynthesize in the mild wet winters.

Nate Stephenson famously described these patterns in 1990 and argued that accounting for water balance helped explain the distribution of vegetation types across North America.

Stephenson 1990 Figure 2 showing the distribution of major North American plant formations along gradients of annual actual evapotranspiration (y-axis, 0-1500mm) and annual water deficit (x-axis, 0-3000mm). Tundra and Coniferous Forest occur at low AET and low deficit, Deciduous Forest and Southern Mixed Forest at high AET and low deficit, Tallgrass and Shortgrass Prairie at intermediate AET and moderate deficit, and Cold Desert, Shrub, and Warm Desert at low AET and high deficit. Adapted from Stephenson 1990, The American Naturalist 135(5):649–670. http://www.jstor.org/stable/2462028

We will investigate how ecoregions are distributed with respect to AET and water deficit using data from Dobrowski et al. (2013) to recreate the plot of Stephenson (1990). We will see that some ecosystems (using ecoregion as a very coarse proxy) are water limited and some are energy limited.  

First, bring in the AET and deficit data. The data represent the average for 110 years (1900 to 2009) estimated at each pixel based on PRISM data and various other ancillary datasets used to relate temperature and precipitation to potential evapotranspiration (PET), actual transpiration (AET), and water deficit.

Code
aet_mean <- rast("data/Lab4/aet_mean.tif")

def_mean <- rast("data/Lab4/def_mean.tif")

Because the data available only represent AET and deficit, we have to calculate PET. Because deficit = PET - AET, we can calculate PET using AET + deficit. This is easy in R. This will add the values for each pixel for the layers together. Then, plot all 3 values (PET, AET, and deficit). Finally, we will stack all 3 of these datasets into one R object.

Code
pet_mean <- aet_mean + def_mean # calculate PET
par(mfrow = c(3, 1)) # set graphing parameters (3 rows and 1 column of plots) 

# If this works, you will see 3 maps, one for potential evapotransportation, actual evapotranspiration, and one for water deficit for the contiguous U.S.
plot(pet_mean)
plot(aet_mean)
plot(def_mean)

Code
# dev.off() # Uncomment this and turn the device off after you run those plots.
pet_aet_def <- c(pet_mean, aet_mean, def_mean) # stack those up!

We are going to summarize these values for different ecoregions in the contiguous United States. Because ecoregions are hierarchical (i.e., level 4 ecoregions are nested within level 3, which are nested within level 2, which are nested within level 1), we will bring in the coarsest version (level 1) and a more detailed version (level 3) and turn both into raster datasets using rasterize, telling R to assign the pixels the field “NA_L1NAME” (level 1 ecoregions) or “NA_L3NAME” (level 3 ecoregions). But, first, we’ll need to project the ecoregions so that they match the crs of the pet_aet_def raster stack.

Code
ecoreg <- vect("data/Lab4/us_eco_l3_state_boundaries.shp")

ecoregPRJ <- project(ecoreg, pet_aet_def)
ecoregL1Rast <- rasterize(ecoregPRJ, pet_aet_def, field = "NA_L1NAME")
ecoregL3Rast <- rasterize(ecoregPRJ, pet_aet_def, field = "NA_L3NAME")

# Let's plot the level 1 ecoregions.
# If this works, you will see a map of ecoregions for the contiguous U.S.
plot(ecoregL1Rast)

Code
# Those colors aren't great for ecoregions. Let's assign colors like this:
eco_cols <- c(
  "EASTERN TEMPERATE FORESTS"      = "#228B22",  
  "GREAT PLAINS"                   = "#DAA520",  
  "MARINE WEST COAST FOREST"       = "#2E8B57",  
  "MEDITERRANEAN CALIFORNIA"       = "#D2691E",  
  "NORTH AMERICAN DESERTS"         = "#DEB887",  
  "NORTHERN FORESTS"               = "#1C5D99",  
  "NORTHWESTERN FORESTED MOUNTAINS"= "#556B2F",  
  "SOUTHERN SEMI-ARID HIGHLANDS"   = "#CD5C5C",  
  "TEMPERATE SIERRAS"              = "#8B4513",  
  "TROPICAL WET FORESTS"           = "#006400")

# If this works, you will see a map of ecoregions for the contiguous U.S. using colors described above.
plot(ecoregL1Rast, col = eco_cols)

Because climate influences vegetation productivity, we will bring in a dataset on net primary productivity (NPP), which is basically the total photosynthesis of plants minus the respiration of plants. This data does not include heterotrophic respiration, decomposition, or loss of carbon by fire, etc. However, estimates of NPP can be a useful response and covariate representing plant growth. We will bring these data in and make sure it matches the resolution and extent of our pet_aet_def stack using resample with the bilinear interpolation method.

Code
npp <- rast("data/Lab4/NPP.tif")

nppPRJ <- resample(npp, pet_aet_def, method = "bilinear")

# If this works, you will see a map of net primary productivity for the contiguous U.S.
plot(nppPRJ,
     col = colorRampPalette(c("khaki", "forestgreen", "darkgreen"))(30))

We will now stack all of our data including PET, AET, deficit, NPP, and the ecoregions. NPP data need to be divided by 10,000 to reflect the units (kilograms of carbon per m2 per year), and we’ll do that in this step to take care of it. After we stack the data, we will rename the columns to something simple and meaningful and look at the maps.

Code
waterStack <- c(pet_mean, aet_mean, def_mean, nppPRJ/10000, ecoregL1Rast, ecoregL3Rast)

names(waterStack) <- c("pet", "aet", "def", "npp", "eco1", "eco3")

# If this works, you will see 6 maps of the contiguous U.S., PET, AET, water deficit, NPP, level 1 ecoregions, and level 3 ecoregions.
plot(waterStack)

Now, let’s try to recreate the figure of Stephenson (1990) who plotted AET (y-axis) against deficit (x-axis). We will first turn our stack into a data frame with as.data.frame including the coordinates with (xy = TRUE). We will speed things up by taking a random sample of 5,000 locations with sample_n(5000). I know that some of the data probably has NAs, so let’s drop those with drop. Finally, let’s create a simple plot where deficit is on the x-axis, AET is on the y-axis.

Code
# If this works, you will see a scatter plot showing AET on the y-axis and water deficit on the x-axis. The cloud of points form a "triangle" with no observations in the upper right of the plot. 
waterStack %>% as.data.frame(xy = TRUE) %>% sample_n(5000) %>% drop_na() %>%  
  ggplot(aes(x = def, y = aet)) +
  geom_point()

That’s a nice plot, but let’s tweak some things to improve it. We will adjust transparency of the points using alpha = 0.25 and make them a little larger with size = 3. Then, we’ll use theme_bw() to get rid of the default grey background of ggplot. We’ll also add more meaningful axis labels using xlab and ylab.

Code
# If this works, you will see a scatter plot showing AET on the y-axis and water deficit on the x-axis. The cloud of points form a "triangle" with no observations in the upper right of the plot. The symbols are slightly transparent.

waterStack %>% as.data.frame(xy = TRUE) %>% sample_n(5000) %>% drop_na() %>%  
  ggplot(aes(x = def, y = aet)) +
  geom_point(alpha = 0.25, size = 3) + theme_bw() +
  xlab("Deficit (mm)") + ylab("AET (mm)")

That’s starting to look better, but it is sometimes hard for me to get my head around this plot when we don’t include PET. By plotting PET as a third dimension of the plot (in our case, we will make the size of the points reflect PET) we will better see patterns in the data. We can do this by setting size = pet in the aes parameter.

Code
# If this works, you will see a scatter plot showing AET on the y-axis and water deficit on the x-axis. The cloud of points form a "triangle" with no observations in the upper right of the plot. The symbols are slightly transparent and their sizes are proportional to PET.

waterStack %>% as.data.frame(xy = TRUE) %>% sample_n(5000) %>% drop_na() %>%  
  ggplot(aes(x = def, y = aet, size = pet)) +
  geom_point(alpha = 0.25) + theme_bw() +
  xlab("Deficit (mm)") + ylab("AET (mm)") 

Notice how small the points are in the lower left part of this plot. The small size represent low PET (and, of course low AET and deficit given their position). This is helpful, but it might be even more useful to adjust the size and the color of the points to more conspicuously display PET in two dimensions (size and color).

Code
# If this works, you will see a scatterplot showing AET on the y-axis and water deficit on the x-axis. The cloud of points form a "triangle" with no observations in the upper right of the plot. The symbols are slightly transparent and their colors are assigned based on PET. 

waterStack %>% as.data.frame(xy = TRUE) %>% sample_n(5000) %>% drop_na() %>%  
  ggplot(aes(x = def, y = aet, size = pet, color = pet)) +
  geom_point(alpha = 0.5) + theme_bw() +
  scale_color_viridis_c(option = "plasma") +
  xlab("Deficit (mm)") + ylab("AET (mm)") 

Now the patterns of PET are more conspicuous. In fact, here’s what Stephenson (1990) said:

See if you can follow him and compare your graph to the geography he mentions in the passage above.

Now, look at the plot of “plant formations” from Stephenson (1990) included above and see which kinds of vegetation are characterized by these conditions. What vegetation is plotted in the lower right by Stephenson? What are the water balance conditions of regions dominated by this biome?

PET, AET, and deficit not only influence the distributions of biomes, but Stephenson (1990) describes a couple of predictions concerning water balance and net primary productivity:

Let’s evaluate these predictions using an independent estimate of NPP. Because we already included NPP in our raster stack, this is very easy. All we need to do is change the variable on the y-axis and the label (of course!).

Code
# If this works, you will see a scatter plot where NPP is on the y-axis and water deficit is on the x-axis. Symbols are sized proportional to PET with colors corresponding to PET. 
waterStack %>% as.data.frame(xy = TRUE) %>% sample_n(5000) %>% drop_na() %>%  
  ggplot(aes(x = def, y = npp, size = pet, color = pet)) +
  geom_point(alpha = 0.5) + theme_bw() +
  scale_color_viridis_c(option = "plasma") +
  xlab("Deficit (mm)") + ylab("NPP (kg C/m²/yr)") 

We can also investigate the relationship between NPP and AET.

Code
# If this works, you will see a scatter plot where NPP is on the y-axis and AET is on the x-axis. Symbols are sized proportional to water deficit with colors corresponding to PET. The scatter of points generally positive.  

waterStack %>% as.data.frame(xy = TRUE) %>% sample_n(5000) %>% drop_na() %>%  
  ggplot(aes(x = aet, y = npp, size = def, color = pet)) +
  geom_point(alpha = 0.5) + theme_bw() +
  scale_color_viridis_c(option = "plasma") +
  xlab("AET (mm)") + ylab("NPP (kg C/m²/yr)") 

Now, that we’ve looked into a few relationships between water balance (PET, AET, and deficit) and NPP, let’s see how ecoregions “map” onto these relationships. Because we stacked ecoregions, we can easily just tell R to color the symbols per the ecoregion names (i.e., color = eco1),

Code
# If this works, you will see a scatter plot where AET is on the y-axis and water deficit is on the x-axis. Symbols are color coded by 10 level 1 ecoregions for the contiguous U.S. 
waterStack %>% as.data.frame(xy = TRUE) %>% sample_n(5000) %>% drop_na() %>%  
  ggplot(aes(x = def, y = aet, color = eco1)) +
  geom_point(alpha = 0.25, size = 3) + theme_bw() +
  xlab("Deficit (mm)") + ylab("AET (mm)") +
  scale_color_manual(values = eco_cols)

Compare that plot to the plot that Stephenson (1990) created. What is similar? What is different? Why?

I liked how we adjusted the size of these points according to their PET values. This isn’t very conspicuous, but it helped understand the multivariate characteristics. Let’s add that back in using size = pet while keeping the colors associated with the ecoregions.

Code
# If this works, you will see a scatter plot where AET is on the y-axis and water deficit is on the x-axis. Symbols are sized proportional to PET and color coded by 10 level 1 ecoregions for the contiguous U.S.

waterStack %>% as.data.frame(xy = TRUE) %>% sample_n(5000) %>% drop_na() %>%  
  ggplot(aes(x = def, y = aet, color = eco1, size = pet)) +
  geom_point(alpha = 0.25) + theme_bw() +
  xlab("Deficit (mm)") + ylab("AET (mm)") +
  scale_color_manual(values = eco_cols)

That looks okay, but let’s make some adjustments to the legends.

Code
# If this works, you will see a scatter plot where AET is on the y-axis and water deficit is on the x-axis. Symbols are sized proportional to PET and color coded by 10 level 1 ecoregions for the contiguous U.S.
waterStack %>% as.data.frame(xy = TRUE) %>% sample_n(5000) %>% drop_na() %>%  
  ggplot(aes(x = def, y = aet, color = eco1, size = pet)) +
  geom_point(alpha = 0.25) +
  scale_color_manual(values = eco_cols, guide = "none") +  # turn off eco legend
  scale_size_continuous(name = "PET (mm)") +               # keep PET legend
  theme_bw() +
  xlab("Deficit (mm)") + ylab("AET (mm)") +
  theme(
    legend.position = c(0.95, 0.95),   # relative coords inside panel
    legend.justification = c("right", "top")) 

That’s a pretty nice representation of patterns described in Stephenson (1990), but there’s so much overlap. Let’s facet by ecoregion to plot each ecoregion on its own plot.

Code
# If this works, you will see 10 scatter plots where AET is on the y-axis and water deficit is on the x-axis. The 10 scatter plots represent data for 10 level 1 ecoregion. 

waterStack %>% as.data.frame(xy = TRUE) %>% sample_n(5000) %>% drop_na() %>%  
  ggplot(aes(x = def, y = aet, color = eco1, size = pet)) +
  geom_point(alpha = 0.25) +
  scale_color_manual(values = eco_cols, guide = "none") +  # turn off eco legend
  scale_size_continuous(name = "PET (mm)") +               # keep PET legend
  facet_wrap(~eco1) +
  theme_bw() +
  xlab("Deficit (mm)") + ylab("AET (mm)") +
  theme(
    legend.position = c(0.95, 0.3),   # relative coords inside panel
    legend.justification = c("right", "top")) 

There’s still some work we could do here like reducing the size of the facet titles (the ecoregions), but let’s call it good for now.

One thing that is very helpful in data visualization is making your plots interactive. There are various packages that allow you to do this (plotly and ggiraph). Here, we’ll use ggiraph to make our scatter plot interactive. Make sure to install ggiraph, load the library, and then make the plot and name it p (or whatever).

Code
#install.packages(ggiraph)
library(ggiraph)

p <- waterStack %>% as.data.frame(xy = TRUE) %>% sample_n(5000) %>% 
  drop_na() %>%  
  ggplot(aes(x = def, y = aet, 
             color = eco1, size = pet,
             tooltip = eco1, data_id = eco1)) +   # add tooltip & id
  geom_point_interactive(alpha = 0.25) +
  scale_color_manual(values = eco_cols, guide = "none") +  # no eco legend
  scale_size_continuous(name = "PET (mm)") +               # keep PET legend
  theme_bw() +
  xlab("Deficit (mm)") +  ylab("AET (mm)") +
  theme(
    legend.position = c(0.95, 0.95),
    legend.justification = c("right", "top"))

# If this works, you will see an interactive scatter plots where AET is on the y-axis and water deficit is on the x-axis. You can hover your mouse over a symbol to see which ecoregion the colors represent.  

if (knitr::is_html_output()) {
  girafe(
    ggobj = p,
    options = list(
      opts_hover(css = "stroke:black;stroke-width:1.5px;fill-opacity:1;"),
      opts_hover_inv(css = "opacity:0.4;")))
} else {
  print(p)
}

TASK 2.

You can take this task in multiple directions. Feel free to look at patterns using the level 3 ecoregions WITHIN a level 1 ecoregion. Hint: you can use dplyr::filter(eco1 == "NAME") and use color = eco3 to investigate patterns of PET, AET, and deficit for level 3 ecoregions within your chosen ecoregion. Note, that you will need to replace “NAME” in my hint above with the correct name of the level 1 ecoregion.

You may also choose to investigate relationships in NPP, PET, AET, and deficit by ecoregions in whatever way you chose. In other words, use the base code here to plot relationships in other ways.

Alternatively, pull all the data into ArcGIS Pro, explore the patterns in relationship to aerial imagery, and make some observations. See screenshot below.

For any of these tasks, describe patterns in water balance. Which ecoregions are more energy limited? Which are more water limited? Which are most productive? What are the effects of these patterns on agriculture, ecosystem functions, etc.?

ArcGIS Pro map view showing two side-by-side map frames of the same geographic area in Montana, Wyoming, and Idaho. The left frame shows a World Imagery basemap with ecoregion boundaries overlaid. The right frame shows actual evapotranspiration (AET) as a raster layer with a yellow-to-blue color ramp, where blue indicates higher AET in mountainous areas. The Symbology pane on the right shows the AET raster is displayed using histogram equalize stretch.

Data source(s)

Monthly precipitation normals (prism/ folder): PRISM Climate Group, Oregon State University.

Net primary productivity (NPP.tif): Numerical Terradynamic Simulation Group, University of Montana.

Actual evapotranspiration and water deficit (aet_mean.tif, def_mean.tif): AdaptWest Water Balance data.

Ecoregions, level 3, with state boundaries (us_eco_l3_state_boundaries.shp): EPA.