###PCA

head(ext)
head(ext.s)

PCA <- prcomp(ext.s, center = F, scale. = F)
PCA
plot(PCA)
biplot(PCA)

library(factoextra)

fviz_pca_var(PCA, axes=c(1,2), repel=T)

fviz_pca(PCA, axes=c(1,2), repel=T, 
         geom = c("point"))

library(vegan)

PCA <- rda(ext.s, scale=F)
PCA

(eigenvals(PCA)/PCA$tot.chi)*100


biplot(PCA, display = "species", choices = c(1,2))
biplot(PCA, display = "species", choices = c(2,3))
biplot(PCA, display = "sites", choices = c(1,2))

PCA.sc <- scores(PCA, display = "sites", choices = c(1,2))
head(PCA.sc)

cor(PCA.sc)

library(berryFunctions)
colPoints(forest$X, forest$Y, PCA.sc[,1], add=F)
colPoints(forest$X, forest$Y, PCA.sc[,2], add=F)

class(dist.jac.c)

PCOA <- cmdscale(dist.jac.c, k=5)
plot(PCOA)
colPoints(forest$X, forest$Y, PCOA[,2], add=F)

plot(PCOA)
ef <- envfit(PCOA, env=ext.s, permutations=999,
             choices=c(1,2))
ef
plot(ef)

plot(PCOA, type="n")
points(PCOA, pch=21, bg=my.col[clust.ward.k5])
plot(ef)

plot(forest$X, forest$Y, pch=21, bg=my.col[clust.ward.k5])

plot(PCOA, type="n")
points(PCOA, pch=21, bg=my.col[clust.ward.k5])

ordisurf(PCOA, forest$Diversity, choices = c(1, 2),
         add=T)

plot(PCOA, type="n")
points(PCOA, pch=21, bg=my.col[clust.ward.k5])

ordisurf(PCOA, ext$Altitude, choices = c(1, 2),
         add=T)

plot(PCOA, type="n")
points(PCOA, pch=21, bg=my.col[clust.ward.k5])

ordisurf(PCOA, ext$ForestAB, choices = c(1, 2),
         add=T)


plot(forest[, c("X", "Y")], type="n")
points(forest[, c("X", "Y")], pch=21, bg=my.col[clust.ward.k5])

ordisurf(forest[, c("X", "Y")], ext$ForestAB, choices = c(1, 2),
         add=T)

NMDS <- metaMDS(dist.jac, k=3, engine = "isoMDS")
NMDS

plot(NMDS)
NMDS$points
plot(NMDS$points[,1:2], type="n")
points(NMDS$points[,1:2], pch=21, bg=my.col[clust.ward.k5])

ordisurf(NMDS$points[,1:2], ext$Limestone.and.calcareous.sediments, choices = c(1, 2),
         add=T)

library(vegan3d)
ordirgl(NMDS, col=my.col[clust.ward.k5])
rgl.bg(color="white")

hist(forest$Diversity)
hist(ext$Precipitation)
hist(log(ext$Precipitation))

x <- log(ext$Precipitation)
x
