The shapes of mountains, slope, and topographic aspect
Data for this lab.
Download Lab3.zip from the course data archive on Zenodo and unzip it into a folder called data/Lab3/ in your project directory.
Elevation and topography
Elevation, topography, and soils all govern patterns of landscapes and set the stage for physical and biological processes. Variability in topography influences physical processes like erosion, disturbance processes like fire, and micro-climatic conditions and associated distributions of resource availability like soil moisture. Elevation, topography, and soils form the landscape “template” upon which other physical and biological processes operate to give rise to landscape patterns of vegetation.
A shaded relief map shows the topographic patterns of the northern Greater Yellowstone Ecosystem and associated patterns in land cover.
In this lab, we are going to (1) examine the “shapes of mountains” in Montana and discuss the implications of these patterns on mountain ecosystems, and (2) use a digital elevation model (i.e., a raster map of elevation) to calculate various metrics like slope, aspect, topographic position, and a heat load index. Finally, we will explore interactions between elevation, heat load index, and other ecological patterns.
Exercise 1. Shapes of mountains in Montana
Elevation (i.e., the vertical height of a landform or location) is associated with numerous factors - most notably temperature - influencing patterns of ecosystems. Temperature tends to decrease with increasing elevation. Temperature tends to decrease with increasing latitude too, of course. Ecosystems are therefore distributed such that an observer climbing a mountain can “sample” vegetation types observed at higher latitudes.
The role mountains play in facilitating or impeding species migrations during periods of historical changes in climate is the topic of some very interesting research. Likewise, research on the effects of future climate change on mountain ecosystems and their species has resulted in some fascinating insights. The general prediction is that species will move upslope to track increases in temperature. Using future climate predictions, some scientists have documented a potential loss of climate conditions at the tops of mountains. Other ecologists have measured the change in the geographic area of climate conditions to predict local extinctions of species. This work relies on a simple species-area relationship to predict loss in species with the loss in area as climate shifts up slopes. Notice the shape of the mountain in this classic example. There’s more land area in the lower elevation range and less area as you increase elevation.
Adapted from McDonald & Brown 1992, Conservation Biology 6(3):409–415. https://doi.org/10.1046/j.1523-1739.1992.06030409.x
Paul Elsen and Morgan Tingley realized that not all mountains are shaped like this. They used data from a digital elevation model (DEM, a raster map where each pixel represents the elevation) to investigate the shapes of mountains simply by plotting histograms of elevation among mountain ranges around the planet. They used some summary statistics of the shape of each histogram to classify the shapes of mountains. Elsen and Tingley suggested that these different shapes of mountains warranted a more complicated view of how climate change may put mountain species at risk of losing habitat. Some mountains have more area at higher elevation providing more opportunities for species to find new habitat as temperatures increase.
From Elsen & Tingley 2015, Nature Climate Change 5. https://doi.org/10.1038/nclimate2656. Used with permission from the publisher under license 6332060890717.
We are going to be be looking at the shapes of mountain ranges in Montana using the first step in Elsen et al.’s approach.
Elevation and mountains
First, we will load libraries and bring in a DEM and shapefile of mountain ranges in Montana. You can read more about the datasets in the links.
Code
library(terra)library(sf)library(tidyverse)elev <-rast("data/Lab3/MT_dem.tif")mtns <-vect("data/Lab3/Mtn_Ranges.shp")# We need to project the mountains to the same crs as the elevation datamtnsPRJ <-project(mtns, elev)# Now, plot the maps of elevation and the Montana mountains # If this works, you will see a map of Montana elevation, showing the mountains in the west and the plains in the east. plot(elev)
Code
# If this works, you will see a map of Montana mountain ranges.plot(mtnsPRJ) # if this returns an error, remove "add = T" and rerun
We want to use tidyverse function to subset the mountains data (i.e., select only one mountain range). This works best if we turn the terra vector into an special features (sf) object. We’ll do that, then look at the names of the variables in the attribute table. “NAME” is one of the attributes, which stores the name of each mountain range. We’ll also look at all the mountain ranges in the dataset using unique().
Code
# turn the terra vector into a sf objectmtns_sf <-st_as_sf(mtnsPRJ)# what are the names of the variables in the attribute table?names(mtns_sf)
Now, we will use the filter function in dplyr, which is part of the tidyverse to select the Gallatin Range, which is just south of Bozeman. Then, plot the boundaries of this mountain range.
Code
gallatin_sf <- mtns_sf %>%filter(NAME =="Gallatin Range")# If this works, you will see 6 maps of the Gallatin Range, one for each variable in the accompanying data table.plot(gallatin_sf)
Next, we will use this new sf object as a mask to extract the DEM data for only the Gallatin Range. We add trim() to remove all the blank space left over after essentially clipping the data to the Gallatin Range. You can try removing %>% trim(), running that line, and plotting to see what trim() does. It can be handy.
# If this works, you will see a map of elevation for the Gallatin Range.plot(gallatin_elev)
One of the core parts of Elsen and Tingley’s method is to plot and examine the histograms of elevation for mountain ranges. We will do this with hist(), which plots a traditional histogram where the number of observations (pixels) within each bin (a range of values) is plotted. We will also use density() to plot a smoothed histogram (a kernel density plot).
Code
# If these lines of code work, you will see a histogram and smoothed histogram (kernel density plot) of elevation values revealing elevation to be rather normally distributed.hist(gallatin_elev)
Code
density(gallatin_elev)
One way Elsen and Tingley plotted the land area for different elevations was to create a two-sided kernel density plot. You can do this in R using violin plots, which are becoming more common in the scientific literature (but, beware, some people do not like these plots!).
Code
# This should produce a "violin plot" of elevation for the Gallatin Range.gallatin_elev %>%as.data.frame() %>%ggplot(aes(x ="Gallatin Range", y = MT_dem)) +geom_violin(scale ="width", fill ="grey") +labs(x ="Mountain Range", y ="Elevation (m)") +theme_bw()
What do you notice about the “shape” of the Gallatin Range in relation to the different categories of mountain shapes that Elsen and Tingley recognized? We won’t use their method to classify mountain ranges into the categories (diamond, pyramid, inverse pyramid, hourglass). Instead, just “eye-ball” the shape and list the shape you think it bests matches.
TASK 1.
Choose 2 other mountain ranges in Montana, follow the steps above to extract the data to the mountain ranges of your choice, plot the histogram and density plot of elevation, and describe which shape you think it most matches of the four recognized by Elsen and Tingley. Describe the possible implications of these shapes. Write up an abstract following Landscape Ecology abstract format.
OPTIONAL. Histograms as map legends.
I have found that histograms serve as excellent map legends. This is a very informative way to visualize the spatial patterns and statistical distribution simultaneously and provides transparency in how colors are assigned given the range of values in a raster dataset. In the case at hand, mapping elevation alongside the histogram in a color-coordinated way can provide a really information-rich visualization of data.
I start by creating a color ramp that attempts to match Elsen and Tingley. I then turn the DEM raster into a dataframe so that I can plot it using ggplot. I then use the density function to pull out values from the kernel density estimation for plotting in ggplot. Finally, I put the map and histogram together using the patchwork library.
Code
## OPTIONAL!# This will produce a map and smoothed histogram of elevation for the Gallatin Range.# Custom ramp based on your barpaul_colors <-c("#0B2C7A", "#20998F", "#00DB00", "#FFFF00", "#EDA113", "#C2523C")paul_ramp <-colorRampPalette(paul_colors)(100)# Extract elevation values from DEM (sample if very large)elev_df <-as.data.frame(gallatin_elev, xy =TRUE, na.rm =TRUE)names(elev_df) <-c("x", "y", "elevation")map <- elev_df %>%ggplot() +geom_tile(aes(x = x, y = y, fill = elevation)) +scale_fill_gradientn(colors = paul_ramp) +coord_fixed() +theme_void() +theme(legend.position ="none")# Compute density of elevationsdens <-density(elev_df$elevation, na.rm =TRUE, n =2^12)# Convert to a dataframe for ggplotdens_df <-data.frame(elevation = dens$x,density = dens$y)hist <-ggplot(dens_df, aes(x = elevation, y = density)) +geom_segment(aes(xend = elevation, yend =0, colour = elevation)) +geom_line(color ="black", linewidth =0.5) +scale_colour_gradientn(colours = paul_ramp) +theme_classic() +labs(x ="Elevation (m)", y =NULL) +theme(legend.position ="none",axis.text.y =element_blank(), axis.ticks.y =element_blank(), axis.line.y =element_blank()) # patchwork is a package that allows you to easily put multiple # ggplot maps together in panels.# install.packages("patchwork")library(patchwork)map + hist
Code
final_plot <- map +inset_element(hist,left =0.55, bottom =0.02, right =0.98, top =0.40, align_to ='panel')final_plot
Exercise 2. Topography (slope and aspect) and “heat load index”
Now, we will focus again on the Gallatin Range and use the DEM to calculate slope (the steepness of the topography), aspect (the direction the slope faces), and several derived metrics intended to represent topographic position and “heat load”. These variables (elevation, slope, aspect, of heat load) could be useful covariates in models of seedling success, species distributions, predictors of fire severity, etc.
Slope refers to how steepness of the area (change in elevation with change in distance), whereas aspect refers to the compass direction a slope faces. In the northern hemisphere at mid-latitudes steep slopes that face southwest are much hotter and drier than steep slopes that face northeast. This fact influences soil moisture, vegetation productivity, species composition, fuel moisture and fire behavior, snow depth, and more. The same principles apply to a built environment: the slope (pitch) and aspect of your home’s roof determines the optimal locations of solar panel installation and your risk of developing ice dams. This information can help you predict skiing conditions too. Slopes with southerly aspects tend to warm in the day and - of course - freeze at night. This can lead to really icy conditions in the morning and “mashed potatoes” in the afternoon.
Notice the striking differences in vegetation composition and structure related to aspect in this photo from southwestern Idaho.
We will start by looking - again - at the elevation of the Gallatin Range, then calculating the slope and aspect using terra::terrain(), which include a variety of topographic calculations. The default units for slope are degrees (0 = flat and 90 = vertical cliff), but there’s some confusing information about this online. I found one page that suggested that radians are the default units. You can check this by running terrain(gallatin_elev, "slope") and compare the values when you add , unit = "radians" to the line of code. The default units for aspect are in degrees (the compass baring that the slope faces). You can also use radians for aspect too.
Code
# recall that we extracted (clipped) the DEM data to the Gallatin Range # above.gallatin_elev <- elev %>%mask(gallatin_sf) %>%trim()
# If this works, you will see the elevation map of the Gallatin Range.plot(gallatin_elev, axes = F) # plot the DEM without axes
Code
# calculate slopeslope <-terrain(gallatin_elev, "slope") # try also with: unit = "radians"slopeRad <-terrain(gallatin_elev, "slope", unit ="radians") # Look at the maps of the estimates of slope using the different units# If these work, you will see plots of slope in percent and radians. plot(slope, axes = F)
Code
plot(slopeRad, axes = F)
Code
# Calculate aspect with both units and plot them bothaspect <-terrain(gallatin_elev, "aspect") aspectRad <-terrain(gallatin_elev, "aspect", unit ="radians") # If these work, you will see a map of aspect in degrees and radians.plot(aspect)
Code
plot(aspectRad)
Slope and aspect can be very useful by themselves to understand the physical template governing landscape composition and arrangement. However, consider that aspect of a slope is basically the direction that the slope faces. If you collect these data in the field, you will often use a compass to measure which way the slope faces (see diagrams below, source).
A slope that is facing one degree west of due north is 359 degrees, and a slope facing 1 degree east of due north is 1 degree (obviously). If you are not familiar with using a compass look at how the directions are distributed below (source). This presents a challenge when using aspect as a variable.
Compass “rose” showing cardinal directions (N, S, E, W), intercardinal directions (NE, NW, SE, SW), and secondary intercardinal directions (NNE, ENE, ESE, SSE, SSW, WSW, WNW, NNW), with degree markings from 0 to 360 around the outer ring.
There are several options for dealing with aspect as a variable including using cosine to measure “northness” where values of 1 are aspects that face north and values of 0 are aspects that face south. Below, we will calculate cosine of aspect (in radians), map these values, stack both versions of aspect with the cosine of aspect, and look at the relationship between aspect (in degrees) and the cosine of aspect. I find these kinds of plots to be important checks to make sure the calculations are doing what I think they are doing!
Code
cos_aspect <-cos(aspectRad)# If this works, you will see a map of the cosine of aspect in the Gallatin Range.plot(cos_aspect)
Code
# Let's stack aspect (in degrees), aspect in radians, and the cosine of aspectaspects <-c(aspect, aspectRad, cos_aspect)# make sure you change the names of the layers in the stacknames(aspects) <-c("asp_deg", "asp_rad", "cos_asp")# look at the plot of aspects in degrees (compass bearing) with the cosine of aspect in radians# If this works, you will see a plot showing how the cosine of aspect varies across aspect in degrees. Cosine of aspect is high around 0 and 360 (northern aspects) and lowest at 180 (southern aspects).plot(aspects$asp_deg, aspects$cos_asp)
Taking the cosine of aspect takes care of the issue that 359 and 1 are very different numerically but very similar ecologically. But, there are still two issues to consider. Slopes facing due south actually aren’t as hot and dry as those facing slightly southwest. This is because southwestern slopes in the northern hemisphere receive afternoon sun. These slopes have had all day to warm up and experience evaporative cooling. Southeastern facing slopes will received the amount of incoming solar radiation as southwestern slopes, but southeastern slopes received their sun in the morning when conditions are cooler. One way to deal with this - proposed by McCune and Dylan 2002 - is to adjust the cosine so that southwestern slopes are assigned the highest value and northeastern slopes the lowest values. We can use the first formula in McCune and Dylan (2002) with our calculated aspect for the Gallatin Range.
Code
# Use first formula in McCune and Dylan (2002) to calculate a heat load index # This shifts the index so that that southwestern slopes (facing 225 degrees)# are highest and northeastern slopes (facing 45 degrees) have the # lowest value.hli_1 <- (1-cos(aspectRad -45))/2# If this works, you will see a plot of the heat load index for the Gallatin Range.plot(hli_1, axes = F)
McCune and Dylan (2002) recognize that this heat load index doesn’t account for the steepness of slopes. The aspect direction will be more important on steeper slopes. Luckily, the spatialEcol package includes a heat load index that accounts for the fact that steep southwestern-facing slopes tend to be the hottest and driest topographic aspects in mid-latitudes of the northern hemisphere. You also use the elevation data as input and the package calculates slope and aspect “behind the scenes”.
Code
# first download the spatialEcol package (remove the #) and load it# install.packages("spatialEcol")library(spatialEco)hli_2 <- spatialEco::hli(gallatin_elev)# If this works, you will see a map of the heat load index for the Gallatin Range.plot(hli_2, axes = F)
Another handy metric in spatialEco is a topographic position index. Because water, sediments, carbon, and other materials flow or fall downhill, we often want to estimate where a location (pixel) is in relation to other locations. A topographic index can measure the relative position of locations using multiple spatial extents. Some locations can be locally “low” but more regionally “high”. Think about an alpine lake that drains the highest mountains. This hypothetical lake is low compared to the surrounding mountains but relatively high compared to other streams and lakes in a mountain range. The topographic position index (tpi) allows you to specify what extent you want to measure it. TPI is the value of the focal pixel minus the average of the values in the moving window. We will run it for different moving window sizes and plot the results.
Code
# run TPI with scale = 13 (i.e., 13x13 window or 6 pixels on each # side of the center, focal pixel)tpi13 <- spatialEco::tpi(gallatin_elev, scale =13)# If this works, you will see a map of topographic position index for the Gallatin Range.plot(tpi13, axes = F)
Code
# run TPI with scale = 33 (i.e., 33x33 window or 16 pixels on each # side of the center pixel)tpi33 <- spatialEco::tpi(gallatin_elev, scale =33)# If this works, you will see another map of topographic position index for the Gallatin Range.plot(tpi33, axes = F)
Code
# run TPI with scale = 101 (i.e., 101x101 windw or 50 pixels on each # side of the center pixel)tpi101 <-tpi(gallatin_elev, scale =101)# If this works, you will see another map of topographic position index for the Gallatin Range.plot(tpi101, axes = F)
Notice how the patterns and values change with the different moving window sizes? How might you use this metric in ecological research?
Heat load index and canopy cover.
Now, let’s investigate the relationship between ecological variables and topography. Specifically, we will start by evaluating the relationship between canopy cover and heat load index and whether this relationship varies at different elevations. You can find more information on the canopy cover dataset here. Briefly, for this dataset canopy cover is the % of an area covered by tree canopies. Canopy cover is a continuous datasets that tells us how how dense the forest canopy is across the landscape. This datasets could be used to model species habitat suitability (differentiating between species that require or avoid closed canopy forests), as an input to connectivity modeling, to assess the continuity of fuels for wildfire risk assessment, etc. Here, we’re interested in how canopy cover varies with heat load index (a function of slope and aspect). Before running the analysis, what do you predict the relationship to be between heat load index and canopy cover in the Gallatin Range south of Bozeman? How might this relationship change with elevation in the Gallatin Range?
Bring in the canopy cover data and “clip” it to the Gallatin Range as we used in the previous exercise. Use trim() to remove empty space around your new raster. We will then stack elevation, canopy cover, and heat load index into a raster stack, rename the variables, turn the stack into a dataframe, and plot the relationship between heat load index and canopy cover.
Code
# bring in data on elevation and mountains and project again if you need to# bring in data on canopy cover (I've already projected it for you)canopy <-rast("data/Lab3/MT_canopy_coverPRJ.tif")# extract the canopy cover to the gallatin rangegallatin_canopy <- canopy %>%mask(gallatin_sf) %>%trim()
# If this works, you will see an estimate of canopy cover for the Gallatin Range.plot(gallatin_canopy)
Code
# stack the variables into a raster stack called canopy_hli and # plot the stackcanopy_hli <-c(gallatin_elev, gallatin_canopy, hli_2)# If this works, you will see 3 maps for the Gallatin Range: elevation from the DEM, canopy cover, and heat load index. plot(canopy_hli)
Code
# I recommend renaming layers in a stack at this stagenames(canopy_hli) <-c("elevation", "canopy_cover", "heat_load_index")# turn into a dataframedf_canopy_hli <- canopy_hli %>%as.data.frame()# plot the relationship between heat load index and canopy cover# we will add a GAM (generalized additive model) smoothing function # to explore the relationship# If this works, you will see a scatterplot and smoothed function showing heat load index on the x-axis and canopy cover on the y-axis. df_canopy_hli %>%sample_n(50000) %>%drop_na() %>%ggplot(aes(heat_load_index, canopy_cover)) +geom_point(alpha =0.05) +geom_smooth(stat ="smooth", method ="gam") +xlab("Heat load index") +ylab("Canopy cover (%)") +theme_bw()
Recall that we’re interested in how this relationships varies from low to high elevations. We’re first going to classify elevation to 2 “bins” using ntile(2) whereby half of the elevation values get assigned a 1 (lower elevation) and half get assigned a 2 (higher elevation). We will then use these new elevation classes to plot the relationship of heat load index and canopy cover within low and high elevations.
Code
# Classify elevation into 2 equal sized groupsdf_canopy_hli <- df_canopy_hli %>%mutate(elev_bin =ntile(elevation, 2)) # If this works, you will see two scatterplots and smoothed functions showing heat load index on the x-axis and canopy cover on the y-axis in two elevation bins in the Gallatin Range. df_canopy_hli %>%sample_n(50000) %>%# take a sample for faster plottingdrop_na() %>%# remove any NAs in the dataggplot(aes(heat_load_index, canopy_cover)) +geom_point(alpha =0.05) +# make the symbols semi-transparent using alphafacet_wrap(~elev_bin) +# split the data into panels for the elevation bins geom_smooth(stat ="smooth", method ="gam") +# add GAM smooth linexlab("Heat load index") +ylab("Canopy cover (%)") +# customize axis labelstheme_bw() # use as black and white (bw) theme
Look at this plot. Are you convinced that relationships exist between heat load index and canopy cover? How does the relationship change with elevation? Try to explain the patterns. Why would heat load be associated with canopy cover? What other factors affect canopy cover other than slope and aspect?
TASK 2.
Re-run the analysis above for another mountain range in Montana, compare with the patterns we observed in the Gallatin Range, and write up an abstract following Landscape Ecology abstract format.
---title: "Lab 3. Elevation and Topography"subtitle: "The shapes of mountains, slope, and topographic aspect"---::: {.callout-note appearance="minimal"}**Data for this lab.**Download `Lab3.zip` from the [course data archive on Zenodo](https://doi.org/10.5281/zenodo.22101926) and unzip it into a folder called `data/Lab3/` in your project directory.:::# Elevation and topographyElevation, topography, and soils all govern patterns of landscapes and set the stage for physical and biological processes. Variability in topography influences physical processes like erosion, disturbance processes like fire, and micro-climatic conditions and associated distributions of resource availability like soil moisture. Elevation, topography, and soils form the landscape "template" upon which other physical and biological processes operate to give rise to landscape patterns of vegetation.In this lab, we are going to (1) examine the "shapes of mountains" in Montana and discuss the implications of these patterns on mountain ecosystems, and (2) use a digital elevation model (i.e., a raster map of elevation) to calculate various metrics like slope, aspect, topographic position, and a heat load index. Finally, we will explore interactions between elevation, heat load index, and other ecological patterns.# Exercise 1. Shapes of mountains in MontanaElevation (i.e., the vertical height of a landform or location) is associated with numerous factors - most notably temperature - influencing patterns of ecosystems. Temperature tends to decrease with increasing elevation. Temperature tends to decrease with increasing latitude too, of course. Ecosystems are therefore distributed such that an observer climbing a mountain can "sample" vegetation types observed at higher latitudes.The role mountains play in facilitating or impeding species migrations during periods of historical changes in climate is the topic of some very interesting research. Likewise, research on the effects of future climate change on mountain ecosystems and their species has resulted in some fascinating insights. The general prediction is that species will move upslope to track increases in temperature. Using future climate predictions, some scientists have documented a potential loss of climate conditions at the tops of mountains. Other ecologists have measured the change in the geographic area of climate conditions to predict local extinctions of species. This work relies on a simple species-area relationship to predict loss in species with the loss in area as climate shifts up slopes. Notice the shape of the mountain in this classic example. There's more land area in the lower elevation range and less area as you increase elevation. *Adapted from McDonald & Brown 1992, Conservation Biology 6(3):409–415. https://doi.org/10.1046/j.1523-1739.1992.06030409.x*Paul Elsen and Morgan Tingley realized that not all mountains are shaped like this. They used data from a digital elevation model (DEM, a raster map where each pixel represents the elevation) to investigate the shapes of mountains simply by plotting histograms of elevation among mountain ranges around the planet. They used some summary statistics of the shape of each histogram to classify the shapes of mountains. Elsen and Tingley suggested that these different shapes of mountains warranted a more complicated view of how climate change may put mountain species at risk of losing habitat. Some mountains have more area at higher elevation providing more opportunities for species to find new habitat as temperatures increase.*From Elsen & Tingley 2015, Nature Climate Change 5. https://doi.org/10.1038/nclimate2656. Used with permission from the publisher under license 6332060890717.*We are going to be be looking at the shapes of mountain ranges in Montana using the first step in Elsen et al.'s approach.## Elevation and mountainsFirst, we will load libraries and bring in a [DEM](https://landfire.gov/topographic/elevation) and shapefile of [mountain ranges in Montana](https://mslservices.mt.gov/Geographic_Information/Data/DataList/datalist_Details.aspx?did=%7B03903E60-C81D-4126-A060-69AD917106B4%7D). You can read more about the datasets in the links.```{r}library(terra)library(sf)library(tidyverse)elev <-rast("data/Lab3/MT_dem.tif")mtns <-vect("data/Lab3/Mtn_Ranges.shp")# We need to project the mountains to the same crs as the elevation datamtnsPRJ <-project(mtns, elev)# Now, plot the maps of elevation and the Montana mountains # If this works, you will see a map of Montana elevation, showing the mountains in the west and the plains in the east. plot(elev)# If this works, you will see a map of Montana mountain ranges.plot(mtnsPRJ) # if this returns an error, remove "add = T" and rerun```We want to use tidyverse function to subset the mountains data (i.e., select only one mountain range). This works best if we turn the terra vector into an special features (sf) object. We'll do that, then look at the names of the variables in the attribute table. "NAME" is one of the attributes, which stores the name of each mountain range. We'll also look at all the mountain ranges in the dataset using `unique()`.```{r}# turn the terra vector into a sf objectmtns_sf <-st_as_sf(mtnsPRJ)# what are the names of the variables in the attribute table?names(mtns_sf)# In the variable called "NAME" list the unique namesunique(mtns_sf$NAME)```How many mountain ranges are there?Now, we will use the `filter` function in `dplyr`, which is part of the `tidyverse` to select the Gallatin Range, which is just south of Bozeman. Then, plot the boundaries of this mountain range.```{r}gallatin_sf <- mtns_sf %>%filter(NAME =="Gallatin Range")# If this works, you will see 6 maps of the Gallatin Range, one for each variable in the accompanying data table.plot(gallatin_sf)```Next, we will use this new sf object as a `mask` to extract the DEM data for only the Gallatin Range. We add `trim()` to remove all the blank space left over after essentially clipping the data to the Gallatin Range. You can try removing `%>% trim()`, running that line, and plotting to see what `trim()` does. It can be handy.```{r}gallatin_elev <- elev %>%mask(gallatin_sf) %>%trim()# If this works, you will see a map of elevation for the Gallatin Range.plot(gallatin_elev)```One of the core parts of Elsen and Tingley's method is to plot and examine the histograms of elevation for mountain ranges. We will do this with `hist()`, which plots a traditional histogram where the number of observations (pixels) within each bin (a range of values) is plotted. We will also use `density()` to plot a smoothed histogram ([a kernel density plot](https://www.r-bloggers.com/2023/08/kernel-density-plots-in-r/)).```{r}# If these lines of code work, you will see a histogram and smoothed histogram (kernel density plot) of elevation values revealing elevation to be rather normally distributed.hist(gallatin_elev)density(gallatin_elev)```One way Elsen and Tingley plotted the land area for different elevations was to create a two-sided kernel density plot. You can do this in R using [violin plots](https://mode.com/blog/violin-plot-examples), which are becoming more common in the scientific literature (but, beware, some people do not like these plots!).```{r}# This should produce a "violin plot" of elevation for the Gallatin Range.gallatin_elev %>%as.data.frame() %>%ggplot(aes(x ="Gallatin Range", y = MT_dem)) +geom_violin(scale ="width", fill ="grey") +labs(x ="Mountain Range", y ="Elevation (m)") +theme_bw()```What do you notice about the "shape" of the Gallatin Range in relation to the different categories of mountain shapes that Elsen and Tingley recognized? We won't use their method to classify mountain ranges into the categories (diamond, pyramid, inverse pyramid, hourglass). Instead, just "eye-ball" the shape and list the shape you think it bests matches.::: {.callout-tip appearance="minimal"}**TASK 1.**Choose 2 other mountain ranges in Montana, follow the steps above to extract the data to the mountain ranges of your choice, plot the histogram and density plot of elevation, and describe which shape you think it most matches of the four recognized by Elsen and Tingley. Describe the possible implications of these shapes. Write up an abstract following *Landscape Ecology* abstract format.:::**OPTIONAL. Histograms as map legends.**I have found that histograms serve as excellent map legends. This is a very informative way to visualize the spatial patterns and statistical distribution simultaneously and provides transparency in how colors are assigned given the range of values in a raster dataset. In the case at hand, mapping elevation alongside the histogram in a color-coordinated way can provide a really information-rich visualization of data.I start by creating a color ramp that attempts to match Elsen and Tingley. I then turn the DEM raster into a dataframe so that I can plot it using ggplot. I then use the density function to pull out values from the kernel density estimation for plotting in ggplot. Finally, I put the map and histogram together using the `patchwork` library.```{r}## OPTIONAL!# This will produce a map and smoothed histogram of elevation for the Gallatin Range.# Custom ramp based on your barpaul_colors <-c("#0B2C7A", "#20998F", "#00DB00", "#FFFF00", "#EDA113", "#C2523C")paul_ramp <-colorRampPalette(paul_colors)(100)# Extract elevation values from DEM (sample if very large)elev_df <-as.data.frame(gallatin_elev, xy =TRUE, na.rm =TRUE)names(elev_df) <-c("x", "y", "elevation")map <- elev_df %>%ggplot() +geom_tile(aes(x = x, y = y, fill = elevation)) +scale_fill_gradientn(colors = paul_ramp) +coord_fixed() +theme_void() +theme(legend.position ="none")# Compute density of elevationsdens <-density(elev_df$elevation, na.rm =TRUE, n =2^12)# Convert to a dataframe for ggplotdens_df <-data.frame(elevation = dens$x,density = dens$y)hist <-ggplot(dens_df, aes(x = elevation, y = density)) +geom_segment(aes(xend = elevation, yend =0, colour = elevation)) +geom_line(color ="black", linewidth =0.5) +scale_colour_gradientn(colours = paul_ramp) +theme_classic() +labs(x ="Elevation (m)", y =NULL) +theme(legend.position ="none",axis.text.y =element_blank(), axis.ticks.y =element_blank(), axis.line.y =element_blank()) # patchwork is a package that allows you to easily put multiple # ggplot maps together in panels.# install.packages("patchwork")library(patchwork)map + histfinal_plot <- map +inset_element(hist,left =0.55, bottom =0.02, right =0.98, top =0.40, align_to ='panel')final_plot```# Exercise 2. Topography (slope and aspect) and "heat load index"Now, we will focus again on the Gallatin Range and use the DEM to calculate slope (the steepness of the topography), aspect (the direction the slope faces), and several derived metrics intended to represent topographic position and "heat load". These variables (elevation, slope, aspect, of heat load) could be useful covariates in models of seedling success, species distributions, predictors of fire severity, etc.Slope refers to how steepness of the area (change in elevation with change in distance), whereas aspect refers to the compass direction a slope faces. In the northern hemisphere at mid-latitudes steep slopes that face southwest are much hotter and drier than steep slopes that face northeast. This fact influences soil moisture, vegetation productivity, species composition, fuel moisture and fire behavior, snow depth, and more. The same principles apply to a built environment: the slope (pitch) and aspect of your home's roof determines the optimal locations of solar panel installation and your risk of developing ice dams. This information can help you predict skiing conditions too. Slopes with southerly aspects tend to warm in the day and - of course - freeze at night. This can lead to really icy conditions in the morning and "mashed potatoes" in the afternoon.Notice the striking differences in vegetation composition and structure related to aspect in this photo from southwestern Idaho. *Photo by Thayne Tuason, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Effects_of_aspect_on_vegetation-_SW_Idaho.JPG), CC-BY-SA 3.0.*We will start by looking - again - at the elevation of the Gallatin Range, then calculating the slope and aspect using `terra::terrain()`, which include a variety of topographic calculations. The default units for slope are degrees (0 = flat and 90 = vertical cliff), but there's some confusing information about this online. I found one page that suggested that radians are the default units. You can check this by running `terrain(gallatin_elev, "slope")` and compare the values when you add `, unit = "radians"` to the line of code. The default units for aspect are in degrees (the compass baring that the slope faces). You can also use radians for aspect too.```{r}# recall that we extracted (clipped) the DEM data to the Gallatin Range # above.gallatin_elev <- elev %>%mask(gallatin_sf) %>%trim()# If this works, you will see the elevation map of the Gallatin Range.plot(gallatin_elev, axes = F) # plot the DEM without axes# calculate slopeslope <-terrain(gallatin_elev, "slope") # try also with: unit = "radians"slopeRad <-terrain(gallatin_elev, "slope", unit ="radians") # Look at the maps of the estimates of slope using the different units# If these work, you will see plots of slope in percent and radians. plot(slope, axes = F)plot(slopeRad, axes = F)# Calculate aspect with both units and plot them bothaspect <-terrain(gallatin_elev, "aspect") aspectRad <-terrain(gallatin_elev, "aspect", unit ="radians") # If these work, you will see a map of aspect in degrees and radians.plot(aspect)plot(aspectRad)```Slope and aspect can be very useful by themselves to understand the physical template governing landscape composition and arrangement. However, consider that aspect of a slope is basically the direction that the slope faces. If you collect these data in the field, you will often use a compass to measure which way the slope faces (see diagrams below, [source](https://avalanche.org/avalanche-encyclopedia/terrain/slope-characteristics/aspect/)). *Source: [avalanche.org](https://avalanche.org/avalanche-encyclopedia/terrain/slope-characteristics/aspect/), used with permission.*A slope that is facing one degree west of due north is 359 degrees, and a slope facing 1 degree east of due north is 1 degree (obviously). If you are not familiar with using a compass look at how the directions are distributed below ([source](https://en.wikibooks.org/wiki/Trigonometry/Compass_Bearings)). This presents a challenge when using aspect as a variable.*Source: [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Compass_rose.png)*There are several options for dealing with aspect as a variable including using cosine to measure "northness" where values of 1 are aspects that face north and values of 0 are aspects that face south. Below, we will calculate cosine of aspect (in radians), map these values, stack both versions of aspect with the cosine of aspect, and look at the relationship between aspect (in degrees) and the cosine of aspect. I find these kinds of plots to be important checks to make sure the calculations are doing what I think they are doing!```{r}cos_aspect <-cos(aspectRad)# If this works, you will see a map of the cosine of aspect in the Gallatin Range.plot(cos_aspect)# Let's stack aspect (in degrees), aspect in radians, and the cosine of aspectaspects <-c(aspect, aspectRad, cos_aspect)# make sure you change the names of the layers in the stacknames(aspects) <-c("asp_deg", "asp_rad", "cos_asp")# look at the plot of aspects in degrees (compass bearing) with the cosine of aspect in radians# If this works, you will see a plot showing how the cosine of aspect varies across aspect in degrees. Cosine of aspect is high around 0 and 360 (northern aspects) and lowest at 180 (southern aspects).plot(aspects$asp_deg, aspects$cos_asp)```Taking the cosine of aspect takes care of the issue that 359 and 1 are very different numerically but very similar ecologically. But, there are still two issues to consider. Slopes facing due south actually aren't as hot and dry as those facing slightly southwest. This is because southwestern slopes in the northern hemisphere receive afternoon sun. These slopes have had all day to warm up and experience evaporative cooling. Southeastern facing slopes will received the amount of incoming solar radiation as southwestern slopes, but southeastern slopes received their sun in the morning when conditions are cooler. One way to deal with this - proposed by [McCune and Dylan 2002](https://onlinelibrary.wiley.com/doi/epdf/10.1111/j.1654-1103.2002.tb02087.x) - is to adjust the cosine so that southwestern slopes are assigned the highest value and northeastern slopes the lowest values. We can use the first formula in McCune and Dylan (2002) with our calculated aspect for the Gallatin Range.```{r}# Use first formula in McCune and Dylan (2002) to calculate a heat load index # This shifts the index so that that southwestern slopes (facing 225 degrees)# are highest and northeastern slopes (facing 45 degrees) have the # lowest value.hli_1 <- (1-cos(aspectRad -45))/2# If this works, you will see a plot of the heat load index for the Gallatin Range.plot(hli_1, axes = F)```McCune and Dylan (2002) recognize that this heat load index doesn't account for the steepness of slopes. The aspect direction will be more important on steeper slopes. Luckily, the `spatialEcol` package includes a heat load index that accounts for the fact that steep southwestern-facing slopes tend to be the hottest and driest topographic aspects in mid-latitudes of the northern hemisphere. You also use the elevation data as input and the package calculates slope and aspect "behind the scenes".```{r}# first download the spatialEcol package (remove the #) and load it# install.packages("spatialEcol")library(spatialEco)hli_2 <- spatialEco::hli(gallatin_elev)# If this works, you will see a map of the heat load index for the Gallatin Range.plot(hli_2, axes = F)```Another handy metric in `spatialEco` is a topographic position index. Because water, sediments, carbon, and other materials flow or fall downhill, we often want to estimate where a location (pixel) is in relation to other locations. A topographic index can measure the relative position of locations using multiple spatial extents. Some locations can be locally "low" but more regionally "high". Think about an alpine lake that drains the highest mountains. This hypothetical lake is low compared to the surrounding mountains but relatively high compared to other streams and lakes in a mountain range. The topographic position index (`tpi`) allows you to specify what extent you want to measure it. TPI is the value of the focal pixel minus the average of the values in the moving window. We will run it for different moving window sizes and plot the results.```{r}# run TPI with scale = 13 (i.e., 13x13 window or 6 pixels on each # side of the center, focal pixel)tpi13 <- spatialEco::tpi(gallatin_elev, scale =13)# If this works, you will see a map of topographic position index for the Gallatin Range.plot(tpi13, axes = F)# run TPI with scale = 33 (i.e., 33x33 window or 16 pixels on each # side of the center pixel)tpi33 <- spatialEco::tpi(gallatin_elev, scale =33)# If this works, you will see another map of topographic position index for the Gallatin Range.plot(tpi33, axes = F)# run TPI with scale = 101 (i.e., 101x101 windw or 50 pixels on each # side of the center pixel)tpi101 <-tpi(gallatin_elev, scale =101)# If this works, you will see another map of topographic position index for the Gallatin Range.plot(tpi101, axes = F)```Notice how the patterns and values change with the different moving window sizes? How might you use this metric in ecological research?## Heat load index and canopy cover.Now, let's investigate the relationship between ecological variables and topography. Specifically, we will start by evaluating the relationship between canopy cover and heat load index and whether this relationship varies at different elevations. You can find more information on the canopy cover dataset [here](https://data.fs.usda.gov/geodata/rastergateway/treecanopycover/docs/TCC_v2023-5_Methods.pdf). Briefly, for this dataset canopy cover is the % of an area covered by tree canopies. Canopy cover is a continuous datasets that tells us how how dense the forest canopy is across the landscape. This datasets could be used to model species habitat suitability (differentiating between species that require or avoid closed canopy forests), as an input to connectivity modeling, to assess the continuity of fuels for wildfire risk assessment, etc. Here, we're interested in how canopy cover varies with heat load index (a function of slope and aspect). Before running the analysis, what do you predict the relationship to be between heat load index and canopy cover in the Gallatin Range south of Bozeman? How might this relationship change with elevation in the Gallatin Range?Bring in the canopy cover data and "clip" it to the Gallatin Range as we used in the previous exercise. Use `trim()` to remove empty space around your new raster. We will then stack elevation, canopy cover, and heat load index into a raster stack, rename the variables, turn the stack into a dataframe, and plot the relationship between heat load index and canopy cover.```{r}# bring in data on elevation and mountains and project again if you need to# bring in data on canopy cover (I've already projected it for you)canopy <-rast("data/Lab3/MT_canopy_coverPRJ.tif")# extract the canopy cover to the gallatin rangegallatin_canopy <- canopy %>%mask(gallatin_sf) %>%trim()# If this works, you will see an estimate of canopy cover for the Gallatin Range.plot(gallatin_canopy)# stack the variables into a raster stack called canopy_hli and # plot the stackcanopy_hli <-c(gallatin_elev, gallatin_canopy, hli_2)# If this works, you will see 3 maps for the Gallatin Range: elevation from the DEM, canopy cover, and heat load index. plot(canopy_hli)# I recommend renaming layers in a stack at this stagenames(canopy_hli) <-c("elevation", "canopy_cover", "heat_load_index")# turn into a dataframedf_canopy_hli <- canopy_hli %>%as.data.frame()# plot the relationship between heat load index and canopy cover# we will add a GAM (generalized additive model) smoothing function # to explore the relationship# If this works, you will see a scatterplot and smoothed function showing heat load index on the x-axis and canopy cover on the y-axis. df_canopy_hli %>%sample_n(50000) %>%drop_na() %>%ggplot(aes(heat_load_index, canopy_cover)) +geom_point(alpha =0.05) +geom_smooth(stat ="smooth", method ="gam") +xlab("Heat load index") +ylab("Canopy cover (%)") +theme_bw()```Recall that we're interested in how this relationships varies from low to high elevations. We're first going to classify elevation to 2 "bins" using `ntile(2)` whereby half of the elevation values get assigned a 1 (lower elevation) and half get assigned a 2 (higher elevation). We will then use these new elevation classes to plot the relationship of heat load index and canopy cover within low and high elevations.```{r}# Classify elevation into 2 equal sized groupsdf_canopy_hli <- df_canopy_hli %>%mutate(elev_bin =ntile(elevation, 2)) # If this works, you will see two scatterplots and smoothed functions showing heat load index on the x-axis and canopy cover on the y-axis in two elevation bins in the Gallatin Range. df_canopy_hli %>%sample_n(50000) %>%# take a sample for faster plottingdrop_na() %>%# remove any NAs in the dataggplot(aes(heat_load_index, canopy_cover)) +geom_point(alpha =0.05) +# make the symbols semi-transparent using alphafacet_wrap(~elev_bin) +# split the data into panels for the elevation bins geom_smooth(stat ="smooth", method ="gam") +# add GAM smooth linexlab("Heat load index") +ylab("Canopy cover (%)") +# customize axis labelstheme_bw() # use as black and white (bw) theme```Look at this plot. Are you convinced that relationships exist between heat load index and canopy cover? How does the relationship change with elevation? Try to explain the patterns. Why would heat load be associated with canopy cover? What other factors affect canopy cover other than slope and aspect?::: {.callout-tip appearance="minimal"}**TASK 2.**Re-run the analysis above for another mountain range in Montana, compare with the patterns we observed in the Gallatin Range, and write up an abstract following *Landscape Ecology* abstract format.:::# Data source(s)Digital elevation model (MT_dem.tif): [LANDFIRE](https://landfire.gov/topographic/elevation).Tree canopy cover (MT_canopy_coverPRJ.tif): [USFS Forest Service Geospatial Data Gateway, Tree Canopy Cover product](https://data.fs.usda.gov/geodata/rastergateway/treecanopycover/docs/TCC_v2023-5_Methods.pdf)Montana mountain ranges (Mtn_Ranges.shp): [Montana State Library](https://mslservices.mt.gov/Geographic_Information/Data/DataList/datalist_Details.aspx?did=%7B03903E60-C81D-4126-A060-69AD917106B4%7D).