Code
# Load packages (install if you need to)
library(terra)
library(sf)
library(mapview)
library(pals)
library(viridis)
library(tidyverse)
library(ggridges)
library(ncf)Spatial autocorrelation and Moran’s I
Data for this lab.
Download Lab8.zip from the course data archive on Zenodo and unzip it into a folder called data/Lab8/ in your project directory.
“A thing is right when it tends to preserve the integrity, stability and beauty of the biotic community. It is wrong when it tends otherwise.” - Aldo Leopold
The concept of ecological integrity is pervasive in global conservation targets and U.S. federal policy. The first two targets of the Global Biodiversity Framework outline the importance of protecting “ecosystems of high ecological integrity”. The Clean Water Act, National Wildlife Refuge System Improvement Act of 1997, U.S. Forest Service’s 2012 Planning Rule, and the Bureau of Land Management’s (BLM) Fundamentals of Rangeland Health, among other laws and regulations reference the importance of maintaining or restoring ecological integrity.
As an example, the Forest Service’s 2012 Planning Rule requires that forest plans “must include plan components… to maintain or restore the ecological integrity of terrestrial and aquatic ecosystems.” Ecological integrity is defined here as “the quality or condition of an ecosystem when its dominant ecological characteristics (for example, composition, structure, function, connectivity, and species composition and diversity) occur within the natural range of variation and can withstand and recover from most perturbations imposed by natural environmental dynamics or human influence.”
Conceptual framework of ecological integrity (composition, structure, function). Credit: Lucy Poley, Wildlife Conservation Society Canada. Used with permission.
The concept of ecological integrity is similar to the concept of ecological intactness. Often, integrity and intactness are used synonymously. One of the requirements of BLM’s Public Lands Rule is to “Protect the most intact, functioning landscapes.”
Clearly, policy makers understand that “integrity” is important to maintain or restore, and various definitions of integrity have been presented. However, there is no “integrity-meter” that measures an unambiguous attribute of landscapes. Most scholars understand integrity to be assessed using multiple criteria.
In the last several years numerous efforts have used spatial data on roads, land cover, light pollution, transmission lines, and other mapped features that represent a degree of human modification as a composite index. The Human Footprint, global map of human modification, and other spatial data have been produced that assume that land use and development represent stressors that can alter the ecological composition, structure, and function (i.e., ecological integrity).
Image below illustrates how multiple datasets are combined to map the Human Modification (Theobald et al. 2025), which has been associated with ecological integrity.
The Human Modification Framework, showing data curation, spatial modeling, and integration into a global Human Modification index. Credit: Katie Walker, The Nature Conservancy. Used with permission.
Here, we will evaluate the human modification dataset that has been used to map lands of high integrity (i.e., intact landscapes). We will explore the spatial patterns of these datasets using spatial statistics (e.g., Moran’s I) and investigate how ecological integrity varies with topography and among regions of Montana, Idaho, and Wyoming. Spatial patterns in human modification and ecological integrity may tell us whether the underlying patterns are random or clumped in a similar way to topography, soils, or other factors that influence where humans develop lands, build roads, or otherwise modify landscapes. We will only scratch the surface here. The goals of this lab are (1) to introduce you to the multiple criteria that have been used to measure and map ecological integrity and (2) to demonstrate how spatial statistics can be used with these kinds of data.
A widely used dataset to represent ecological integrity is David Theobald and colleagues’ map of human modification. Theobald and colleagues combined mapped features that represent ecological stressors including land cover conversion, roads, mining activity, human population density, and other criteria that represent ways that humans alter natural ecosystems. The combination of these criteria has been used as a composite map of human modification or the inverse, ecological integrity. The data have been used to map the Earth’s remaining intact landscapes (wildlands or wilderness), as the basis for connectivity modeling, and as a general map of ecological integrity.
The Global Map of Human Modification. Credit: Katie Walker, The Nature Conservancy. Used with permission.
We will explore global and local Moran’s I using the composite map of ecological integrity. This approach will be used to ask questions such as “how clumped are lands of high ecological integrity across Montana, Idaho, and Wyoming based on the different features that may disrupt ecological integrity?”
# Bring in human modification-based map of ecological integrity
ei <- rast("data/Lab8/hm_MTIDWY.tif")
# Look at a map of ecological integrity (i.e, the opposite of human modification)
# This will show human modification for Montana, Idaho, and Wyoming. You can see the interstate highways and regions of agriculture as bright yellow and large wildlands as black regions.
plot(ei, col = rev(magma(50)), axes = F)
Before we explore the spatial autocorrelation of ecological integrity and consider what these patterns mean, let’s summarize the patterns among ecoregions of Montana, Idaho, and Wyoming. First, we’ll bring in the ecoregion polygons, rasterize them, stack the ecoregions with the ecological integrity, turn the stack into a dataframe, and plot kernel density plots (i.e., “smoothed” histograms) for each ecoregion (in a visualization sometimes called “ridgeline” plots).

[1] "US_L3CODE" "US_L3NAME" "NA_L3CODE" "NA_L3NAME" "NA_L2CODE"
[6] "NA_L2NAME" "NA_L1CODE" "NA_L1NAME" "L3_KEY" "L2_KEY"
[11] "L1_KEY" "Shape_Leng" "Shape_Area" "FID"
# Turn the ecoregion polygons into a raster using rasterize
# make the cell size, crs, and extent match the ecological integrity ("ei") data
# and assign the pixels the ecoregion names in the field "US_L3NAME"
ecoRaster <- ecoregions %>% rasterize(ei, field = "US_L3NAME")
# Look at this map
# This shows a map of ecoregions in Montana, Idaho, and Wyoming.
plot(ecoRaster)

x y ei ecoregion
3702 -1545473 3059679 0.9815145 Northern Rockies
3703 -1544473 3059679 0.9818787 <NA>
4865 -1545473 3058679 0.9819241 Northern Rockies
4866 -1544473 3058679 0.9821137 Northern Rockies
4867 -1543473 3058679 0.9809589 Northern Rockies
4868 -1542473 3058679 0.9743989 Northern Rockies
# We will use some special plotting features in "ggridges" for this plot.
# This shows a map of plot of smoothed histograms of ecological integrity by ecoregions in Montana, Idaho, and Wyoming.
ei_ecoregionDF %>% drop_na() %>% group_by(ecoregion) %>%
sample_frac(0.1) %>% ungroup() %>%
ggplot(aes(x = ei, y = fct_reorder(factor(ecoregion), ei, .fun = mean))) +
geom_density_ridges() +
xlab("Ecological Integrity") + ylab("Ecoregion")+
guides(fill = FALSE)+
theme_classic() + theme(text = element_text(size = 14))
# Let's use a color scheme that we could match with our maps.
# This shows a map of plot of smoothed histograms of ecological integrity by ecoregions in Montana, Idaho, and Wyoming.
ei_ecoregionDF %>% drop_na() %>% group_by(ecoregion) %>%
sample_frac(0.1) %>% ungroup() %>%
ggplot(aes(x = ei, y = fct_reorder(factor(ecoregion), ei, .fun = mean))) +
geom_density_ridges_gradient(aes(fill = after_stat(x))) +
scale_fill_viridis_c(option = "magma", direction = -1) +
xlab("Ecological Integrity") + ylab("Ecoregion")+
guides(fill = FALSE)+
theme_classic() + theme(text = element_text(size = 14))
Look at the ridgeline plots of ecological integrity for each ecoregion. Which ecoregions have the highest ecological integrity? Why?
We will now explore the geographic distribution of ecological integrity using spatial statistics.
One of the first laws of geography is that things closer together tend to be more alike than things further apart. I’m paraphrasing Tobler’s Law. In ecology, we say that things we measure are often spatially correlated, or that there is spatial autocorrelation in the data (variables are correlated with themselves across geographic space). Observing and quantifying this autocorrelation can reveal important spatial patterns and processes (e.g., species dispersal and colonization) and may also be essential for adhering to the statistical assumption that samples are independent. In other words, if you sample in a way where a variable shows strong spatial autocorrelation, you may not be able to count those observations as truly independent. This can mess up our inference when conducting hypothesis testing and must be addressed. Here, we will focus on assessing spatial autocorrelation to quantify spatial patterns in continuous data on ecological integrity. Assessing these patterns may provide insights into landscapes that maintain their integrity and those that have impaired integrity.
We will use Moran’s I to do this. Put simply, Moran’s I is analogous to a correlation coefficient assessing how one variable is correlated with itself across geographic space. In fact, the formula for Moran’s I is very similar to the formula to calculate a correlation coefficient and can be interpreted similarly. The higher Moran’s I, the stronger the spatial autocorrelation. Take, for example, the simulated landscapes below. I have included Moran’s I above each map. The closer the patterns become to random (i.e., uncorrelated) the lower Moran’s I is. These values are called “global” Moran’s I and provide one number to quantify the entire landscape.

You can also calculate “local” Moran’s I and assess how the spatial autocorrelation changes with distance between observations. We can map local spatial correlation like below. Higher local autocorrelation is in yellow.

And we can plot how autocorrelation changes with distance using plots known as correlograms. Correlograms are closely related to “variograms” or “semivariograms”, but show the opposite patterns (i.e., how dissimilarity increases with distance). Correlograms can be useful in understanding the spatial scale driving a process, helping to decide on an appropriate grain or resolution to use in predictive modeling, aiding a field study to avoid spatial autocorrelation (i.e., how far apart should you put plots so that data are not spatial autocorrelated?). Here, we will use correlograms to understand the spatial extent of patterns in ecological integrity. The examples below show the correlograms associated with the maps above. Again, as the patterns become more random the correlation of observation closer together approaches 0.

We will first calculate the global Moran’s I, which is quite easy in R. The package terra has a function called autocor that allows you to do this.
Then, we will calculate and map local Moran’s I.
INVhm270_extract
0.9332348

Now, let’s create a correlogram to investigate how spatial autocorrelation varies with distance, as I have done above for the simulated landscapes.
set.seed(3950)
# We need to make the raster a dataframe
eidf <- ei %>% as.data.frame(xy = T) %>% sample_n(1000)
# adjust the names
names(eidf) <- c("x", "y", "ei")
# run the correlogram from the package ncf
# increment = 25000 (meters) is the distance "bins" used to calculate
# autocorrelation at different distances.
cor_int <- ncf::correlog(x = eidf$x, y = eidf$y, z = eidf$ei,
increment = 25000, resamp = 0, na.rm = TRUE)
# look at the output called "cor_int"
cor_int$n
1 2 3 4 5 6 7 8 9 10 11 12 13
1104 3245 5180 6827 8455 10126 11176 12402 13432 14702 15573 16357 16940
14 15 16 17 18 19 20 21 22 23 24 25 26
17547 17888 18263 18452 18187 18592 18367 17866 17852 16971 16657 15970 15631
27 28 29 30 31 32 33 34 35 36 37 38 39
14836 13961 13012 12206 11378 10352 9659 8810 7995 6836 5797 4930 4191
40 41 42 43 44 45 46 47 48 49 50 51 52
3283 2459 1816 1277 944 692 479 342 201 127 92 44 18
53
1
$mean.of.class
1 2 3 4 5 6 7
16491.92 38681.19 63256.82 87910.33 112727.42 137872.93 162626.92
8 9 10 11 12 13 14
187634.81 212641.76 237676.88 262549.95 287511.31 312439.38 337591.23
15 16 17 18 19 20 21
362543.72 387457.27 412440.10 437446.86 462510.17 487449.32 512374.94
22 23 24 25 26 27 28
537466.94 562395.47 587402.91 612489.06 637394.40 662424.51 687345.22
29 30 31 32 33 34 35
712324.42 737289.96 762254.35 787288.03 812335.51 837316.46 862229.42
36 37 38 39 40 41 42
887219.72 912137.53 936868.09 962273.30 986886.85 1011935.92 1036910.60
43 44 45 46 47 48 49
1061640.15 1086888.45 1111845.39 1136732.94 1162055.76 1185552.22 1212116.32
50 51 52 53
1236759.01 1263332.49 1283509.86 1300389.17
$correlation
1 2 3 4 5
0.3444458685 0.1790701393 0.1121178328 0.0842828618 0.0605681675
6 7 8 9 10
0.0533616922 0.0457547941 0.0257871178 0.0064547356 -0.0035318521
11 12 13 14 15
-0.0084579452 0.0081272843 0.0001941112 0.0002364264 0.0097910089
16 17 18 19 20
-0.0045105907 -0.0125688366 0.0061867411 0.0127844584 -0.0195545223
21 22 23 24 25
-0.0073312339 -0.0202793222 0.0132906385 0.0129186402 0.0217232112
26 27 28 29 30
-0.0076338202 0.0042448313 0.0018478193 -0.0235020590 -0.0337932418
31 32 33 34 35
-0.0453737763 -0.0736910515 -0.0723048656 -0.0354299340 -0.0261094613
36 37 38 39 40
-0.0234040133 -0.0396318798 -0.0336351888 0.0022971540 -0.0510863546
41 42 43 44 45
-0.0500101980 -0.0727298734 -0.1213892164 -0.0585712534 -0.0349907348
46 47 48 49 50
-0.1843602942 -0.1982737156 0.1129571439 -0.4593194803 -0.3197016674
51 52 53
-0.0264290979 -1.0016964911 -0.3151295023
$x.intercept
(Intercept)
221495.7
$p
NULL
$call
[1] "ncf::correlog(x = eidf$x, y = eidf$y, z = eidf$ei, increment = 25000, "
[2] " resamp = 0, na.rm = TRUE)"
attr(,"class")
[1] "correlog"
Now, let’s produce the correlogram using the output we created above. The type = "b" and pch = 19 are just graphing options (type = b is connecting dots with lines and pch = 19 tells R we want our points to be filled circles. We’re also dividing the “mean of class” by 1000 so that the units are in kilometers and not meters. abline just adds a hashed line to the plot at 0, so there’s a clear indication of where we lose any spatial autocorrelation.
# Plot the output of the correlogram using base R
# "mean of class" is the mean distances. Let's divide those by 1000 so that the
# units are in km and not meters
plot(cor_int$mean.of.class / 1000, cor_int$correlation,
type = "b", pch = 19, ylim = c(-1,1),
xlab = "Distance (km)", ylab = "Moran's I")
abline(h = 0, lty = 2, col = "grey50")
Look back at the map of ecological integrity as measured by Theobald’s human modification, and study the correlogram. What does the plot tell you about the spatial ‘clumpiness’ of areas of high human modification or high ecological integrity? What are the causes and consequences of these patterns?
Let’s bring in the inputs to human modification and evaluate the spatial autocorrelation in each of the criteria.
[1] "data/Lab8/MTIDWY/HMv20240801_2022s_AA_300_tif.tif"
[2] "data/Lab8/MTIDWY/HMv20240801_2022s_AG_300_tif.tif"
[3] "data/Lab8/MTIDWY/HMv20240801_2022s_BU_300_tif.tif"
[4] "data/Lab8/MTIDWY/HMv20240801_2022s_EX_300_tif.tif"
[5] "data/Lab8/MTIDWY/HMv20240801_2022s_FR_300_tif.tif"
[6] "data/Lab8/MTIDWY/HMv20240801_2022s_HI_300_tif.tif"
[7] "data/Lab8/MTIDWY/HMv20240801_2022s_NS_300_tif.tif"
[8] "data/Lab8/MTIDWY/HMv20240801_2022s_PO_300_tif.tif"
[9] "data/Lab8/MTIDWY/HMv20240801_2022s_TI_300_tif.tif"
These inputs include two letter codes, which are described below. Look over this list and consider how these “threat types” might impact ecological integrity. Again, consider ecological integrity as a quality of ecosystems and landscapes related to the composition, structure, and function. How might each of these threats affect integrity and in what ways? What is missing?
| Code | Threat Type | Description |
|---|---|---|
| AA | All threats combined | Composite index integrating all human modification pressures. |
| AG | Agriculture | Areas modified by crop cultivation, pasture, or other agricultural use. |
| BU | Built environments | Residential, commercial, and recreational development. |
| EX | Energy production and mining | Land modified for oil, gas, coal, wind, solar, or mineral extraction. |
| FR | Biological resource use | Areas affected by forestry, logging, or other extraction of biological resources. |
| HI | Human accessibility | Modification due to proximity to human access (e.g., roads, trails, settlements). |
| NS | Natural systems modification | Alterations of natural processes such as dams, water diversion, or fire suppression. |
| PO | Pollution | Areas influenced by chemical, nutrient, or other pollution sources. |
| TI | Transportation and service corridors | Roads, railways, powerlines, pipelines, and other linear infrastructure. |
Now, let’s look at the maps of each of these threats or stressors.
TASK 1.
Look at the patterns in the maps for the inputs to human modification. Re-run the global and local Moran’s I for at least 3 of the inputs and produce the correlogram. Compare the values and maps of the three criteria in relationship to how (and why) humans modified lands and whether the modification is spatially aggregated or more randomly distributed. Compare your correlograms to the ones I created with the simulated landscapes above. What do you think the ecological consequences of these different patterns are for ecological integrity? Include the maps and plots in a multi-panel figure with a descriptive caption, report the global Moran’s I in the caption, and describe the patterns. Write up your results as an abstract for Landscape Ecology.
Now, let’s investigate whether human modification and ecological integrity vary with topography, namely elevation and slope steepness. We will first bring in elevation, project it to match the human modification data, and calculate slope using the terrain function.


Now, we will create a raster stack of ecological integrity, elevation, and slope. We will turn this raster stack into a dataframe, and use ggplot to investigate the relationship between elevation and slope and human modification.
# Use the Theobald hm data and stack with elevation and slope calculated above.
ei_topo <- c(ei, elvPRJ, slp)
ei_topoDF <- as.data.frame(ei_topo, xy = T) %>% sample_n(1000)
names(ei_topoDF) <- c("x", "y", "ei", "elev", "slope")
# create the plot of elevation and ecological integrity
# This will produce a scatter plot showing ecological integrity on the y-axis and elevation on the x-axis.
ei_topoDF %>% ggplot(aes(x = elev, y = ei)) + geom_point(alpha = 0.5) + theme_bw()

TASK 2.
More rigorously explore the relationships between ecological integrity and topography (elevation and slope). What kind of analysis could you use for hypothesis testing here (hint: what did we use when the scatter plot looks like a piece of pie?)? Interpret the results. What is driving the patterns? What are the ecological and conservation consequences? Re-run the global and local Moran’s I and produce a correlogram of elevation. Compare patterns of spatial autocorrelation with those we produced for ecological integrity. Which patterns are more randomly distributed and which patterns are more spatially clumped? What are the causes and consequences of these patterns? Write up your results as an abstract for Landscape Ecology.
Theobald’s Global Human Modification data: https://zenodo.org/records/14502573
---
title: "Lab 8. Ecological Integrity"
subtitle: "Spatial autocorrelation and Moran's I"
---
::: {.callout-note appearance="minimal"}
**Data for this lab.**
Download `Lab8.zip` from the [course data archive on Zenodo](https://doi.org/10.5281/zenodo.22101926) and unzip it into a folder called `data/Lab8/` in your project directory.
:::
# Background
“A thing is right when it tends to preserve the **integrity**, stability and beauty of the biotic community. It is wrong when it tends otherwise.” - Aldo Leopold
The concept of ecological integrity is pervasive in global conservation targets and U.S. federal policy. The first two targets of the Global Biodiversity Framework outline the importance of protecting "ecosystems of high ecological integrity". The Clean Water Act, National Wildlife Refuge System Improvement Act of 1997, U.S. Forest Service's 2012 Planning Rule, and the Bureau of Land Management's (BLM) Fundamentals of Rangeland Health, among other laws and regulations reference the importance of maintaining or restoring ecological integrity.
As an example, the Forest Service's 2012 Planning Rule requires that forest plans "must include plan components... to maintain or restore the ecological integrity of terrestrial and aquatic ecosystems." Ecological integrity is defined here as "the quality or condition of an ecosystem when its dominant ecological characteristics (for example, **composition**, **structure**, **function**, connectivity, and species composition and diversity) occur within the natural range of variation and can withstand and recover from most perturbations imposed by natural environmental dynamics or human influence."
{fig-align="center"}*Conceptual framework of ecological integrity (composition, structure, function). Credit: Lucy Poley, Wildlife Conservation Society Canada. Used with permission.*
The concept of ecological integrity is similar to the concept of ecological intactness. Often, integrity and intactness are used synonymously. One of the requirements of BLM's Public Lands Rule is to "Protect the most intact, functioning landscapes."
Clearly, policy makers understand that "integrity" is important to maintain or restore, and various definitions of integrity have been presented. However, there is no "integrity-meter" that measures an unambiguous attribute of landscapes. Most scholars understand integrity to be assessed using multiple criteria.
In the last several years numerous efforts have used spatial data on roads, land cover, light pollution, transmission lines, and other mapped features that represent a degree of human modification as a composite index. The Human Footprint, global map of human modification, and other spatial data have been produced that assume that land use and development represent stressors that can alter the ecological composition, structure, and function (i.e., ecological integrity).
Image below illustrates how multiple datasets are combined to map the Human Modification ([Theobald et al. 2025](https://www.nature.com/articles/s41597-025-04892-2)), which has been associated with ecological integrity.
*The Human Modification Framework, showing data curation, spatial modeling, and integration into a global Human Modification index. Credit: Katie Walker, The Nature Conservancy. Used with permission.*
Here, we will evaluate the human modification dataset that has been used to map lands of high integrity (i.e., intact landscapes). We will explore the spatial patterns of these datasets using spatial statistics (e.g., Moran's I) and investigate how ecological integrity varies with topography and among regions of Montana, Idaho, and Wyoming. Spatial patterns in human modification and ecological integrity may tell us whether the underlying patterns are random or clumped in a similar way to topography, soils, or other factors that influence where humans develop lands, build roads, or otherwise modify landscapes. We will only scratch the surface here. The goals of this lab are (1) to introduce you to the multiple criteria that have been used to measure and map ecological integrity and (2) to demonstrate how spatial statistics can be used with these kinds of data.
## Theobald's human modification data and ecological integrity
A widely used dataset to represent ecological integrity is David Theobald and colleagues' map of [human modification](https://www.nature.com/articles/s41597-025-04892-2). Theobald and colleagues combined mapped features that represent ecological stressors including land cover conversion, roads, mining activity, human population density, and other criteria that represent ways that humans alter natural ecosystems. The combination of these criteria has been used as a composite map of human modification or the inverse, ecological integrity. The data have been used to map the Earth's remaining [intact landscapes](https://scholar.law.colorado.edu/cgi/viewcontent.cgi?article=1560&context=celj) (wildlands or wilderness), as the basis for [connectivity modeling](https://link.springer.com/article/10.1007/s10980-022-01530-9), and as a general map of [ecological integrity](https://link.springer.com/article/10.1007/s10980-013-9941-6).
*The Global Map of Human Modification. Credit: Katie Walker, The Nature Conservancy. Used with permission.*
We will explore global and local Moran's I using the composite map of ecological integrity. This approach will be used to ask questions such as "how clumped are lands of high ecological integrity across Montana, Idaho, and Wyoming based on the different features that may disrupt ecological integrity?"
```{r}
# Load packages (install if you need to)
library(terra)
library(sf)
library(mapview)
library(pals)
library(viridis)
library(tidyverse)
library(ggridges)
library(ncf)
```
```{r}
# Bring in human modification-based map of ecological integrity
ei <- rast("data/Lab8/hm_MTIDWY.tif")
# Look at a map of ecological integrity (i.e, the opposite of human modification)
# This will show human modification for Montana, Idaho, and Wyoming. You can see the interstate highways and regions of agriculture as bright yellow and large wildlands as black regions.
plot(ei, col = rev(magma(50)), axes = F)
```
### Assessing ecological integrity among ecoregions using "ridgeline" plots
Before we explore the spatial autocorrelation of ecological integrity and consider what these patterns mean, let's summarize the patterns among ecoregions of Montana, Idaho, and Wyoming. First, we'll bring in the ecoregion polygons, `rasterize` them, stack the ecoregions with the ecological integrity, turn the stack into a dataframe, and plot kernel density plots (i.e., "smoothed" histograms) for each ecoregion (in a visualization sometimes called "ridgeline" plots).
```{r}
# read in the ecoregions for Montana, Idaho, and Wyoming
ecoregions <- vect("data/Lab8/ecoregions_MTIDWY.shp")
# look at the map of ecoregions
# This shows a map of ecoregions in Montana, Idaho, and Wyoming.
plot(ecoregions)
# Look at the names. We will want this when we rasterize the polygons
names(ecoregions)
# Turn the ecoregion polygons into a raster using rasterize
# make the cell size, crs, and extent match the ecological integrity ("ei") data
# and assign the pixels the ecoregion names in the field "US_L3NAME"
ecoRaster <- ecoregions %>% rasterize(ei, field = "US_L3NAME")
# Look at this map
# This shows a map of ecoregions in Montana, Idaho, and Wyoming.
plot(ecoRaster)
# Stack this rasterized ecoregions with the ecological integrity data
ei_ecoregion <- c(ei, ecoRaster)
# Look at the maps
# This shows a map of human modification and ecoregions in Montana, Idaho, and Wyoming.
plot(ei_ecoregion)
# Let's rename the layers in the stack
names(ei_ecoregion) <- c("ei", "ecoregion")
# We will turn these two rasters into a dataframe keeping the coordinates (xy = T)
ei_ecoregionDF <- as.data.frame(ei_ecoregion, xy = TRUE)
# look at the top of the dataframe
head(ei_ecoregionDF)
# We will use some special plotting features in "ggridges" for this plot.
# This shows a map of plot of smoothed histograms of ecological integrity by ecoregions in Montana, Idaho, and Wyoming.
ei_ecoregionDF %>% drop_na() %>% group_by(ecoregion) %>%
sample_frac(0.1) %>% ungroup() %>%
ggplot(aes(x = ei, y = fct_reorder(factor(ecoregion), ei, .fun = mean))) +
geom_density_ridges() +
xlab("Ecological Integrity") + ylab("Ecoregion")+
guides(fill = FALSE)+
theme_classic() + theme(text = element_text(size = 14))
# Let's use a color scheme that we could match with our maps.
# This shows a map of plot of smoothed histograms of ecological integrity by ecoregions in Montana, Idaho, and Wyoming.
ei_ecoregionDF %>% drop_na() %>% group_by(ecoregion) %>%
sample_frac(0.1) %>% ungroup() %>%
ggplot(aes(x = ei, y = fct_reorder(factor(ecoregion), ei, .fun = mean))) +
geom_density_ridges_gradient(aes(fill = after_stat(x))) +
scale_fill_viridis_c(option = "magma", direction = -1) +
xlab("Ecological Integrity") + ylab("Ecoregion")+
guides(fill = FALSE)+
theme_classic() + theme(text = element_text(size = 14))
```
Look at the ridgeline plots of ecological integrity for each ecoregion. Which ecoregions have the highest ecological integrity? Why?
We will now explore the geographic distribution of ecological integrity using spatial statistics.
### Spatial autocorrelation in ecological integrity
One of the first laws of geography is that things closer together tend to be more alike than things further apart. I'm paraphrasing Tobler's Law. In ecology, we say that things we measure are often spatially correlated, or that there is spatial autocorrelation in the data (variables are correlated with themselves across geographic space). Observing and quantifying this autocorrelation can reveal important spatial patterns and processes (e.g., species dispersal and colonization) and may also be essential for adhering to the statistical assumption that samples are independent. In other words, if you sample in a way where a variable shows strong spatial autocorrelation, you may not be able to count those observations as truly independent. This can mess up our inference when conducting hypothesis testing and must be addressed. Here, we will focus on assessing spatial autocorrelation to quantify spatial patterns in continuous data on ecological integrity. Assessing these patterns may provide insights into landscapes that maintain their integrity and those that have impaired integrity.
We will use Moran's I to do this. Put simply, Moran's I is analogous to a correlation coefficient assessing how one variable is correlated with itself across geographic space. In fact, the formula for Moran's I is very similar to the formula to calculate a correlation coefficient and can be interpreted similarly. The higher Moran's I, the stronger the spatial autocorrelation. Take, for example, the simulated landscapes below. I have included Moran's I above each map. The closer the patterns become to random (i.e., uncorrelated) the lower Moran's I is. These values are called "global" Moran's I and provide one number to quantify the entire landscape.
{fig-alt="Grid of six spatial raster images illustrating decreasing spatial autocorrelation, each labeled with its Moran's I value, using a dark purple-to-yellow color scale from 0 to above 0.80. Top row, left to right: Moran's I = 0.9997 shows smooth, large-scale gradients with a distinct dark patch on the left transitioning to bright yellow on the right; Moran's I = 0.9985 shows similarly smooth patterns with slightly more texture; Moran's I = 0.9687 shows finer-grained but still clearly clustered patches of color. Bottom row, left to right: Moran's I = 0.8356 shows more fragmented, mottled patterns with smaller clusters; Moran's I = 0.317 shows mostly fine-grained speckled texture with only faint large-scale structure; Moran's I = -0.00013 shows completely random speckled noise with no discernible spatial pattern. The sequence demonstrates how spatial autocorrelation decreases from strong clustering to complete spatial randomness."}
You can also calculate "local" Moran's I and assess how the spatial autocorrelation changes with distance between observations. We can map local spatial correlation like below. Higher local autocorrelation is in yellow.
{fig-alt="Grid of six spatial raster maps showing local Moran's I values, each labeled with its corresponding global Moran's I statistic, using a dark purple-to-yellow (viridis) color scale with a different range for each panel. Top row, left to right: Moran's I = 0.9997 shows smooth clusters of high local Moran's I (yellow-green, up to 5.0) against a low-value background (dark purple), with one prominent bright cluster in the upper right; Moran's I = 0.9985 shows a similar smooth clustered pattern with values up to 6.0 and multiple bright clusters; Moran's I = 0.9687 shows finer-grained but still clustered high-value patches, with values up to 8-9. Bottom row, left to right: Moran's I = 0.8356 shows more fragmented clusters of high local Moran's I (up to 12) amid a low, uniform background; Moran's I = 0.317 shows sparse, faint patches of elevated values (up to 8) against a mostly uniform teal background with little structure; Moran's I = -0.00013 shows a uniform, fine-grained speckled pattern with a narrow value range (-2 to 2) and no discernible spatial clustering. The sequence illustrates how local indicators of spatial association weaken and lose spatial structure as global spatial autocorrelation decreases"}
And we can plot how autocorrelation changes with distance using plots known as correlograms. Correlograms are closely related to "variograms" or "semivariograms", but show the opposite patterns (i.e., how dissimilarity increases with distance). Correlograms can be useful in understanding the spatial scale driving a process, helping to decide on an appropriate grain or resolution to use in predictive modeling, aiding a field study to avoid spatial autocorrelation (i.e., how far apart should you put plots so that data are not spatial autocorrelated?). Here, we will use correlograms to understand the spatial extent of patterns in ecological integrity. The examples below show the correlograms associated with the maps above. Again, as the patterns become more random the correlation of observation closer together approaches 0.
{fig-alt="Grid of six correlograms showing spatial correlation as a function of distance, each with an inset thumbnail of the corresponding raster surface and labeled with its Moran's I value. Each panel plots correlation (y-axis, -1 to 1) against distance in mean-of-class units (x-axis, 0 to 1400), with a dashed horizontal line at zero. Top row, left to right: Moran's I = 0.9997 shows correlation starting near 1.0 at short distances and declining steadily to about -1.0 near 1100-1200, with a slight uptick at the farthest distances; Moran's I = 0.9985 shows a similar steady decline from near 1.0 to about -1.0; Moran's I = 0.9687 shows a comparable but slightly noisier decline from about 0.9 to -1.0. Bottom row, left to right: Moran's I = 0.8356 shows a decline starting lower, around 0.6, dropping to about -0.8 with more scatter; Moran's I = 0.317 shows a much flatter, near-zero correlation across all distances with only slight negative drift; Moran's I = -0.00013 shows correlation hovering right around zero across all distances with no discernible trend. The sequence illustrates how spatial correlation structure — strong at short distances and negative at long distances — weakens and disappears as global Moran's I decreases toward zero."}
We will first calculate the global Moran's I, which is quite easy in R. The package `terra` has a function called `autocor` that allows you to do this.
Then, we will calculate and map local Moran's I.
```{r}
# Calculate global Moran's I for entire raster
ei_global_I <- autocor(ei, global = TRUE, method = "moran")
ei_global_I
# Calculate Local Moran's I
ei_local_I <- autocor(ei, global = FALSE, method = "moran")
# Look at the map of local Moran's I.
plot(ei_local_I, axes = F)
```
Now, let's create a correlogram to investigate how spatial autocorrelation varies with distance, as I have done above for the simulated landscapes.
```{r}
set.seed(3950)
# We need to make the raster a dataframe
eidf <- ei %>% as.data.frame(xy = T) %>% sample_n(1000)
# adjust the names
names(eidf) <- c("x", "y", "ei")
# run the correlogram from the package ncf
# increment = 25000 (meters) is the distance "bins" used to calculate
# autocorrelation at different distances.
cor_int <- ncf::correlog(x = eidf$x, y = eidf$y, z = eidf$ei,
increment = 25000, resamp = 0, na.rm = TRUE)
# look at the output called "cor_int"
cor_int
# Notice some distances have VERY few observations!
```
Now, let's produce the correlogram using the output we created above. The `type = "b"` and `pch = 19` are just graphing options (`type = b` is connecting dots with lines and `pch = 19` tells R we want our points to be filled circles. We're also dividing the "mean of class" by 1000 so that the units are in kilometers and not meters. `abline` just adds a hashed line to the plot at 0, so there's a clear indication of where we lose any spatial autocorrelation.
```{r}
# Plot the output of the correlogram using base R
# "mean of class" is the mean distances. Let's divide those by 1000 so that the
# units are in km and not meters
plot(cor_int$mean.of.class / 1000, cor_int$correlation,
type = "b", pch = 19, ylim = c(-1,1),
xlab = "Distance (km)", ylab = "Moran's I")
abline(h = 0, lty = 2, col = "grey50")
```
Look back at the map of ecological integrity as measured by Theobald's human modification, and study the correlogram. What does the plot tell you about the spatial 'clumpiness' of areas of high human modification or high ecological integrity? What are the causes and consequences of these patterns?
Let's bring in the inputs to human modification and evaluate the spatial autocorrelation in each of the criteria.
```{r}
# list of the files with the extension of "tif" and return the full file names.
ei_input_files <- list.files("data/Lab8/MTIDWY",
pattern = ".tif$", full.names = TRUE)
# look at these filenames.
ei_input_files
# Now, stack the rasters up.
ei_inputs <- rast(ei_input_files)
```
These inputs include two letter codes, which are described below. Look over this list and consider how these "threat types" might impact ecological integrity. Again, consider ecological integrity as a quality of ecosystems and landscapes related to the composition, structure, and function. How might each of these threats affect integrity and in what ways? What is missing?
| Code | Threat Type | Description |
|----|----|----|
| **AA** | All threats combined | Composite index integrating all human modification pressures. |
| **AG** | Agriculture | Areas modified by crop cultivation, pasture, or other agricultural use. |
| **BU** | Built environments | Residential, commercial, and recreational development. |
| **EX** | Energy production and mining | Land modified for oil, gas, coal, wind, solar, or mineral extraction. |
| **FR** | Biological resource use | Areas affected by forestry, logging, or other extraction of biological resources. |
| **HI** | Human accessibility | Modification due to proximity to human access (e.g., roads, trails, settlements). |
| **NS** | Natural systems modification | Alterations of natural processes such as dams, water diversion, or fire suppression. |
| **PO** | Pollution | Areas influenced by chemical, nutrient, or other pollution sources. |
| **TI** | Transportation and service corridors | Roads, railways, powerlines, pipelines, and other linear infrastructure. |
Now, let's look at the maps of each of these threats or stressors.
```{r}
# Look at the maps of the inputs to human modification
plot(ei_inputs)
```
::: {.callout-tip appearance="minimal"}
**TASK 1.**
Look at the patterns in the maps for the inputs to human modification. Re-run the global and local Moran's I for **at least 3** of the inputs and produce the correlogram. Compare the values and maps of the three criteria in relationship to how (and why) humans modified lands and whether the modification is spatially aggregated or more randomly distributed. Compare your correlograms to the ones I created with the simulated landscapes above. What do you think the ecological consequences of these different patterns are for ecological integrity? Include the maps and plots in a multi-panel figure with a descriptive caption, report the global Moran's I in the caption, and describe the patterns. Write up your results as an abstract for *Landscape Ecology*.
:::
# Ecological integrity and topography.
Now, let's investigate whether human modification and ecological integrity vary with topography, namely elevation and slope steepness. We will first bring in elevation, project it to match the human modification data, and calculate slope using the `terrain` function.
```{r}
# Bring in elevation data (a digital elevation model)
elv <- rast("data/Lab8/elev_MTIDWY.tif")
# match the projection to the human modification data
elvPRJ <- project(elv, ei, method = "bilinear")
# Look at the elevation map, which is always pretty cool for this region.
plot(elvPRJ, axes = F)
# calculate the slope and plot it
slp <- terrain(elvPRJ, "slope")
# This will show a plot of slope for Montana, Idaho, and Wyoming.
plot(slp, axes = F)
```
Now, we will create a raster stack of ecological integrity, elevation, and slope. We will turn this raster stack into a dataframe, and use `ggplot` to investigate the relationship between elevation and slope and human modification.
```{r}
# Use the Theobald hm data and stack with elevation and slope calculated above.
ei_topo <- c(ei, elvPRJ, slp)
ei_topoDF <- as.data.frame(ei_topo, xy = T) %>% sample_n(1000)
names(ei_topoDF) <- c("x", "y", "ei", "elev", "slope")
# create the plot of elevation and ecological integrity
# This will produce a scatter plot showing ecological integrity on the y-axis and elevation on the x-axis.
ei_topoDF %>% ggplot(aes(x = elev, y = ei)) + geom_point(alpha = 0.5) + theme_bw()
# create the plot of slope steepness and ecological integrity
# This will produce a scatter plot showing ecological integrity on the y-axis and slope steepness on the x-axis.
ei_topoDF %>% ggplot(aes(x = slope, y = ei)) + geom_point(alpha = 0.5) + theme_bw()
```
::: {.callout-tip appearance="minimal"}
**TASK 2.**
More rigorously explore the relationships between ecological integrity and topography (elevation and slope). What kind of analysis could you use for hypothesis testing here (hint: what did we use when the scatter plot looks like a piece of pie?)? Interpret the results. What is driving the patterns? What are the ecological and conservation consequences? Re-run the global and local Moran's I and produce a correlogram of elevation. Compare patterns of spatial autocorrelation with those we produced for ecological integrity. Which patterns are more randomly distributed and which patterns are more spatially clumped? What are the causes and consequences of these patterns? Write up your results as an abstract for *Landscape Ecology*.
:::
# Data source(s)
Theobald's Global Human Modification data: <https://zenodo.org/records/14502573>