Skip to main content

10.2 Principal component analysis

Bioclim data

Bioclimatic variables are derived from monthly temperature and precipitation data to provide ecologically meaningful measures of climatic conditions. They capture three main aspects of climate: annual trends (e.g., mean annual temperature), seasonal variation (e.g., annual temperature and precipitation ranges), and extreme or limiting conditions (e.g., temperature of the coldest month and precipitation of the driest quarter). By representing climatic conditions that are particularly relevant to species’ physiological tolerances and ecological requirements, bioclimatic variables are widely used in species distribution modelling and other ecological applications.

For this lab, we use the 19 standard bioclimatic variables from CHELSA (Climatologies at High Resolution for the Earth’s Land Surface Areas), version 2.1, covering the reference period 1981–2010. CHELSA is a global, high-resolution climate dataset based on downscaled ERA5 reanalysis data (Karger et al., 2021, 2017). The original data, provided at a spatial resolution of 30 arc-seconds, were aggregated to 10 arc-minutes for this lab. Ocean areas and Antarctica were excluded by applying a spatial mask.

The dataset comprises 19 bioclimatic layers (Table 13.1). To reduce storage requirements, all values are stored as integers using scaled units. Consequently, the stored values must be interpreted according to the scaling factor of each variable. For example, a value of 125 for bioclim1 represents a mean annual temperature of 12.5 °C.

Table 13.1: CHELSA bioclimatic variables, their descriptions, and units.
Variable Description Unit
bioclim1 Mean annual temperature °C × 10
bioclim2 Mean diurnal temperature range °C × 10
bioclim3 Isothermality, bioclim2/bioclim7 ratio × 1000
bioclim4 Temperature seasonality, standard deviation of the monthly mean temperatures °C × 1000
bioclim5 Maximum temperature of the warmest month °C × 10
bioclim6 Minimum temperature of the coldest month °C × 10
bioclim7 Annual temperature range, bioclim5 − bioclim6 °C × 10
bioclim8 Mean temperature of the wettest quarter °C × 10
bioclim9 Mean temperature of the driest quarter °C × 10
bioclim10 Mean temperature of the warmest quarter °C × 10
bioclim11 Mean temperature of the coldest quarter °C × 10
bioclim12 Annual precipitation mm/year
bioclim13 Precipitation of the wettest month mm/month
bioclim14 Precipitation of the driest month mm/month
bioclim15 Precipitation seasonality, coefficient of variation of the monthly precipitation %
bioclim16 Precipitation of the wettest quarter mm/quarter
bioclim17 Precipitation of the driest quarter mm/quarter
bioclim18 Precipitation of the warmest quarter mm/quarter
bioclim19 Precipitation of the coldest quarter mm/quarter

For this demonstration, we use a random global sample of 1000 pixels and four of the bioclimatic variables: mean annual temperature (bioclim1, Tmean), maximum temperature of the warmest month (bioclim5, Tmax), minimum temperature of the coldest month (bioclim6, Tmin), and annual precipitation (bioclim12, Precip).

clim <- read.csv("data/chelsa_bio_1981-2010_V.2.1_land_10arcmin_sample.csv")
head(clim)
  Tmean Tmax Tmin Precip
1  -144  121 -374    603
2   169  336    7    309
3   112  263  -33    938
4   -72  155 -302    614
5   298  406  189    595
6   222  359   25     32

Before running a PCA, it is useful to look at how the variables relate to each other. The function pairs() creates a scatter plot matrix, which shows a scatter plot for every pair of variables.

pairs(clim)

The scatter plot matrix shows that the three temperature variables are strongly correlated. Tmean is almost linearly related to both Tmin and Tmax, while Tmax and Tmin are related less tightly. Precip shows no clear linear relationship with the temperature variables, and its distribution is strongly right-skewed. If we used all four variables as predictors in a regression model, we would face multicollinearity. Correlated predictors inflate the standard errors of the coefficients, which leads to wider confidence intervals and less reliable inference. For example, it would be difficult to tell whether an effect is due to Tmean or Tmin.

One way to reduce multicollinearity is to drop variables based on correlation coefficients or scientific knowledge. This works well if there is prior knowledge about the variables, but it becomes cumbersome for larger sets of predictors. An alternative is principal component analysis (PCA). PCA reduces the dimensionality of the data, i.e. fewer variables are needed to capture most of the variation, and it yields uncorrelated components.

Fit PCA

There are two functions in R for performing a PCA: princomp() and prcomp(). princomp() computes the eigenvalues and eigenvectors of the correlation or covariance matrix using eigen(), whereas prcomp() uses a singular value decomposition (svd()) of the data matrix, which is numerically more stable. Here, we use prcomp().

pca <- prcomp(clim, scale. = TRUE)

Setting scale. = TRUE standardizes each variable to unit variance before the PCA is computed (the default is scale. = FALSE). This is important when the variables have different units or ranges, as in our case (°C × 10 vs. mm/year). Otherwise, the variable with the largest variance, here Precip, would dominate the principal components. Alternatively, you can standardize the data with scale() and pass the standardized data to prcomp().

Scores

The prcomp object stores both the transformation (the rotation matrix, see Rotation coefficients) and the transformed data. The transformed values are called scores: the coordinates of each observation on the principal components. You can access the scores with pca$x:

pca_scores <- data.frame(pca$x)
head(pca_scores)
         PC1         PC2         PC3          PC4
1 -3.2918525  0.14072126  0.18696822 -0.052708205
2  0.4686530 -0.85063718  0.08329705 -0.020806229
3 -0.2092080  0.05625645 -0.01871303 -0.003984131
4 -2.5489684  0.04042014  0.13036294  0.050216826
5  2.0666701 -0.76334652 -0.01898270 -0.020942486
6  0.8417253 -1.22488155  0.02868711  0.163802801

The scores form a new set of variables, named PC1 to PC4. In contrast to the original climate variables, the principal components are uncorrelated, as the scatter plot matrix below shows.

pairs(pca_scores)

You can apply the fitted transformation to any dataset with the same variables using predict(). This is useful, for example, to transform new observations or an entire raster into the PCA space. In the example below, we apply the transformation to the same data that was used to fit the PCA. Hence, the results are identical to the scores stored in pca$x.

predicted_pca_scores <- predict(pca, clim)
head(predicted_pca_scores)
            PC1         PC2         PC3          PC4
[1,] -3.2918525  0.14072126  0.18696822 -0.052708205
[2,]  0.4686530 -0.85063718  0.08329705 -0.020806229
[3,] -0.2092080  0.05625645 -0.01871303 -0.003984131
[4,] -2.5489684  0.04042014  0.13036294  0.050216826
[5,]  2.0666701 -0.76334652 -0.01898270 -0.020942486
[6,]  0.8417253 -1.22488155  0.02868711  0.163802801

Rotation coefficients

The PCA transformation is defined by the rotation coefficients, also called loadings. Each column of the rotation matrix is an eigenvector and holds the coefficients of one principal component. You can access the rotation matrix of a prcomp object as follows:

pca$rotation
             PC1         PC2        PC3          PC4
Tmean  0.5976109 -0.05441656 -0.1452895  0.786632709
Tmax   0.5296984 -0.37328673  0.7005468 -0.298849010
Tmin   0.5782788  0.13357678 -0.5965455 -0.540263228
Precip 0.1669564  0.91643500  0.3636737  0.003727598

The coefficients describe how each principal component is a linear combination of the (standardized) input variables. You can think of it as a cooking recipe: the coefficients specify how much of each climate variable is needed to “cook up” a principal component. For PC1, the recipe is:

\[PC1 = 0.598 \cdot Tmean + 0.53 \cdot Tmax + 0.578 \cdot Tmin + 0.167 \cdot Precip\]

Let’s apply this recipe to the first observation in our dataset. Because we set scale. = TRUE in prcomp(), we first need to standardize the variables to mean zero and unit variance (z-scores) using scale().

# first observation (standardized)
clim_obs <- head(scale(clim), 1)
clim_obs
         Tmean      Tmax     Tmin     Precip
[1,] -2.043531 -1.649487 -1.96787 -0.3528351
# rotation coefficients of PC1
pca1_coeff <- pca$rotation[, 1]
pca1_coeff
    Tmean      Tmax      Tmin    Precip 
0.5976109 0.5296984 0.5782788 0.1669564 

Multiplying the two vectors is a vectorized operation: each standardized value is multiplied with its corresponding coefficient. Summing up the products gives the PC1 score of that observation.

sum(clim_obs * pca1_coeff)
[1] -3.291853

PC1 is the transformation (the recipe), and the score is the value you obtain when applying the transformation to an observation. Let’s compare our result with the score computed by prcomp():

head(pca$x, 1)
           PC1       PC2       PC3         PC4
[1,] -3.291853 0.1407213 0.1869682 -0.05270821

The magnitude of the coefficients reflects how much each variable contributes to a principal component. On PC1, Tmean, Tmax, and Tmin have large coefficients of similar size, whereas the coefficient of Precip is small. So, PC1 mainly represents a temperature gradient. On PC2, in contrast, Precip has by far the largest coefficient, i.e. PC2 mainly represents a moisture gradient.

The sign of the coefficients tells us about the direction of the relationship. On PC1, all four coefficients have the same sign, so all variables change in the same direction along PC1. Note, however, that the direction of an eigenvector is arbitrary: flipping the signs of all coefficients of a component gives an equally valid solution.

\[PC_i \hat{=} -PC_i\]

So, do not get attached to the absolute sign of a coefficient. What matters is whether variables have the same or opposite signs on a component. For example, on PC2, Precip and Tmax have opposite signs, i.e. they form a contrast: high values of one go along with low values of the other. PC2 can be interpreted as a moisture (or aridity) gradient: it mainly increases with precipitation and, to a lesser extent, with lower summer maximum temperatures. High PC2 scores indicate wet places with relatively moderate summer maxima, low PC2 scores indicate dry places with relatively hot summers. Interpreting such patterns always requires knowledge of the underlying ecological or climatological processes, e.g. related to elevation, latitude, or continentality.

Eigenvalues

To see how the total variance of our four climate variables is distributed among the principal components, we look at the eigenvalues. The eigenvalues are the variances of the principal components (one for each component). Because we standardized the variables, each variable has a variance of one, and the eigenvalues sum up to the number of variables (here four). The prcomp object stores the square roots of the eigenvalues, i.e. the standard deviations of the components:

pca$sdev
[1] 1.6653297 1.0371581 0.3816833 0.0727868

From this, we can calculate the fraction of the total variance explained by each component (its variance divided by the sum of all component variances):

var_exp <- data.frame(pc = 1:4,
                      var_exp = pca$sdev^2 / sum(pca$sdev^2))

# add the variances cumulatively
var_exp$var_exp_cumsum <- cumsum(var_exp$var_exp)
var_exp
  pc     var_exp var_exp_cumsum
1  1 0.693330759      0.6933308
2  2 0.268924222      0.9622550
3  3 0.036420539      0.9986755
4  4 0.001324479      1.0000000

A scree plot shows the component variances against the component number. The idea is to look for an “elbow”, i.e. the point after which the explained variance levels off. Components after the elbow add little information.

par(mfrow=c(1,2))
plot(var_exp$pc, var_exp$var_exp, type="b", col=4,
     ylab="Fraction of explained variance", xlab="Principal component")
plot(var_exp$pc, var_exp$var_exp_cumsum, type="b", col=6,
     ylab="Cumulative fraction of explained variance", xlab="Principal component")

You are probably not surprised that there is an easier way:

summary(pca)
Importance of components:
                          PC1    PC2     PC3     PC4
Standard deviation     1.6653 1.0372 0.38168 0.07279
Proportion of Variance 0.6933 0.2689 0.03642 0.00132
Cumulative Proportion  0.6933 0.9623 0.99868 1.00000

PC1 alone explains 69.3% of the variance, PC2 26.9%, PC3 3.6%, and PC4 only 0.13%. Together, the first two components capture 96.2% of the variance. Hence, we can reduce our four correlated climate variables to two uncorrelated components, the temperature gradient (PC1) and the moisture gradient (PC2), without losing much information.

Correlation analysis

Another way to interpret the principal components is to look at the correlations between the PC scores and the original variables. A variable that is strongly correlated with a component contributes much to it. Explore the scatter plot matrix below and look at how PC1 is related to the original variables. Compare this with your interpretation of the rotation coefficients. Then do the same for PC2, PC3, and PC4.

df <- cbind(clim, pca_scores)
pairs(df)

The same information in numbers: the correlation coefficients between the original variables (rows) and the principal components (columns).

round(cor(clim, pca_scores), 2)
        PC1   PC2   PC3   PC4
Tmean  1.00 -0.06 -0.06  0.06
Tmax   0.88 -0.39  0.27 -0.02
Tmin   0.96  0.14 -0.23 -0.04
Precip 0.28  0.95  0.14  0.00

Biplot

A biplot shows the variables and the observations in one graphic:

  • Observations (here our 1000 sampled pixels) are plotted as points (or labels) by their PC scores. Their axes are at the bottom and left.
  • Variables are drawn as arrows from the origin. Their axes are at the top and right.

With standardized variables, as in our case, the x-coordinate of an arrow tip is the correlation of the variable with the first component shown (e.g. PC1), and the y-coordinate is its correlation with the second component (e.g. PC2) (see the correlation table in the previous section). R multiplies all arrows by the same constant so that they fit the plot.

How to read the arrows:

  • Direction: the variable increases in the direction of the arrow, i.e. observations in the direction of an arrow tend to have high values of that variable. An arrow that points along a PC axis is correlated mainly with that component.
  • Angle between arrows: a small angle indicates a strong positive correlation, an angle of about 90° indicates little correlation, and arrows pointing in opposite directions indicate a negative correlation.
  • Length: longer arrows indicate variables that are better represented by the two components shown. In our case, all four arrows are of similar length, because PC1 and PC2 together capture almost all of their variance.

By default, biplot() shows PC1 and PC2. Note, there are other implementations of biplots in different packages (e.g. PCAtools, ggbiplot).

biplot(pca)

The biplot confirms our interpretation of the rotation coefficients. The arrows of Tmean, Tmax, and Tmin point in a similar direction along the PC1 axis, i.e. they are strongly correlated with each other and together define the temperature gradient. The Precip arrow points mainly along the PC2 axis and is almost perpendicular to the temperature arrows, i.e. precipitation is largely unrelated to temperature and defines the moisture gradient. The Tmax arrow is slightly tilted away from Precip, reflecting the contrast between precipitation and summer maximum temperature on PC2.

With choices you can select other components, e.g. PC1 and PC3. Because the observation labels (row numbers) clutter the plot, we replace them with dots using xlabs.

biplot(pca, choices=c(1,3), xlabs=rep('.', nrow(pca$x)))

Both Tmax and Tmin still point mainly along PC1, but on the PC3 axis they point to opposite sides. PC3 therefore contrasts places with hot summers and cold winters with places where summer and winter temperatures are similar, i.e. it reflects the annual temperature range, often referred to as continentality. However, PC3 explains only a small fraction of the total variance (see Eigenvalues).

prcomp vs princomp

Both functions perform a PCA and give practically the same results, but they store them under different names (Table 13.2), which matters when you read code or tutorials that use the other function. Small differences may occur because the signs of the loadings can be flipped and princomp() divides by \(n\) instead of \(n-1\) when computing the variances. Also, princomp() only works if there are more observations than variables, whereas prcomp() has no such limitation.

Table 13.2: Comparison between prcomp and princomp.
Description prcomp() princomp()
Decomposition method svd() eigen()
Standard deviations of the principal components sdev sdev
Matrix of variable loadings (columns are eigenvectors) rotation loadings
Variable means (means that were subtracted) center center
Variable standard deviations (the scalings applied to each variable) scale scale
Coordinates of observations on the principal components x scores

References

Karger, D.N., Conrad, O., Böhner, J., Kawohl, T., Kreft, H., Soria-Auza, R.W., Zimmermann, N.E., Linder, H.P., Kessler, M., 2021. Climatologies at high resolution for the earth’s land surface areas. https://doi.org/10.16904/envidat.228
Karger, D.N., Conrad, O., Böhner, J., Kawohl, T., Kreft, H., Soria-Auza, R.W., Zimmermann, N.E., Linder, H.P., Kessler, M., 2017. Climatologies at high resolution for the earth’s land surface areas. Scientific Data 4, 170122. https://doi.org/10.1038/sdata.2017.122