# Ch. 2 – PCA Example

We start by importing the main packages, and generating 1000 points over a rotated ellipse.

library(ggplot2)
library(spatstat)
library(ggfortify)
# Generate 1000 points over a rotated ellipse
data.line <-  runifdisc(1000)
data.line <- affine(data.line, mat= diag(c(3,1)))
data.line <- rotate(data.line, angle=pi/4)

The ellipse can be plotted with the following code.

# Plot ellipse
plot.line <- ggplot(data.line, aes(x, y)) plot.line + geom_point(alpha = 0.3) + theme_bw()

# If we want to save it, uncomment.
# ggsave("LinearEllipse.tiff")

We now can generate a Principal Component Analysis of the rotated ellipse. The resulting one is not rotated, and is circular.

# Apply PCA

# Plot the ellipse.
plot.pca + theme_bw()

# Uncomment to save.
# ggsave("PCAEllipse.tiff")

The ellipse now is a circle and it is not rotated. The principal components can be seen over the cloud.

To get the equations describing the rotation, simply run the following code:

pca.line
Standard deviations:
[1] 1.5268614 0.4869591

Rotation:
PC1        PC2
x 0.7003205 -0.7138285
y 0.7138285  0.7003205

The resulting rotation can be expressed as:

$$\begin{pmatrix} x \\ y \end{pmatrix} = \begin{bmatrix} 0.7003205 & -0.7138285 \\ 0.7138285 & 0.7003205 \end{bmatrix} \cdot \begin{pmatrix} a \\ b \end{pmatrix}$$