27 Ordination
27.1 Introduction
Humans are visual creatures, relying much more on their sense of vision than other senses like smell for understanding the world. When’s the last time you smelled a dataset?
Unfortunately, humans are also creatures of 3 spatial dimensions, and that severely limits our ability to “see” patterns in data. Even if patterns in data might exist clearly in 4 or 5 dimensions, our primate brains just won’t see those patterns. Instead, we need ways to bring those high-dimensional patterns down to 3 or fewer. Or, ways to bring 3 dimensional patterns down to 1 or 2, for ease of interpretation. These practices all fall under the umbrella of dimension reduction. One very powerful set of techniques for dimension reduction is ordination. A good ordination will reveal previously unseen (or unseeable) patterns in data, allow cluster identification, or even show gradients in the data that researchers didn’t know they were looking for.
Ordination is literally ordering observations along two or more axes. We put observations in order by translating them into a new coordinate system. How that translation is done varies wildly among ordination techniques. No matter how they work, all ordination methods have the same goal: representing patterns in fewer dimensions than there are variables. This makes ordination an approach to exploratory data analysis. Most ordination techniques allow to better see patterns, but they are not inferential tests themselves.
The applications of ordination overlap with those of the multivariate techniques that we have already seen:
- Dimension reduction: Summarizing variation across many variables using a smaller number of synthetic axes, making complex multivariate datasets easier to visualize and interpret.
- Gradient discovery: Identifying major patterns of variation among observations, which may represent underlying biological or environmental gradients.
- Group identification: Visualizing similarities and differences among observations, including identifying potential clusters of observations that share similar characteristics.
These goals are not mutually exclusive. Dimension reduction is accomplished by finding gradients in the data that are not necessarily equivalent to any of the original variables. The first is what ordination does mathematically; the second is often what we hope to find biologically. Group identification can occur when we find observations forming clusters in an ordination plot, which is itself created by plotting observations against the latent gradients identified by the algorithm. The connection to clustering from the previous chapter should be obvious.
27.1.1 Ordination terminology
Ordination is a very different approach to statistics than we have seen so far in this course. We have largely stepped outside of the world of modeling and hypothesis testing, because most ordination methods are not hypothesis tests. But, we are still using many of the building blocks of inferential statistics that we have already learned. For example, the concepts of variance and covariance are of central importance in many ordination techniques.
One of the biggest changes is that we need to start thinking of variables as being equivalent to axes. This is directly related to the notion of (spaces and coordinate systems)[#sec-diss-space-coord] that we explored in Chapter 25. The dataset defines one coordinate systemThis is somewhat similar to how in Chapter 25 we started thinking of observations as equivalent to vectors.
27.1.2 Types of ordination
There are many methods of ordination, which differ in how they construct ordination axes and what kinds of patterns they are designed to reveal. We can classify these methods in two ways: whether the ordination is constrained by explanatory variables, and how the ordination axes are calculated.
27.1.2.1 Constrained vs. unconstrained ordination
In unconstrained ordination, the axes are calculated from the variation among observations without using external explanatory variables. For example, we might use measurements of several morphological traits to ordinate specimens, allowing us to identify major patterns of morphological variation. We could then investigate whether those patterns correspond to differences among species, habitats, or other characteristics. Figure 27.2 below shows how an unconstrained ordination is constructed using the A-E-S matrix schema that we saw in Section 24.2.
In constrained ordination, the axes are constructed to represent variation associated with one or more explanatory variables. For example, we might use environmental variables such as temperature, precipitation, and elevation to explain variation in species composition across sites. Rather than simply finding the major patterns of variation in species composition, constrained ordination focuses on the portion of that variation that can be explained by the environmental variables.
Constrained ordination is often called canonical ordination, particularly in ecology. The term canonical refers to mathematical methods that identify relationships between sets of variables, as in canonical correlation analysis. In ecological applications, canonical ordination generally refers to methods that construct ordination axes using explanatory variables. However, the term has a broader mathematical meaning and is not always synonymous with constrained ordination.
27.1.2.2 Eigenanalysis vs. optimization
Ordination methods also differ in the mathematical procedures used to construct their axes.
Some methods, including principal components analysis (PCA) and principal coordinates analysis (PCoA), use eigenanalysis: mathematical procedures that decompose a matrix into eigenvalues and eigenvectors. In linear algebra, an eigenvector is a vector whose direction is not changed by a linear transformation. An eigenvalue describes how an eigenvector is scaled by the transformation (see this video for visual explanation). Mathematically, we can write
\[\mathbf{A}\vec{v}=\lambda\vec{v}\]
where \(\mathbf{A}\) is the matrix that describes a linear transformation, \(\vec{v}\) is an eigenvector, and \(\lambda\) is an eigenvalue. Again, go watch this video.
In Figure 27.1, the red vectors in the center panel are the eigenvectors which will define the axes of the ordination space. An The eigenvectors are used to construct ordination axes, while the eigenvalues describe the amount of variation represented by those axes. These methods generally produce a solution directly through matrix calculations.
Other methods use numerical optimization, an iterative process that searches for a configuration of observations that best satisfies a particular criterion. For example, nonmetric multidimensional scaling (NMDS) arranges observations in a low-dimensional space so that the ranked distances between observations correspond as closely as possible to their ranked dissimilarities in the original dataset. The algorithm repeatedly adjusts the positions of observations to minimize a measure of disagreement called stress.
Both approaches produce ordinations, but they differ in what their axes represent and how faithfully they preserve relationships in the original dataset. In methods such as PCA, the ordination axes are calculated as linear combinations of the original variables, allowing us to interpret each axis in terms of those variables. Other eigenanalysis methods, such as PCoA, derive their axes from a distance matrix rather than directly from the original variables.
In optimization-based methods such as NMDS, the axes do not have a direct mathematical relationship with the original variables. Instead, the objective is to arrange observations so that distances between them in the ordination space reproduce the ranked dissimilarities in the original dataset as closely as possible. Consequently, an NMDS configuration can be rotated or reflected without changing its meaning, because the relationships among observations remain unchanged. In fact, in vegan::metaMDS(), which performs NMDS, the default post-processing includes rotating the configuration so that its first axis aligns with the direction of maximum variance. Although an eigenanalysis-based configuration can also be rotated, doing so generally changes the mathematical interpretation of its axes. For example, rotating a PCA configuration would mean that the first axis no longer necessarily represents the direction of maximum variance.
| Method | Constrained? | Main computational approach |
|---|---|---|
| Principal components analysis (PCA) | No | Eigenanalysis / SVD |
| Principal coordinates analysis (PCoA) | No | Eigenanalysis |
| Nonmetric multidimensional scaling (NMDS) | No | Iterative optimization |
| Redundancy analysis (RDA) | Yes | Regression + eigenanalysis |
| Canonical correspondence analysis (CCA) | Yes | Weighted regression + eigenanalysis |
| Distance-based redundancy analysis (dbRDA) | Yes | Distance-based eigenanalysis + regression |
| Linear discriminant analysis (LDA) | Yes | Generalized eigenanalysis |
27.2 Principal components analysis (PCA)
27.2.1 Introduction
The first and probably most commonly used ordination technique is principal component analysis (PCA). It works by finding synthetic gradients that capture most the variation between the observations more efficiently than the original variables. These gradients are calculated by finding linear combinations of the variables. These combinations really define a rotation, a kind of linear transformation, of the the original coordinate system. There are an infinite number of ways that we could apply a linear transformation to the data; the principal components are just the eigenvectors of the transformation captures the greatest variance on the first axis; the second greatest variance on the second axis, and so on.
27.2.2 What PCA does
To get an intuitive understanding of PCA, work through it using an imaginary dataset with two variables, Variable 1 and Variable 2. You could capture and display all the information about this dataset in a 2-d scatterplot, by simply plotting one variable against the other. Likewise, you could capture and display all of the information about a 3-dimensional dataset with a 3-d plot. For 4 or more dimensions, a true scatterplot can’t be rendered sensibly or even understood by our meat-based brains.
One way to describe the variation among the observations in Figure 27.4 is to think about how the samples vary along each axis. The figure below shows how the variation among samples can be broken down into the variation in Variable 1 and the variation in Variable 2. When we say “variation in variable 1”, we mean “deviation between the values of variable 1 and the mean of variable 1”. That is what is shown in Figure 27.5 below.
- Each point, or sample, has a Variable 1 coordinate and a Variable 2 coordinate.
- Each point’s value for Variable 1 can be thought of as the difference between that value and the mean of Variable 1.
- Likewise, each point’s value for Variable 2 can be thought of as the difference between that value and the mean of Variable 2.
- The position of each point can thus be reframed as its deviation with respect to the Variable 1, and its deviation with respect to Variable 2. This reframing is the same as centering each variable (i.e., subtracting the mean).
- The total variance among the samples is equal to the variance with respect to Variable 1 plus the variance with respect to Variable 2.
Figure 27.5 above shows how the total variation in the dataset is split up (“partitioned”) into variation in Variable 1 and variation in Variable 2.
Describing each observation as its deviation from the mean of each variable has the effect of centering the points at the origin. Notice that the variation, expressed as sums of squared deviations, is unchanged (Figure 27.6).
Figure 27.6 below shows the data as deviations from the means of each variable. Notice that the variation is each direction is unchanged from Figure 27.5.
Next, we standardize each variable to have a variance of 1. This means that the original values are converted to Z-scores by subtracting the mean and dividing by the SD (i.e., they are z-scaled). Recall from Section 11.4.1 that the z-score of an observation \(x\) is
\[z\left(x\right)=\frac{x-\mu}{\sigma}\]
Doing PCA without standardizing variables will distort the results because each variable’s importance in the PCA will depend on its magnitude, not its relationship to other variables. Standardization puts variation along any axis on equal footing. Figure 27.7 shows the data as deviations from the variable means after standardization. Compare this figure to Figure 27.6 above. All that changed are the axis scales and the sum of squared deviations. Note that the sums of squares are equal for both variables now.
The goal of PCA is to find a new coordinate system that puts the most variance possible on its first axis, then the second most variance on its second axis, and so on. This new coordinate system will have the same number of dimensions as the original dataset. But whereas in the standardized dataset all variables (axes) have the same amount of variation associated with them, in the PCA coordinate system some axes will explain more variation than others.
The variation among the observations is defined in terms of Variable 1 and Variable 2, and Variable 1 and Variable 2 contributed equally to the total variation. But, we could describe most of the variation between points with just one variable, or axis, the red line (Figure 27.8). Any remaining variation will be in the direction perpendicular to the red axis, the blue axis (dashed line).
The red axis is a vector that contains information about both Variable 1 and Variable 2. It is tricky, but not too hard, to calculate each observation’s deviations from the mean of the red axis (left panel below) (Figure 27.9). We can also calculate the deviations along a perpendicular vector, because even after describing the variation in the red direction, there is still some variation in the blue direction (right panel).
We know that the variation along the red and blue axes is the same as the variation on the Variable 1 and Variable 2 axes, because the sums of squares are the same (\(76.6 + 21.4 = 49 + 49\)) . The red and blue axes are just different ways of orienting the data to express the same patterns. All we really did was rotate the original coordinate system (defined by Variables 1 and 2) to a new coordinate system (Figure 27.10).
27.2.3 Example using vegan
27.2.3.1 Data import and preparation
For an example PCA analysis, let’s revisit the small mammal measurement data from Section 26.2.2. Download the individual measurement dataset and the taxonomic dataset and put them in your working directory.
tax <- read.csv("data-neon-taxa.csv")
ind <- read.csv("data-neon-ind-meas.csv")We are going to use PCA to explore variation in small mammal morphology. First we need to organize the data. Cut the measurement data down to just the columns we need: individual, species, body mass, and the four standard measurements.
use.cols <- c("tagID", "abb", "totalLength",
"tailLength", "hindfootLength",
"earLength", "weight")
dx <- ind[,use.cols]
# only want individuals with no missing measurements
dx <- dx[complete.cases(dx),]How many individuals do we have of each species?
rev(sort(table(dx$abb)))
Pergos Perboy Perman Perleu Musmus Reimeg Chapen Onyleu Ratrat Dipord
1486 745 704 634 390 320 294 273 258 203
Reimon Perfla2 Pertru Myorut Chahis Sorcin Perpar Chabai Micoec Dipmic
185 170 110 86 79 51 41 35 34 29
Sighis Chacal Chaint Reiful Micoch Onytor Micpen Ochnut Tammin Icttri
28 27 26 25 25 23 22 18 17 17
Neoflo Perpol Peratt Neoalb Micmon Sortun Onyare Miclon Perere Orypal
15 14 14 14 14 13 12 12 10 10
Lemtri Lemcur Sormon Perino Zaphud Permer Perfla1 Dipmer Sigoch Podflo
9 9 7 7 6 6 6 6 5 5
Myogap Micpin Tamstr Neomex Zappri Xerspi Sigari Reihum Peramp Baitay
5 5 4 4 3 3 3 3 3 3
Tamspe Tamruf Tamamo Percri Napins Micxan Micmiu Xerter Tamhud Sorhoy
2 2 2 2 2 2 2 1 1 1
Ratnor Pernas Perlon Percal Neomic Neomac Miccal
1 1 1 1 1 1 1
There is quite a wide range of numbers of individuals between species. To prevent the species with many individuals from having too much influence over the analysis, let’s randomly select 50 individuals from every species with at least 50 individuals. That will give us 16 species. Note that this is not what we would do in a real analysis. Instead, this is just a strategy to make the ordination easier to understand as a teaching example. If you want to do the example with all individuals, just uncomment the line indicated below.
set.seed(7410)
sp <- names(which(table(dx$abb) >= 50))
out <- vector("list", length(sp))
for (i in seq_along(sp)) {
d <- dx[dx$abb == sp[i], ]
out[[i]] <- d[sample(nrow(d), 50), ]
}
dx.pca <- do.call(rbind, out)
# if you want to try the analysis with all
# of the species, uncomment and run this line:
#dx.pca <- dx
dx.pca <- merge(dx.pca, tax[,c("abb", "species", "family")])
table(dx.pca$species)
Chaetodipus hispidus Chaetodipus penicillatus Dipodomys ordii
50 50 50
Mus musculus Myodes rutilus Onychomys leucogaster
50 50 50
Perognathus flavus Peromyscus boylii Peromyscus gossypinus
50 50 50
Peromyscus leucopus Peromyscus maniculatus Peromyscus truei
50 50 50
Rattus rattus Reithrodontomys megalotis Reithrodontomys montanus
50 50 50
Sorex cinereus
50
How many families do we have, and how many specie each?
table(dx.pca$family)
Cricetidae Heteromyidae Muridae Soricidae
450 200 100 50
27.2.3.2 Fit the PCA
We will use package vegan for ordination. Load it and run the PCA. We will leave body mass out of the ordination for now…that will be important later.
Use argument scale=TRUE to standardize the variables first. The default in vegan::pca is to not scale the variables, because that usually isn’t necessary (or even sensible) with the default distance measure.
library(vegan)
pca.cols <- c("totalLength", "tailLength",
"hindfootLength", "earLength")
p1 <- pca(dx.pca[,pca.cols], scale=TRUE)
summary(p1)
Call:
pca(X = dx.pca[, pca.cols], scale = TRUE)
Partitioning of correlations:
Inertia Proportion
Total 4 1
Unconstrained 4 1
Eigenvalues, and their contribution to the correlations
Importance of components:
PC1 PC2 PC3 PC4
Eigenvalue 3.0109 0.6850 0.24573 0.05835
Proportion Explained 0.7527 0.1713 0.06143 0.01459
Cumulative Proportion 0.7527 0.9240 0.98541 1.00000
The result shows us that PC1 explains about 75.3% of the variation in measurements. PC2 adds another 17.1%. Just the first two PCs account for 92.4% of the variation. Because we are ordinating on measurements, and the first PC captures a large percentage of the variation, there is a good chance that the first PC is capturing a size gradient (as we saw in Figure 26.10).
27.2.3.3 Plot the PCA
The plot and biplot methods for pca objects will produce a quick graph, but it’s not very helpful. I prefer to extract the useful parts of the results and build a plot using base graphics.
What we need are the PC scores of the observations and the biplot arrows of the original variables. The “scores” are what we call the coordinates in the PC coordinate system. The positions of the observations in the ordination space reflect their similarity and dissimilarity relative to each other. The biplot arrows start at the origin and show the relationship between the original variables and the ordination space. You can think of them as the “shadows” you would get if you projected the original axes onto the plane of the figure (remember that we obtained the PCA space by rotating the original space).
First, let’s assign some colors and shapes to the species and families. This will help us make sense of the ordination plot.
spps <- sort(unique(dx.pca$species))
fams <- sort(unique(dx.pca$family))
col.spps <- hcl.colors(length(spps), palette = "Dark 3")
col.fams <- hcl.colors(length(fams), palette = "Dark 3")
pch.fams <- 15:18
names(col.spps) <- spps
names(col.fams) <- fams
names(pch.fams) <- famsNext, we extract the scores of the observations. The ordination scores can be calculated in one of two ways, referred to as scaling (see Section 27.2.3.3.1). For examining clusters of observations, we should use scaling 1. The function scores() will extract the scores we need. Note that in ordination functions in package vegan, observations are always referred to as sites, and variables as species. This is a result of the origin of vegan in community ecology.
# extract scores with scaling 1
xy.samp1 <- scores(p1, display="sites",
choices=1:2, scaling=1)
xy.vars1 <- scores(p1, display="species",
choices=1:2, scaling=1)
par(mar=c(5,5,7,1), bty="n", xpd=NA)
plot(xy.samp1[,1], xy.samp1[,2],
pch=pch.fams[dx.pca$family],
col=col.spps[dx.pca$species],
xlab="PC1 (75.3%)", ylab="PC2 (17.1%)")
# shorten the biplot vectors to fit on the plot area
scal <- 0.04
segments(0, 0, scal*xy.vars1[,1], scal*xy.vars1[,2], lwd=2)
# move the biplot labels out by 2%
moveout <- 1.02
text(moveout*scal*xy.vars1[,1], moveout*scal*xy.vars1[,2],
rownames(xy.vars1), cex=1.2)
legend(-0.9, 0.45, legend=spps,
col=col.spps,
pch=pch.fams[tax$family[match(spps, tax$species)]],
ncol=3,
text.font=3, bty="n")
Figure 27.11 shows that many of the species form recognizable clusters. For example, the brown circles in the bottom left are Ord’s kangaroo rat, Dipodomys ordii, and that cluster is well separated from the pink circles in the bottom middle, which is its confamilial Chaetodipus hispidus, the hispid pocket mouse. On the other hand, all of the Peromyscus species (blue and greenish squares) do not separate cleanly from each other and instead form a big mess of overlapping clouds along the right side of the figure. From this we can infer that D. ordii and C. hispidus are more distinct from each other than the Peromyscus species are, despite being in the same family.
Another pattern we can see is that three of the four morphological variables point to the left and slightly down, almost but not quite parallel to PC1. Ear length points in a different direction, positively correlated with PC2 but negatively with PC1. So we can tentatively interpret PC1 as a gradient representing overall size: animals increase in size from right to left. This pattern is very commonly seen when ordinating morphological measurements. However, with scaling type 1, we cannot interpret angles between vectors as correlations. For that, we need scaling type 2.
Extract the scores and make another biplot, this time with scaling 2.
# extract scores with scaling 1
xy.samp2 <- scores(p1, display="sites",
choices=1:2, scaling=2)
xy.vars2 <- scores(p1, display="species",
choices=1:2, scaling=2)
par(mar=c(5,5,7,1), bty="n")
plot(xy.samp2[,1], xy.samp2[,2],
pch=pch.fams[dx.pca$family],
col=col.spps[dx.pca$species],
xlab="PC1 (75.3%)", ylab="PC2 (17.1%)")
scal <- 0.2
segments(0, 0, scal*xy.vars2[,1], scal*xy.vars2[,2], lwd=2)
moveout <- 1.03
text(moveout*scal*xy.vars2[,1], moveout*scal*xy.vars2[,2],
rownames(xy.vars2), cex=1.2, xpd=NA)
legend(-1, 1.1, legend=spps, xpd=NA,
col=col.spps,
pch=pch.fams[tax$family[match(spps, tax$species)]],
ncol=3,
text.font=3, bty="n")
Figure 27.12 uses scaling 2 instead of scaling 1. The point clouds look largely the same, but notice how the axis scales have changed. Under scaling 2, the angles between the biplot vectors are interpretable as correlations between variables. We also see that total length, tail length, and hindfoot length are much closer to parallel with PC1, reflecting their strong loading on that axis.
27.2.3.3.1 A note on biplot scaling
You may have noticed that we used the argument scaling=2 when extracting the scores for the biplot in Figure 27.11. This argument controls how the observation and variable scores are scaled relative to each other.
- In scaling type 1 (distance scaling), the emphasis is on preserving distances among observations. This is useful when comparing observations or identifying clusters. The observation scores preserve Euclidean distances among observations as well as possible in the reduced ordination space. Variable scores are not proportional to their correlations with other variables.
- In scaling type 2 (correlation scaling), the emphasis is on representing relationships among variables. Variable scores are proportional to their correlations with the principal components. Angles between variable vectors approximate correlations among the original variables, assuming the displayed axes adequately represent those variables.
The take-home is that scaling 1 emphasizes distances among observations, while scaling 2 emphasizes correlations among variables. In either case, the variable vectors indicate the directions in which variables increase across the ordination, but angles between vectors should be interpreted as correlations only under scaling 2.
Neither scaling type is inherently better; they emphasize different aspects of the same ordination. For our first biplot above, we used scaling type 1 because we wanted to see relationships between the observations. For the second biplot, we used scaling type 2 because we wanted to interpret the relationships among the morphological measurements and their associations with the principal components.
For example, in Figure 27.11, the vectors for total length and tail length point in nearly the same direction, indicating that these measurements are strongly positively correlated. The angle between total length and ear length is larger, suggesting a weaker positive correlation. These interpretations are approximate because the biplot displays only the first two principal components rather than all four dimensions of the original dataset.
Table 27.2 sums up the differences between the two scaling types and their typical use cases.
| Feature | Scaling 1 (distance scaling) | Scaling 2 (correlation scaling) |
|---|---|---|
| Primary emphasis | Distances among observations | Correlations among variables |
| Best for | Comparing observations, identifying groups, examining gradients | Interpreting variable relationships and associations with PCs |
| Distances between points | Approximate Euclidean distances in the original data | Distances are distorted by the scaling |
| Angles between variable vectors | Not generally interpretable as correlations | Approximate correlations between variables |
When should you use each scaling?
Example use case for scaling 1: Suppose you want to determine whether the 16 mammal species in fig-pca-pca-neon1 form distinct morphological groups. You could plot the specimens using scaling 1, color them by species or family, and examine their separation. Distances between specimens in the PCA plot approximate their multivariate Euclidean distances, insofar as those distances are represented by the displayed PCs.
Example use case for scaling 2: Suppose you want to determine which morphological measurements distinguish those species. You’d use scaling 2 to examine the directions and angles of the measurement vectors. In a scaling 2 biplot, variables strongly correlated with a particular principal component tend to have vectors pointing along that axis. Variables associated with multiple components tend to have vectors pointing between the axes. The coordinates of each vector represent its correlations with the components, up to a common scaling factor.
One subtlety: If you’re plotting only observation scores, the choice of scaling usually doesn’t matter much visually. Switching between scaling 1 and scaling 2 simply rescales the PC axes; it doesn’t change the ordering of observations or the underlying PCA. However, the relative scaling of the axes changes, so distances and apparent group separation can look different.
27.2.3.4 Interpret the principal components
Both biplots above, especially Figure 27.12, suggest that PC1 might have something to do with overall size, and that PC2 might describe variation in ear size after body size is accounted for. Let’s interpret those possible interpretations. We can explore the possible relationships between the original variables and the PCs in 3 somewhat related ways:
- Eigenvector coefficients: coefficients defining each PC as a linear combination of the original variables. Sometimes called the variable loadings but see below.
- Contributions of variables to each PC: which variables contribute the most to each PC (exactly what it sounds like).
- Correlations between variables and PCs: also exactly what it sounds like. Also sometimes called “variable loadings”.
27.2.3.4.1 Eigenvector coefficients
The eigenvector coefficients are the coefficients defining how each principal component is calculated as a linear combination of the original variables. Some people call these coefficients the variable loadings, but others use that term to describe the correlations between the variables and the PCs.
Recall that a linear combination or linear equation is one where the result is obtained by multiplying each term by a constant and adding up those products (Section 14.4.1). For our PCA with four standardized measurements:
\[PC_1=a_{1,1}Z_1+a_{1,2}Z_2+a_{1,3}Z_3+a_{1,4}Z_4\]
where \(Z_i\) are the standardized measurements and \(a_{i,j}\) are the eigenvector coefficients for principal component \(i\), variable \(j\). Principal components 2, 3, and 4 are defined the same way:
\[PC_2=a_{2,1}Z_1+a_{2,2}Z_2+a_{2,3}Z_3+a_{2,4}Z_4\]
\[PC_2=a_{2,1}Z_1+a_{2,2}Z_2+a_{2,3}Z_3+a_{2,4}Z_4\]
\[PC_2=a_{2,1}Z_1+a_{2,2}Z_2+a_{2,3}Z_3+a_{2,4}Z_4\]
We can see the eigenvector coefficients like this:
p1$CA$v PC1 PC2 PC3 PC4
totalLength -0.5534528 -0.1607461 -0.33524341 -0.74529356
tailLength -0.5418198 -0.2357199 -0.46232356 0.66115382
hindfootLength -0.5133475 -0.2450069 0.81986975 0.06526506
earLength -0.3695884 0.9265897 0.04101683 0.05615698
In this case, all variables contributed to PC1, but PC2 is determined mostly by ear length. PC3 is determined mostly by hindfoot length, and PC4 is determined mostly by total length and tail length. It’s worth noting that all four measurements are positively correlated with each other, all though ear length is somewhat less correlated with the others.
cor(dx.pca[,pca.cols]) totalLength tailLength hindfootLength earLength
totalLength 1.0000000 0.9381799 0.8120411 0.5080321
tailLength 0.9381799 1.0000000 0.7863965 0.4508269
hindfootLength 0.8120411 0.7863965 1.0000000 0.4242194
earLength 0.5080321 0.4508269 0.4242194 1.0000000
This pattern of eigenvector coefficients, together with the correlations between the original variables, supports the interpretation of PC1 as a gradient of overall size. All variables have the same moderate coefficient with respect to PC1 with the same sign, and all variables are positively correlated with each other. Subsequent PCs are primarily affected by 1 or 2 measurements. PC2 is dominated by variation in ear length after accounting for the overall size gradient. PC2 is dominated by variation in hindfoot length after accounting for variation in overall size and ear length. And so on.
27.2.3.4.2 Variable contributions
The variable contributions to each PC tell us how much of a role each variable plays in defining each PC. They are calculated as the squared eigenvector coefficients, rescaled to be percentages.
var.contribs <- 100 * p1$CA$v^2
round(var.contribs, 2) PC1 PC2 PC3 PC4
totalLength 30.63 2.58 11.24 55.55
tailLength 29.36 5.56 21.37 43.71
hindfootLength 26.35 6.00 67.22 0.43
earLength 13.66 85.86 0.17 0.32
These contributions reinforce the interpretations we made by looking at the eigenvector coefficients. This makes sense, because the contributions are just the eigenvector coefficients. squared and scaled. Expressing the contributions on a percentage scale makes is more clear just how much PCs 2 and 3 are dominated by one variable.
Because each eigenvector has unit length, the contributions must sum to 100% for each PC.
colSums(var.contribs)PC1 PC2 PC3 PC4
100 100 100 100
27.2.3.4.3 Variable-PC correlations
The correlations between variables and PCs are probably the most intuitive way to find biological interpretations of principal components. These correlations are also referred to as variable loadings, meaning that this term ambiguous because it can also refer to the eigenvector coefficients.
We can get these by requesting a correlation matrix between the original variables and the PC scores of the variables.
cor(dx.pca[,pca.cols],
scores(p1, display="sites", choices=1:4)) PC1 PC2 PC3 PC4
totalLength -0.9603507 -0.1330417 -0.16618498 -0.18002497
tailLength -0.9401650 -0.1950939 -0.22918044 0.15970109
hindfootLength -0.8907600 -0.2027802 0.40642123 0.01576472
earLength -0.6413093 0.7668931 0.02033263 0.01356467
These correlations tell us that PC1 is negatively correlated with every measurement, and in the same direction, supporting our interpretation of this PC as a gradient of overall size. PC2 is strongly correlated with ear length, suggesting that this PC is a gradient of relative ear size. We don’t call PC2 a gradient of ear size, because ear size also contributes to PC1 and because variation in PC2 is only calculated after accounting for variation in PC1.
These correlations are distinct from, but related to, the variable loadings. The loadings tell us how the original variables are combined to construct each PC. The correlations tell us how strongly each original variabele is associated with each PC.
For a PCA with standardized variables, the loadings and correlations are related by
\[r_{jk}=a_{jk}\sqrt{\lambda_k}\]
where \(a_{jk}\) is the loading of variable \(j\) onto PC \(k\), \(\lambda_k\) is the eigenvalue of PC \(k\), and \(r_{jk}\) is the correlation between variable \(j\) and PC \(k\).
Different textbooks and different R packages use the term loading somewhat differently. In stats::prcomp(), the rotation part of the output contains the eigenvectors. Other implementations use “loadings” to refer to the correlations between the variables and the PCs. Legendre and Legendre (2012), which I is my primary reference for multivariate statistics, uses the eigenvector coefficient definition. The documentation for package vegan emphasizes “species scores” and “site scores” rather than use a single definition of “loading”.
We sometimes say that a variable is “loaded onto” a PC if there is some relationship between that variable and the PC. In Figure 27.11, total length, hindfoot length, and tail length all appear to be “loaded onto” PC1. However, what we mean mathematically by “loaded onto” can mean a correlation or can mean an eigenvector coefficient. These things are related but not the same. When (not if) Reviewer 2 objects to your use of “loading”, remind them that both meanings are monotonically related by a factor of \(\sqrt{\lambda_k}\).
Bottom line: if you say that some variable is “loaded onto” a PC because its biplot vector is mostly parallel with that PC, that isn’t incorrect, but it is mathematically ambiguous. Just be clear in your presentation about what you mean.
27.2.3.5 Visualizing patterns in a biplot
Now that we have a handle on what our biplot vectors do and don’t mean, let’s explore some more. We’ll stick to the scaling 2 version of the biplot.
One useful thing we can do is examine the group structure. We can superimpose the group centroids and 95% confidence ellipses on the plot to investigate group separation and overlap. Ellipses are added with function vegan::ordiellipse(), and we can get centroids from our matrix of PC scores. In Figure 27.13 we will omit the points for clarity (with argument type="n" in plot()), but you don’t have to.
# calculate species centroids
cent.p1.sp <- apply(xy.samp2, 2,
function(x){tapply(x, dx.pca$species, mean)})
# alternative shapes
pch.fams2 <- c(22, 21, 24, 23)
names(pch.fams2) <- fams
par(mar=c(5,5,7,1), bty="n")
plot(xy.samp2[,1], xy.samp2[,2],
type="n",
xlab="PC1 (75.3%)", ylab="PC2 (17.1%)")
ordiellipse(p1, groups=dx.pca$species,
col=col.spps,
draw="polygon", border=NA)
points(cent.p1.sp[,1], cent.p1.sp[,2], type="p", lwd=2,
pch=pch.fams2[dx.pca$family[match(spps, dx.pca$species)]],
bg=col.spps)
scal <- 0.2
segments(0, 0, scal*xy.vars2[,1], scal*xy.vars2[,2], lwd=2)
moveout <- 1.03
text(moveout*scal*xy.vars2[,1], moveout*scal*xy.vars2[,2],
rownames(xy.vars2), cex=1.2, xpd=NA)
legend(-1, 1.1, legend=spps, xpd=NA,
pt.bg=col.spps, pt.lwd=2,
pch=pch.fams2[tax$family[match(spps, tax$species)]],
ncol=3,
text.font=3, bty="n")
Another way to visualize groups in a biplot is to plot the minimum convex hull or minimum convex polygon. This is a shape that contains all of the points in a group. We use function ordihull(), which works similarly to ordiellipse().
par(mar=c(5,5,7,1), bty="n")
plot(xy.samp2[,1], xy.samp2[,2],
type="n",
xlab="PC1 (75.3%)", ylab="PC2 (17.1%)")
ordihull(p1, groups=dx.pca$species,
col=col.spps,
draw="polygon", border=NA)
points(cent.p1.sp[,1], cent.p1.sp[,2],
type="p", lwd=2,
pch=pch.fams2[dx.pca$family[match(spps, dx.pca$species)]],
bg=col.spps)
scal <- 0.2
segments(0, 0, scal*xy.vars2[,1], scal*xy.vars2[,2], lwd=2)
moveout <- 1.03
text(moveout*scal*xy.vars2[,1], moveout*scal*xy.vars2[,2],
rownames(xy.vars2), cex=1.2, xpd=NA)
legend(-1, 1.1, legend=spps, xpd=NA,
pt.bg=col.spps, pt.lwd=2,
pch=pch.fams2[tax$family[match(spps, tax$species)]],
ncol=3,
text.font=3, bty="n")vegan::ordihull(). Each symbol represents a species centroid, and the surrounding shaded polygon encloses the outermost specimens of that species in the two-dimensional ordination. Unlike ellipses, convex hulls show the observed extent of each species rather than a statistical summary of its dispersion. PC1 explains 75.3% of the variation and PC2 explains 17.1%. Black vectors represent the morphological measurements using scaling type 2.
We can embellish the group polygons with ordispider(), which draws a segment from the group centroid to every vertex of the minimum convex polygon. The function is ordispider(). Note that this can make a plot very busy and hard to interpret.
par(mar=c(5,5,7,1), bty="n")
plot(xy.samp2[,1], xy.samp2[,2],
type="n",
xlab="PC1 (75.3%)", ylab="PC2 (17.1%)")
ordihull(p1, groups=dx.pca$species,
col=col.spps,
draw="polygon", border="black")
ordispider(p1, groups=dx.pca$species,
col=col.spps, lwd=2)
points(cent.p1.sp[,1], cent.p1.sp[,2], type="p", lwd=2,
pch=pch.fams2[dx.pca$family[match(spps, dx.pca$species)]],
bg=col.spps)
scal <- 0.2
segments(0, 0, scal*xy.vars2[,1], scal*xy.vars2[,2], lwd=2)
moveout <- 1.03
text(moveout*scal*xy.vars2[,1], moveout*scal*xy.vars2[,2],
rownames(xy.vars2), cex=1.2, xpd=NA)
legend(-1, 1.1, legend=spps, xpd=NA,
pt.bg=col.spps, pt.lwd=2,
pch=pch.fams2[tax$family[match(spps, tax$species)]],
ncol=3,
text.font=3, bty="n")vegan::ordispider(). Each colored line connects an individual specimen to its species centroid, illustrating within-species variation in the ordination. Shaded polygons generated by vegan::ordihull() enclose the outermost specimens of each species. PC1 explains 75.3% of the variation and PC2 explains 17.1%. Black vectors represent the morphological measurements using scaling type 2.
Just for fun, let’s make a version symbolized only by family. This reveals something interesting. Notice how the teal ellipse for family Muridae (old world rats and mice) is near the center of the plot, when most of its points are on the left? If you look closely at the right side, you can see a little cloud of teal triangles representing House Mouse (Mus musculus). They were hard to see in previous biplots because were mixed up with all of the other small mice in family Cricetidae (new world rats and mice). We confirm this in Figure 27.16, which shows the genera, and Figure 27.17, which shows the families.
par(mar=c(5,5,4,1), bty="n")
plot(xy.samp2[,1], xy.samp2[,2],
pch=pch.fams[dx.pca$family],
col=col.fams[dx.pca$family],
xlab="PC1 (75.3%)", ylab="PC2 (17.1%)")
ordiellipse(p1, dx.pca$family,
col=col.fams, draw="polygon",
border=NA)
scal <- 0.2
segments(0, 0, scal*xy.vars2[,1], scal*xy.vars2[,2], lwd=2)
text(1.03*scal*xy.vars2[,1], 1.03*scal*xy.vars2[,2],
rownames(xy.vars2), cex=1.2)
legend(-1, 0.9, legend=fams, xpd=NA,
fill=col.fams, cex=1.4,
ncol=2, bty="n")vegan::ordiellipse() summarize the dispersion of specimens within each family. PC1 explains 75.3% of the variation and PC2 explains 17.1%. Black vectors represent the morphological measurements using scaling type 2. The families differ in their distributions across the ordination, although their ellipses overlap.
# pull genus names from tax
dx.pca$genus <- tax$genus[match(dx.pca$abb, tax$abb)]
# unique genera in our dataset
genera <- sort(unique(dx.pca$genus))
# define colors
col.gen <- hcl.colors(length(genera), palette = "Dark 3")
names(col.gen) <- genera
# genus centroids
cent.p1.gen <- apply(xy.samp2, 2,
function(x){tapply(x, dx.pca$genus, mean)})
par(mar=c(5,5,4,1), bty="n")
plot(xy.samp2[,1], xy.samp2[,2],
type="n",
xlab="PC1 (75.3%)", ylab="PC2 (17.1%)")
ordiellipse(p1, dx.pca$genus,
col=col.gen, draw="polygon",
border=NA, alpha=100)
text(cent.p1.gen[,1], cent.p1.gen[,2],
genera, font=3, cex=0.9)
scal <- 0.2
segments(0, 0, scal*xy.vars2[,1], scal*xy.vars2[,2], lwd=2)
text(1.03*scal*xy.vars2[,1], 1.03*scal*xy.vars2[,2],
rownames(xy.vars2), cex=1.2)
legend(-1, 0.9, legend=genera, xpd=NA,
fill=col.gen,
ncol=4, bty="n", text.font=3)vegan::ordiellipse() summarize the dispersion of specimens within each genus, with labels identifying the genera. PC1 explains 75.3% of the variation and PC2 explains 17.1%. Black vectors represent the morphological measurements using scaling type 2. Several genera occupy distinct regions of the ordination, while others overlap, particularly Myodes, Onychomys, Mus, and Reithrodontomys.
27.2.3.6 Factoring out body size
Recall that we found that PC1 is a gradient of body size. What if we wanted to use PCA to example body shape with size factored out? One option, if we are confident that PC1 represented only body size, would to simply drop PC1 and look at plots of PCs 2, 3, and 4. A better option might be to regress our measurements on some measurement of body size. Remember in Section 27.2.3.2 when we deliberately left body mass out of our ordination? That was so we could use it now to factor overall size out of our measurements.
The strategy is to regress each standard measurement against body mass, then perform a second PCA on the residuals of those relationships. First, check some scatterplots to get a sense of what we are dealing with:
par(mar=c(5,5,1,1), mfrow=c(2,2))
plot(dx.pca$weight, dx.pca$totalLength, log="xy")
plot(dx.pca$weight, dx.pca$tailLength, log="xy")
plot(dx.pca$weight, dx.pca$hindfootLength, log="xy")
plot(dx.pca$weight, dx.pca$earLength, log="xy")
Figure 27.18 shows that all four measurements have a strong, allometric relationships with body mass. That is, the relationship follows a power law \(y=ax^b\) or a linear relationship on the log-log scale. Let’s fit those relationships and add the residuals to dx.pca.
logdx <- log(dx.pca[,pca.cols])
names(logdx) <- paste("log", c("total", "tail", "foot", "ear"), sep="_")
dx.pca <- cbind(dx.pca, logdx)
dx.pca$logmass <- log(dx.pca$weight)
mod.list <- vector("list", length=4)
for(i in 1:4){
y <- dx.pca[,names(logdx)[i]]
current.model <- lm(y~dx.pca$logmass)
mod.list[[i]] <- residuals(current.model)
}
dx.pca.res <- do.call(cbind, mod.list)
colnames(dx.pca.res) <- pca.cols
dx.pca.res <- data.frame(dx.pca.res)Now we can run a new PCA on our size-adjusted measurements.
p2 <- pca(dx.pca.res, scale=TRUE)
summary(p2)
Call:
pca(X = dx.pca.res, scale = TRUE)
Partitioning of correlations:
Inertia Proportion
Total 4 1
Unconstrained 4 1
Eigenvalues, and their contribution to the correlations
Importance of components:
PC1 PC2 PC3 PC4
Eigenvalue 2.0858 0.9986 0.7363 0.17933
Proportion Explained 0.5214 0.2497 0.1841 0.04483
Cumulative Proportion 0.5214 0.7711 0.9552 1.00000
This is different. In the first PCA that was not size-adjusted, PC1 accounted for over 75% of variation. In the size-adjusted PCA, it’s more like 52%. We know that overall size has been factored out, so PC1 cannot be a gradient of overall size.
Check the variable loadings (correlation sense):
cor(dx.pca.res,
scores(p2, display="sites", choices=1:4)) PC1 PC2 PC3 PC4
totalLength 0.90903127 0.02676730 0.2926666 0.29545208
tailLength 0.91969117 0.06294948 0.2420286 -0.30270062
hindfootLength 0.63935589 -0.02012092 -0.7684682 0.01660641
earLength 0.06958742 -0.99676003 0.0386570 -0.01151785
The loadings tell us what to expect in the biplot, and actually make a lot of biological sense. PC1 is correlated with total length and tail length, and to a lesser extent hindfoot length. Total length and tail length in particularly are strongly correlated, so it make sense that they should be correlated with the same axis. PC2, as in the first PCA, is strongly associated with ear length. PC3 is mostly a gradient of hindfoot length.
Let’s check out the biplot:
# extract scores with scaling 1
xy.samp3 <- scores(p2, display="sites",
choices=1:4, scaling=2)
xy.vars3 <- scores(p2, display="species",
choices=1:4, scaling=2)
par(mar=c(5,5,7,1), bty="n", xpd=NA)
plot(xy.samp3[,1], xy.samp3[,2],
pch=pch.fams[dx.pca$family],
col=col.spps[dx.pca$species],
xlab="PC1 (52.1%)", ylab="PC2 (25.0%)")
# shorten the biplot vectors to fit on the plot area
scal <- 0.1
segments(0, 0, scal*xy.vars3[,1], scal*xy.vars3[,2], lwd=2)
# move the biplot labels out by 2%
moveout <- 1.02
text(moveout*scal*xy.vars3[,1], moveout*scal*xy.vars3[,2],
rownames(xy.vars3), cex=1.2)
legend(-1.25, 1.1, legend=spps,
col=col.spps,
pch=pch.fams[tax$family[match(spps, tax$species)]],
ncol=3,
text.font=3, bty="n")
In Figure 27.19 we still see PC1 being a gradient of overall size, with ear length being mostly orthogonal to the other variables. The arrangement of the samples is quite different, though. Let’s superimpose the species:
# get species centroids in p2 PCA coordinates
cent.p2.sp <- apply(xy.samp3, 2,
function(x){tapply(x, dx.pca$species, mean)})
par(mar=c(5,5,7,1), bty="n", xpd=NA)
plot(xy.samp3[,1], xy.samp3[,2],
type="n",
xlab="PC1 (52.1%)", ylab="PC2 (25.0%)")
ordiellipse(p2, dx.pca$species, col=col.spps,
border=NA, draw="polygon")
text(cent.p2.sp[,1], cent.p2.sp[,2],
spps, font=3, cex=0.8)
# shorten the biplot vectors to fit on the plot area
scal <- 0.1
segments(0, 0, scal*xy.vars3[,1], scal*xy.vars3[,2], lwd=2)
# move the biplot labels out by 2%
moveout <- 1.02
text(moveout*scal*xy.vars3[,1], moveout*scal*xy.vars3[,2],
rownames(xy.vars3), cex=1.2)
legend(-1.4, 1.1, legend=spps,
fill=col.spps, bty="n", cex=0.8, ncol=3, text.font=3)vegan::ordiellipse() summarize the dispersion of specimens within each species, with labels identifying the species. PC1 explains 52.1% of the variation and PC2 explains 25.0%. Black vectors represent the size-adjusted morphological measurements using scaling type 2. Several species occupy distinct regions of the ordination, while others exhibit considerable overlap.
One interesting consequence I see is that now that we factored out overall size, Rattus is much closer to the Mus and most of the mouse group. We also now see Northern Grasshopper Mouse (Onychomys leucogaster) and Northern Red-backed Vole (Myodes rutilus) as now much more separated from the rest of the cricetids (Peromyscus and Reithrodontomys). And, the heteromyids are grouped together more closely than they were when size was driving PC1. I’m a little surprise to see Masked Shrew (Sorex cinereus) up there with the heteromyids. In the first ordination they were simply the smallest species. Does that pattern happen along other PCs?
par(mar=c(5,5,7,1), bty="n", xpd=NA)
plot(xy.samp3[,1], xy.samp3[,3],
type="n",
xlab="PC1 (52.1%)", ylab="PC3 (18.4%)")
ordiellipse(p2, dx.pca$species, col=col.spps,
border=NA, draw="polygon",
choices=c(1,3))
text(cent.p2.sp[,1], cent.p2.sp[,3],
spps, font=3, cex=0.8)
# shorten the biplot vectors to fit on the plot area
scal <- 0.1
segments(0, 0, scal*xy.vars3[,1], scal*xy.vars3[,3], lwd=2)
# move the biplot labels out by 2%
moveout <- 1.02
text(moveout*scal*xy.vars3[,1], moveout*scal*xy.vars3[,3],
rownames(xy.vars3), cex=1.2)
legend(-1.0, 2, legend=spps,
fill=col.spps, bty="n", cex=0.8, ncol=3, text.font=3)vegan::ordiellipse() summarize the dispersion of specimens within each species, with labels identifying the species. PC1 explains 52.1% of the variation and PC3 explains 18.4%. Black vectors represent the size-adjusted morphological measurements using scaling type 2. Several species that overlap on PC1 and PC2 are more clearly distinguished along PC3, particularly Dipodomys ordii.
It appears so:
par(mar=c(5,5,7,1), bty="n", xpd=NA)
plot(xy.samp3[,2], xy.samp3[,3],
type="n",
xlab="PC2 (25.0%)", ylab="PC3 (18.4%)")
ordiellipse(p2, dx.pca$species, col=col.spps,
border=NA, draw="polygon",
choices=c(2,3))
text(cent.p2.sp[,2], cent.p2.sp[,3],
spps, font=3, cex=0.8)
# shorten the biplot vectors to fit on the plot area
scal <- 0.1
segments(0, 0, scal*xy.vars3[,2], scal*xy.vars3[,3], lwd=2)
# move the biplot labels out by 2%
moveout <- 1.02
text(moveout*scal*xy.vars3[,2], moveout*scal*xy.vars3[,3],
rownames(xy.vars3), cex=1.2)
legend(-0.45, 2, legend=spps,
fill=col.spps, bty="n", cex=0.8, ncol=3, text.font=3)vegan::ordiellipse() summarize the dispersion of specimens within each species, with labels identifying the species. PC2 explains 25.0% of the variation and PC3 explains 18.4%. Black vectors represent the size-adjusted morphological measurements using scaling type 2. Several species are more clearly separated along PC2, particularly Chaetodipus hispidus and Dipodomys ordii, while other species overlap extensively.
So what did we learn?
- PCA can help us visualize variation between samples and what variables drive that variation.
- The closer two samples are together in the ordination space, the more similar they are.
- Variables get bigger in the direction of their arrow.
- Size matters.
- Shrews are weird but neat.
Next let’s explore principal coordinates analysis (PCoA), a technique for exploring patterns among samples without the Euclidean distance metric.
27.3 Principal coordinates analysis (PCoA)
Coming soon!
27.4 Correspondence analysis (CA)
Coming soon!
27.5 Nonmetric multidimensional scaling (NMDS)
27.5.1 Definition and illustration
Nonmetric multidimensional scaling (NMDS) is an ordination method that attempts to arrange samples in a lower-dimensional space in a way that preserves the rank order of the dissimilarity matrix. It finds this arrangement, or configuration, through numerical optimization, rather than eigenanalysis.
NMDS works by finding a way to arrange samples in fewer dimensions while minimizing the distortion of the distance matrix. Imagine a dataset with 3 dimensions (Figure 27.23). The distance matrix, represented by the thin grey lines, exists in the same three-dimensional space as the dataset. Differences between the observations are summarized in the distance matrix. It follows that any new representation of the data should preserve that distance matrix.
The observations could be represented in two dimensions by projecting them down to the plane defined by Variable 1 and Variable 2.
But, there is a problem. If we simply project the points down to 2d, we discard all of the information in the other variables. This has the effect of distorting the distance matrix between the observations. It’s the same problem that arises when projecting the Earth’s surface onto a flat map: removing the curvature (information in the third dimension) distorts relative distances and directions on the map.
If we want to represent the relationships between the samples in a 3d space in a 2d space, we need allow the points to move a bit so that information from the third dimension is not entirely discarded.
Run 0 stress 0.2046256
Run 1 stress 0.2116927
Run 2 stress 0.2051575
Run 3 stress 0.2106919
Run 4 stress 0.2237271
Run 5 stress 0.2176059
Run 6 stress 0.2143323
Run 7 stress 0.2116798
Run 8 stress 0.2112006
Run 9 stress 0.2138354
Run 10 stress 0.2022788
... New best solution
... Procrustes: rmse 0.04241575 max resid 0.2043617
Run 11 stress 0.2106919
Run 12 stress 0.2154941
Run 13 stress 0.2106919
Run 14 stress 0.2167754
Run 15 stress 0.2095638
Run 16 stress 0.2080194
Run 17 stress 0.2051329
Run 18 stress 0.2020145
... New best solution
... Procrustes: rmse 0.01160848 max resid 0.07650897
Run 19 stress 0.2046256
Run 20 stress 0.2020909
... Procrustes: rmse 0.005079137 max resid 0.02857704
*** Best solution was not repeated -- monoMDS stopping criteria:
19: stress ratio > sratmax
1: scale factor of the gradient < sfgrmin

The NMDS configuration looks different than the projection onto the X-Y plane. Did it do a better job at representing the distance matrix?
The left panel in Figure 27.26 is the same as Figure 27.25, showing how the distances in the 2d projection relate to the corresponding distances in the original 3d. The right panel in Figure 27.26 shows how distances in the 2d NMDS space relate to the original 3d distance matrix. Notice that the discrepancies between the NMDS solution distances and the original distances are both positive and negative, whereas the distances in the 2d projection are always less than their counterparts in 3 dimensions. If we calculate the correlations between the original 3d distances and the two methods of reducing the data to 2 dimensions, we see that the distances in the NMDS solution are much more closely correlated with the original distances than the distances in the 2d projection are.
Correlation between 2d projection distances
and original 3d distance matrix
[1] 0.7902007
Correlation between 2d NMDS configuration
distances and original 3d distance matrix
[1] 0.880239
The example we just stepped through illustrates why we use NMDS: dimension reduction without dissimilarity distortion.
27.5.2 Why use NMDS?
Now that we understand the goal of NMDS–representing dissimilarities between samples in reduced dimensions–it’s worth asking “Why?” The choice of ordination method, like the choice of statistical tests, can have important consequences in an analysis.
NMDS is particularly useful for multivariate datasets containing many variables, especially when observations share relatively few characteristics or when the data contain many zeros. For example, community ecology datasets often contain many species that occur at only a few sites, resulting in sparse matrices with relatively few shared species between sites. In these situations, dissimilarity measures such as Sørensen can be useful because they emphasize shared occurrences without treating joint absences as evidence of similarity. NMDS then represents the dissimilarities among observations in a small number of dimensions, attempting to preserve their rank ordering rather than their exact numerical values.
This flexibility makes NMDS useful for exploring complex multivariate patterns that may not be adequately represented by linear relationships. However, datasets containing many pairs of maximally dissimilar observations can be challenging because the ordination has relatively little information about their relative positions.
McCune et al. (2002) note that one advantage of NMDS is that it handles data that are nonnormal, discontinuous, or “otherwise questionable scales”. This is because of the focus on the rank order of the dissimilarity matrix rather than its actual values. Maintaining rank order rather than magnitude makes variables on very diffrent scales or with few values more comparable. They also note that NMDS not only avoids the assumption of linear relationships among variables, it can linearize many relationships because of its reliance on rank order statistics.
That is not to say that NMDS is without disadvantages. One major issue with NMDS is that its reliance on Monte Carlo (random sampling) methods for optimization can cause it to fail to find the best (global) solution. Another feature which can be a disadvantage is that the axes have no direct mathematical relationship with the variables in the dataset.
27.5.3 Details of the algorithm
NMDS works by iteratively searching for a configuration of samples that faithfully represents the rank order of the distance matrix of a dataset in a reduced dimensional space. This is a completely different approach than PCA, which achieves dimension reduction by finding eigenvectors in the dataset that capture the variation more efficiently than the original dataset (i.e., it rotates the dataset).
NMDS works with the \(n\times n\) distance matrix calculated from an \(n\times p\)-dimensional data matrix, where \(n\) is the number of observations and \(p\) is the number of variables. It tries to represent the samples in a \(k\)-dimensional space, where \(k<p\). The configuration in \(k\) dimensions is optimized to minimize stress, which is a measure of how much the distance matrix in \(k\) dimensions distorts the distance matrix in \(p\) dimensions. The distortion measured by stress is a departure from monotonicity. That is, how much the rank order of the dissimilarity matrix changes.
The basic algorithm for NMDS is as follows.
- Calculate the distance matrix \(\mathbf{\Delta}\) in the original \(p\)-dimensional space.
- Assign sample units to a (usually random) starting configuration in the reduced \(k\)-dimensional space.
- Calculate \(\mathbf{D}_k\), the Euclidean distance matrix of the samples in the k-space.
- Rank the elements of \(\mathbf{\Delta}\), and then put the elements of \(\mathbf{D}_k\) in the same order as \(\mathbf{\Delta}\).
- Calculate vector \(\hat{\mathbf{D}}_k\), which is a copy of \(\mathbf{D}_k\) that replaces elements which break monotonicity. For example, \(d_5\) should be a distance that falls between \(d_4\) and \(d_6\). But, if \(d_5<d_4\) or \(d_5>d_6\), \(d_5\) will be adjusted to become \(\hat{d}_5\), which is between \(d_4\) and \(d_6\). The total amount of adjustment needed to adjust every \(d_{i}\) to \(\hat{d}_{i}\) is used to calculate stress.
- The positions of the samples in \(k\)-space is adjusted according to an algorithm that seeks a lower stress value.
- This process is repeated until the stress stops improving.
Because the starting configurations and the re-configurations involve random number sampling (“Monte Carlo methods”), most NMDS software tries several random starts to avoid the possibility of begin trapped in a local solution that is not as optimal as the true global solution.
You should also set the random number seed, so your analysis results are reproducible. Remember, the NMDS axes are arbitrary, so even though you might repeat the analysis and get two solutions with the same stress value, one of them might be rotated from the other…meaning that you have to re-write your plot code!
27.5.4 NMDS example using NEON data
27.5.4.1 Data import and preparation
For an example NMDS analysis, let’s revisit the small mammal capture data from Section 26.2.2. Download the site-level capture dataset, the site metadata, and the taxonomic dataset and put them in your working directory.
tax <- read.csv("data-neon-taxa.csv")
cap <- read.csv("data-neon-captures-site.csv")
met <- read.csv("data-neon-metadata-site.csv")We are going to use NMDS to explore variation in small mammal diversity between sites. First we need to organize the data. We are going to convert the capture numbers in cap to presence-absence: 1 for presence, 0 for absence. We will assume that detection at a site at any point indicates presence, and non-detection indicates absence. We will avoid analyzing capture numbers because capture count is a function of sampling effort and trap success as much as it reflects actual presence or abundance.
pa <- cap
# fix some columns and set rownames
pa$X <- NULL
rownames(pa) <- pa$site
pa$site <- NULL
# convert capture numbers to presence absence
pa[pa>0] <- 1Now let’s check the dataset. We want to screen for potential problems. Chief among these are (1) species present at no sites or 1 site; and (2) sites with no species.
# shows that one species is not present at
# any site. Delete this species because it
# carries no information.
table(colSums(pa)==0)
FALSE TRUE
133 1
# leaves 133 species
pa <- pa[,-which(colSums(pa)==0)]Now check for sites with no species.
# all 46 sites have >=1 species,
# so no worries here
table(rowSums(pa)==0)
FALSE
46
Having one site with no species present might not be a problem, but having more than one would complicate the distance calculations.
Now that we have eliminated the obvious problems, let’s explore the distribution of species occurrences and species richnesses.
# shows that most species are present at very
# few sites. Most sites have around 5-15 species,
# but there is a lot of variability.
par(mfrow=c(1,2))
hist(colSums(pa), main="Sites per species")
hist(rowSums(pa), main="Species per site")
The left panel in Figure 27.28 tell us that the species presence-absence matrix pa is quite sparse: most species occur in at <5 sites. This supports the decision to analyze-presence absence rather than abundance because differences between sites are likely to be driven by differences in composition rather than differences in abundance. The right panel in Figure 27.28 suggests that analyzing composition rather than species richness would be more informative because species richness doesn’t vary very between sites.
The left panel in Figure 27.28 also suggests the use of the Bray-Curtis (Sørensen) dissimilarity measure rather than the Euclidean distance metric. Sørensen dissimilarity is appropriate for presence–absence data because it emphasizes shared occurrences while ignoring joint absences, which provide little evidence of ecological similarity. NMDS then represents these compositional differences in a small number of dimensions without assuming that dissimilarities must correspond linearly to distances in the ordination. However, datasets with many pairs of sites sharing no species can be challenging because those pairs all have the maximum Sørensen dissimilarity.
It is worth noting that the sparsity of the data is a strong argument for the Sørensen dissimilarity, but not an argument for using NMDS over another distance-based ordination method like PCoA. The arguments in favor of NMDS are its rank-based representation of potentially nonlinear relationships and lack of assumptions about linearity.
27.5.4.2 Fit the NMDS
The vegan function for NMDS is metaMDS(). We will use the default dissimilarity, Bray-Curtis, which for binary data is the same as the Sørensen dissimilarity. We will accept the other default arguments in metaMDS() too.
library(vegan)
set.seed(12)
n1 <- metaMDS(pa, distance="bray", k=2)Run 0 stress 0.1157083
Run 1 stress 0.1157084
... Procrustes: rmse 0.0005291083 max resid 0.00309328
... Similar to previous best
Run 2 stress 0.1565656
Run 3 stress 0.1585646
Run 4 stress 0.12028
Run 5 stress 0.1160273
... Procrustes: rmse 0.004644895 max resid 0.02378213
Run 6 stress 0.1157089
... Procrustes: rmse 0.0002810476 max resid 0.001643115
... Similar to previous best
Run 7 stress 0.1157088
... Procrustes: rmse 0.0006986409 max resid 0.004081606
... Similar to previous best
Run 8 stress 0.1160272
... Procrustes: rmse 0.004672019 max resid 0.02354286
Run 9 stress 0.1157087
... Procrustes: rmse 0.0006014595 max resid 0.003510318
... Similar to previous best
Run 10 stress 0.1157082
... New best solution
... Procrustes: rmse 9.505359e-05 max resid 0.0005557513
... Similar to previous best
Run 11 stress 0.1642549
Run 12 stress 0.1160273
... Procrustes: rmse 0.004642375 max resid 0.0238443
Run 13 stress 0.1658836
Run 14 stress 0.1157082
... New best solution
... Procrustes: rmse 3.612556e-05 max resid 0.0002015742
... Similar to previous best
Run 15 stress 0.1349674
Run 16 stress 0.1157083
... Procrustes: rmse 1.743284e-05 max resid 3.244429e-05
... Similar to previous best
Run 17 stress 0.1157086
... Procrustes: rmse 0.0002612398 max resid 0.001526905
... Similar to previous best
Run 18 stress 0.1157087
... Procrustes: rmse 0.0003102469 max resid 0.00180157
... Similar to previous best
Run 19 stress 0.1157087
... Procrustes: rmse 0.0003207051 max resid 0.001873653
... Similar to previous best
Run 20 stress 0.1524464
*** Best solution repeated 5 times
n1
Call:
metaMDS(comm = pa, distance = "bray", k = 2)
global Multidimensional Scaling using monoMDS
Data: pa
Distance: bray
Dimensions: 2
Stress: 0.1157082
Stress type 1, weak ties
Best solution was repeated 5 times in 20 tries
The best solution was from try 14 (random start)
Scaling: centring, PC rotation, halfchange scaling
Species: expanded scores based on 'pa'
The solution has a stress value of about 0.12, which is good but not great. By convention, a stress between 0.1 and 0.2 indicates a usable but imperfect representation of the original dissimilarities. Stress less than 0.1 is preferable, and stress greater than 0.2 means that an ordination is suspect. If you get a stress value greater than 0.2, you can try more random starts, dropping variables with too many 0s or extreme values, or sites with data issues. Or, try another ordination technique.
One important diagnostic for our NMDS fit is called stress plot or Shepard plot. This is a figure that shows how the distance matrix in the ordination solution compares to the distance matrix in the original space. This plot should show a very tight correlation between the two distance matrices. This correlation does not have to be linear. Remember, NMDS preserves the rank order of the distance matrix, not the actual values. Figure 27.29 below shows a pretty good correlation, but a big clump of points where the observed dissimilarity is 1. This is unavoidable in this dataset, because about a quarter of the pairs of sites share no species in common and thus have the maximum Sørensen dissimilarity of 1 (check with length(which(vegdist(pa)==1))).
par(mar=c(5,5,1,1))
stressplot(n1)
27.5.4.3 Inspect and plot
With a stress of about 0.12, we can interpret broad gradients and groups of sites, but should avoid drawing conclusions about small differences between individual samples.
Let’s visualize the ordination by extracting the NMDS axis scores and plotting them. The process is similar to what we did for PCA. However, we are not going to extract species scores, because unlike in PCA the axes are not linear combinations of the underlying variables (or any kind of function, for that matter). Instead, we will use function envfit(), which finds a vector showing the strongest linear association between a variable and the site coordinates in NMDS space.
# scaling doesn't matter as much
# as it did for PCA, so just use
# type 1
xy <- scores(n1, display="sites", scaling=1)
# fit the species vectors
e1 <- envfit(n1, pa)
sp <- e1$vectors$arrows
# show only species with significant
# associations with the NMDS space
sp <- sp[e1$vectors$pvals < 0.05,]
par(mar=c(5,5,1,1))
plot(xy[,1], xy[,2], pch=19, cex=1.3,
xlab="NMDS axis 1", ylab="NMDS axis 2")
segments(0, 0, sp[,1], sp[,2], col="red")
text(sp[,1], sp[,2], rownames(sp),
col="red", cex=0.7)
The species names in the biplot are a little hard to read, but we can zoom in if we need with the xlim and ylim arguments.
par(mar=c(5,5,1,1))
plot(xy[,1], xy[,2], pch=19, cex=1.3,
xlab="NMDS axis 1", ylab="NMDS axis 2",
xlim=c(-0.5, 0.5), ylim=c(0.9, 1.05))
segments(0, 0, sp[,1], sp[,2], col="red")
text(sp[,1], sp[,2], rownames(sp),
col="red", cex=0.7)
par(mar=c(5,5,1,1))
plot(xy[,1], xy[,2], pch=19, cex=1.3,
xlab="NMDS axis 1", ylab="NMDS axis 2",
xlim=c(-0.25, 1), ylim=c(-1, -0.5))
segments(0, 0, sp[,1], sp[,2], col="red")
text(sp[,1], sp[,2], rownames(sp),
col="red", cex=0.7)
Figure 27.30 suggests that sites form a gradient between two groups of species that tend to co-occur. At high values of NMDS axis 2, we have Perman, Perboy, Dipord, Reimeg, Onyleu, Sortro, Tammin, Tamdou, and others. Those are Deer Mouse (Peromyscus maniculatus), Brush Mouse (P. boylii), Ord’s Kangaroo Rat (Dipodomys ordii), Western Harvest Mouse (Reithrodontomys megalotis), Northern Grasshopper Mouse (Onychomys leucogaster), Trowbridge’s Shrew (Sorex trowbridgii), Least Chipmunk (Tamias minimus), and Douglas’s Squirrel (Tamiasciurus douglasii). At lower values of NMDS axis 2, we have Tamstr, Ochnut, Perleu, Pergos, Perpol, Orypal, Blacar, Podflo, Neoflo, and Sighis These are Eastern Chipmunk (Tamias striatus), Golden Mouse (Ochrotomys nuttalli), White-footed Mouse (Peromyscus leucopus), Cotton Mouse (P. gossypinus), Oldfield Mouse (P. polionotus), Marsh Rice Rat (Oryzomys palustris), Southern Short-tailed Shrew (Blarina carolinensis), Florida Mouse (Podomys floridanus), Eastern Woodrat (Neotoma floridana), and Hispid Cotton Rat (Sigmodon hispidus).
Those two clusters of species suggest that NMDS axis 2 might be an east-west gradient. Let’s find out.
27.5.4.4 Fitting environmental variables
We can fit environmental variables to NMDS solutions just like we can species. Let’s use the site metadata in met. The rows of met are in the same order as pa, so we don’t need to merge. For convenience, we can make a new data frame env that has just the columns we need.
env.cols <- c("lat", "lon", "elev",
"precip", "temp", "npp",
"seas.pre", "seas.temp")
env <- met[,env.cols]
# fit the vectors
e2 <- envfit(n1, env)
en <- e2$vectors$arrows
en <- en[e2$vectors$pvals < 0.05,]Now add these to the plot.
par(mar=c(5,5,1,1))
plot(xy[,1], xy[,2], pch=19, cex=1.3,
xlab="NMDS axis 1", ylab="NMDS axis 2")
segments(0, 0, sp[,1], sp[,2], col="#FF000030")
text(sp[,1], sp[,2], rownames(sp),
col="#FF000030", cex=0.7)
segments(0, 0, en[,1], en[,2], col="blue",
lwd=2)
text(en[,1], en[,2], rownames(en),
col="blue", cex=0.7)
Our suspicion about NMDS axis 2 representing a longitudinal gradient wasn’t far off: lon points to the lower right, indicating that lower longitudes (east) are that direction. The vectors for elevation (elev) and seasonality of precipitation seas.pre seem mroe aligned with the gradient we proposed.
Another interesting pattern is that the vectors for latitude and temperature point in nearly opposite directions. This makes sense: higher latitudes experience colder temperatures. The species associated with higher latitudes are Tamhud, Micpen, Micoec, Sorugy, Sorcin, Sortun, Myorut, Uropar, Dicgro, Lemtri, and Micmiu. These are American Red Squirrel (Tamiasciurus hudsonicus), Meadow Vole (Microtus pennsylvanicus), Tundra Vole (M. oeconomus), Barren-ground Shrew (Sorex ugyunak), Masked Shrew (S. cinereus), Tundra Shrew (S. tundrensis), Northern Red-backed Vole (Myodes rutilus), Arctic Ground Squirrel (Urocitellus parryii), Northern Collared Lemming (Dicrostonyx groenlandicus), Nearctic Brown Lemming (Lemmus trimucronatus), and Singing Vole (Microtus miurus). So, the association between latitude and these species makes sense.
Another option for visualizing how environmental variables may relate to your ordination solution is to fit a surface. This is a better way to visualize nonlinear and nonmonotonic patterns.
par(mar=c(5,5,1,1))
plot(xy[,1], xy[,2], pch=19, cex=1.3,
xlab="NMDS axis 1", ylab="NMDS axis 2")
segments(0, 0, sp[,1], sp[,2], col="#FF000030")
text(sp[,1], sp[,2], rownames(sp),
col="#FF000030", cex=0.7)
ordisurf(n1, env$temp, add=TRUE, col="blue")
Family: gaussian
Link function: identity
Formula:
y ~ s(x1, x2, k = 10, bs = "tp", fx = FALSE)
Estimated degrees of freedom:
8.35 total = 9.35
REML score: 105.8698
In this case, Figure 27.34 shows a clear gradient of increasing temperature from left to right. Some variables, like elevation, are more complicated:
par(mar=c(5,5,1,1))
plot(xy[,1], xy[,2], pch=19, cex=1.3,
xlab="NMDS axis 1", ylab="NMDS axis 2")
segments(0, 0, sp[,1], sp[,2], col="#FF000030")
text(sp[,1], sp[,2], rownames(sp),
col="#FF000030", cex=0.7)
ordisurf(n1, env$seas.temp, add=TRUE, col="blue")
Family: gaussian
Link function: identity
Formula:
y ~ s(x1, x2, k = 10, bs = "tp", fx = FALSE)
Estimated degrees of freedom:
8.52 total = 9.52
REML score: 283.944
We can also fit factors using envfit() and show them with ordiellipse():
e3 <- envfit(n1, met$habitat)
hab <- e3$factors$centroids
cols <- hcl.colors(nrow(hab), "Dark 3")
par(mar=c(5,5,1,1))
plot(xy[,1], xy[,2], pch=19, cex=1.3,
xlab="NMDS axis 1", ylab="NMDS axis 2")
text(hab[,1], hab[,2], rownames(hab),
col=cols, xpd=NA)
27.5.4.5 Dimensionality in NMDS
In the previous example, we decided to fit a two-dimensional solution. However, we could have tried a three or four or more dimensional solution. The choice of how many dimensions to use for your NMDS solution depends on a balance of (1) minimizing stress; while (2) keeping the figure interpretable. We can assess how stress changes by plotting the stress of solutions with different numbers of dimenions. The strategy is similar to how we assessed how many clusters were appropriate in K-means clustering: obtain a fit with different values for k, and plot how the stress changes with each additional dimension in the solution.
set.seed(123)
K <- 1:8
klist <- vector("list", length=length(K))
for(i in 1:length(K)){
klist[[i]] <- metaMDS(pa, k=K[i])
}Run 0 stress 0.228575
Run 1 stress 0.262067
Run 2 stress 0.2315957
Run 3 stress 0.2281544
... New best solution
... Procrustes: rmse 0.03306487 max resid 0.1176156
Run 4 stress 0.2480115
Run 5 stress 0.228049
... New best solution
... Procrustes: rmse 0.03660245 max resid 0.1492753
Run 6 stress 0.2274487
... New best solution
... Procrustes: rmse 0.006039331 max resid 0.01876672
Run 7 stress 0.2274344
... New best solution
... Procrustes: rmse 0.03556711 max resid 0.1541928
Run 8 stress 0.2364162
Run 9 stress 0.2423608
Run 10 stress 0.2270764
... New best solution
... Procrustes: rmse 0.02583723 max resid 0.1318518
Run 11 stress 0.2391517
Run 12 stress 0.2314673
Run 13 stress 0.26895
Run 14 stress 0.2286854
Run 15 stress 0.267928
Run 16 stress 0.2700468
Run 17 stress 0.2537889
Run 18 stress 0.2384427
Run 19 stress 0.2375385
Run 20 stress 0.2283212
*** Best solution was not repeated -- monoMDS stopping criteria:
17: stress ratio > sratmax
3: scale factor of the gradient < sfgrmin
Run 0 stress 0.1157083
Run 1 stress 0.1157085
... Procrustes: rmse 8.583335e-05 max resid 0.0004912752
... Similar to previous best
Run 2 stress 0.1160278
... Procrustes: rmse 0.004716377 max resid 0.02336246
Run 3 stress 0.1157086
... Procrustes: rmse 0.0001717128 max resid 0.001003597
... Similar to previous best
Run 4 stress 0.1616957
Run 5 stress 0.1621137
Run 6 stress 0.1786179
Run 7 stress 0.1157084
... Procrustes: rmse 6.139407e-05 max resid 0.000352906
... Similar to previous best
Run 8 stress 0.1205347
Run 9 stress 0.1519212
Run 10 stress 0.1160277
... Procrustes: rmse 0.004713843 max resid 0.0233734
Run 11 stress 0.1620321
Run 12 stress 0.1157085
... Procrustes: rmse 0.0001077177 max resid 0.0006285929
... Similar to previous best
Run 13 stress 0.1157086
... Procrustes: rmse 0.0001353592 max resid 0.0007914416
... Similar to previous best
Run 14 stress 0.1157084
... Procrustes: rmse 0.0004689439 max resid 0.002739212
... Similar to previous best
Run 15 stress 0.1523092
Run 16 stress 0.1157085
... Procrustes: rmse 9.503249e-05 max resid 0.0005396638
... Similar to previous best
Run 17 stress 0.1160275
... Procrustes: rmse 0.004642874 max resid 0.02385903
Run 18 stress 0.1157083
... New best solution
... Procrustes: rmse 0.0004163497 max resid 0.002433842
... Similar to previous best
Run 19 stress 0.115709
... Procrustes: rmse 0.0007016256 max resid 0.004102115
... Similar to previous best
Run 20 stress 0.1205346
*** Best solution repeated 2 times
Run 0 stress 0.0763375
Run 1 stress 0.07775061
Run 2 stress 0.07633781
... Procrustes: rmse 0.001068704 max resid 0.003996407
... Similar to previous best
Run 3 stress 0.07707051
Run 4 stress 0.07775058
Run 5 stress 0.07775028
Run 6 stress 0.07465728
... New best solution
... Procrustes: rmse 0.06885868 max resid 0.2747804
Run 7 stress 0.08233752
Run 8 stress 0.08688661
Run 9 stress 0.07633759
Run 10 stress 0.08188602
Run 11 stress 0.07717132
Run 12 stress 0.07465716
... New best solution
... Procrustes: rmse 0.0004760633 max resid 0.00264286
... Similar to previous best
Run 13 stress 0.07633821
Run 14 stress 0.07717172
Run 15 stress 0.07465766
... Procrustes: rmse 0.0002627313 max resid 0.001525966
... Similar to previous best
Run 16 stress 0.08688675
Run 17 stress 0.07775058
Run 18 stress 0.076338
Run 19 stress 0.07633738
Run 20 stress 0.07465752
... Procrustes: rmse 0.0003595795 max resid 0.002105949
... Similar to previous best
*** Best solution repeated 3 times
Run 0 stress 0.05707645
Run 1 stress 0.0557893
... New best solution
... Procrustes: rmse 0.07022627 max resid 0.2176782
Run 2 stress 0.06243419
Run 3 stress 0.05611113
... Procrustes: rmse 0.06956331 max resid 0.1407431
Run 4 stress 0.0580254
Run 5 stress 0.0564849
Run 6 stress 0.05578526
... New best solution
... Procrustes: rmse 0.002733131 max resid 0.01266276
Run 7 stress 0.05578505
... New best solution
... Procrustes: rmse 0.0002121204 max resid 0.0007407448
... Similar to previous best
Run 8 stress 0.05692241
Run 9 stress 0.05691066
Run 10 stress 0.05704814
Run 11 stress 0.05730222
Run 12 stress 0.05615029
... Procrustes: rmse 0.06344066 max resid 0.1503602
Run 13 stress 0.05635141
Run 14 stress 0.0569116
Run 15 stress 0.05692897
Run 16 stress 0.05653585
Run 17 stress 0.05819276
Run 18 stress 0.05729507
Run 19 stress 0.05691417
Run 20 stress 0.05629475
*** Best solution repeated 1 times
Run 0 stress 0.04260606
Run 1 stress 0.0417477
... New best solution
... Procrustes: rmse 0.05277545 max resid 0.157099
Run 2 stress 0.0425403
Run 3 stress 0.04131872
... New best solution
... Procrustes: rmse 0.03419711 max resid 0.09887441
Run 4 stress 0.04182947
Run 5 stress 0.04180297
... Procrustes: rmse 0.03492129 max resid 0.09960313
Run 6 stress 0.04174045
... Procrustes: rmse 0.03409862 max resid 0.09749863
Run 7 stress 0.04309811
Run 8 stress 0.04213449
Run 9 stress 0.04124068
... New best solution
... Procrustes: rmse 0.01650439 max resid 0.03808153
Run 10 stress 0.0420423
Run 11 stress 0.04128973
... Procrustes: rmse 0.03603476 max resid 0.07775525
Run 12 stress 0.04136642
... Procrustes: rmse 0.00966828 max resid 0.02268173
Run 13 stress 0.04229565
Run 14 stress 0.04135214
... Procrustes: rmse 0.007044621 max resid 0.02398355
Run 15 stress 0.0412051
... New best solution
... Procrustes: rmse 0.034451 max resid 0.08290545
Run 16 stress 0.04115615
... New best solution
... Procrustes: rmse 0.01111334 max resid 0.04020626
Run 17 stress 0.041188
... Procrustes: rmse 0.00477375 max resid 0.01914514
Run 18 stress 0.0411462
... New best solution
... Procrustes: rmse 0.009622325 max resid 0.04233931
Run 19 stress 0.04254125
Run 20 stress 0.04631473
*** Best solution was not repeated -- monoMDS stopping criteria:
20: no. of iterations >= maxit
Run 0 stress 0.03247862
Run 1 stress 0.03162475
... New best solution
... Procrustes: rmse 0.02155085 max resid 0.08697802
Run 2 stress 0.03270739
Run 3 stress 0.03182441
... Procrustes: rmse 0.02589717 max resid 0.1017713
Run 4 stress 0.03295316
Run 5 stress 0.03357546
Run 6 stress 0.03168637
... Procrustes: rmse 0.01104631 max resid 0.04886106
Run 7 stress 0.03348667
Run 8 stress 0.03333902
Run 9 stress 0.03288648
Run 10 stress 0.03278475
Run 11 stress 0.032732
Run 12 stress 0.03193441
... Procrustes: rmse 0.0320945 max resid 0.09020574
Run 13 stress 0.03442658
Run 14 stress 0.03275383
Run 15 stress 0.03301454
Run 16 stress 0.03196447
... Procrustes: rmse 0.02484452 max resid 0.09698914
Run 17 stress 0.03165316
... Procrustes: rmse 0.01545227 max resid 0.05904591
Run 18 stress 0.03196718
... Procrustes: rmse 0.03697085 max resid 0.1235515
Run 19 stress 0.03296006
Run 20 stress 0.03165424
... Procrustes: rmse 0.01361733 max resid 0.05106838
*** Best solution was not repeated -- monoMDS stopping criteria:
20: no. of iterations >= maxit
Run 0 stress 0.0264502
Run 1 stress 0.02623508
... New best solution
... Procrustes: rmse 0.06242094 max resid 0.1640684
Run 2 stress 0.02733809
Run 3 stress 0.02642284
... Procrustes: rmse 0.03836021 max resid 0.1130397
Run 4 stress 0.02667466
... Procrustes: rmse 0.04019661 max resid 0.09232111
Run 5 stress 0.02785315
Run 6 stress 0.02588081
... New best solution
... Procrustes: rmse 0.03435392 max resid 0.09821793
Run 7 stress 0.02611752
... Procrustes: rmse 0.03644499 max resid 0.1073028
Run 8 stress 0.02672231
Run 9 stress 0.02549468
... New best solution
... Procrustes: rmse 0.02970474 max resid 0.07268084
Run 10 stress 0.02630052
Run 11 stress 0.02565997
... Procrustes: rmse 0.02828194 max resid 0.07399177
Run 12 stress 0.02589466
... Procrustes: rmse 0.04976083 max resid 0.1288868
Run 13 stress 0.02651663
Run 14 stress 0.02691703
Run 15 stress 0.02743753
Run 16 stress 0.0281878
Run 17 stress 0.02655447
Run 18 stress 0.02579754
... Procrustes: rmse 0.02829488 max resid 0.09045371
Run 19 stress 0.02635704
Run 20 stress 0.02671691
*** Best solution was not repeated -- monoMDS stopping criteria:
20: no. of iterations >= maxit
Run 0 stress 0.02173106
Run 1 stress 0.02095776
... New best solution
... Procrustes: rmse 0.04068823 max resid 0.1559548
Run 2 stress 0.02191766
Run 3 stress 0.02128473
... Procrustes: rmse 0.02815982 max resid 0.07953337
Run 4 stress 0.02121923
... Procrustes: rmse 0.02842373 max resid 0.0997992
Run 5 stress 0.02157925
Run 6 stress 0.0228222
Run 7 stress 0.02107951
... Procrustes: rmse 0.04464611 max resid 0.1093655
Run 8 stress 0.0232875
Run 9 stress 0.02281427
Run 10 stress 0.02298109
Run 11 stress 0.02224492
Run 12 stress 0.02270626
Run 13 stress 0.02164192
Run 14 stress 0.02243158
Run 15 stress 0.02229288
Run 16 stress 0.02118067
... Procrustes: rmse 0.05039432 max resid 0.1416435
Run 17 stress 0.02247889
Run 18 stress 0.02202836
Run 19 stress 0.02221069
Run 20 stress 0.02235273
*** Best solution was not repeated -- monoMDS stopping criteria:
20: no. of iterations >= maxit
stress <- sapply(klist, function(x){x$stress})Now extract the stress values for each NMDS fit and plot them against dimensionality.
par(mar=c(5,5,1,1))
plot(K, stress, type="l", lwd=3,
xlab="NMDS dimensions (k)",
ylab="Stress",
ylim=c(0, max(stress)))
There is a large drop in stress from 1 to 2 dimensions, and a smaller drop from 2 to 3, and the gains in stress taper off after that. This plot suggests that 2 is sufficient, although in a real investigation you might want to at least explore the 3-dimensional solution.
27.6 Redundancy analysis (RA)
Coming soon!
27.7 Canonical correspondence analysis (CCA)
Coming soon!
27.8 Linear discriminant analysis
Coming soon!