-
Notifications
You must be signed in to change notification settings - Fork 0
/
Cucurbit_leaf_analysis_PCA_ggplot2.R
257 lines (176 loc) · 8.69 KB
/
Cucurbit_leaf_analysis_PCA_ggplot2.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# Cucurbits PCA + ggplot2
# Load needed packages from library
# OPTIONAL - If packages not yet installed - install.packages("package_name")
# To install ggbiplot - load library(devtools), then - install_github("vqv/ggbiplot")
# Load excel reader
library(readxl)
#Load ggplot2
library(ggplot2)
# lOAD ggally after ggplot2
library(GGally)
# lOAD tidyverse or magrittr for pipe operator (%>%) after ggplot2
library(tidyverse)
# Load ggbiplot using require
require(ggbiplot)
# Set working directory first
setwd("C:/Users/company/Desktop/R_Analysis_Cucurbit_Measures")
# Import the Leaf Measures from Excel
Cucurbit_Leaf <- read_excel("Cucurbit_Morphometrics.xlsx",
sheet = "Leaf_Measures")
# OPTIONAL - View the leaves data in window
View(Cucurbit_Leaf)
# Import the Teeth Measures from Excel
Cucurbit_Teeth <- read_excel("Cucurbit_Morphometrics.xlsx",
sheet = "Teeth_Measures")
# OPTIONAL - View the teeth data in window
View(Cucurbit_Teeth)
# Import the bandWidth Measures from Excel
Cucurbit_BW <- read_excel("Cucurbit_Morphometrics.xlsx",
sheet = "bandWidth")
# View the bandwidth data in window
View(Cucurbit_BW)
# OPTIONAL - View the file in console - head(insert_filename)
# OPTIONAL - For data summary in console - summary(insert_filename)
# OPTIONAL - get column names - colnames(insert_filename)
# PAIRWISE SCATTERPLOT
# Before PCA, plot pairwise scatterplot to check variables correlation
# This is to check and take high dimensional data that is
# Highly correlated and reduce dimensionality
# Check meaning of "[4:9]" below - to select columns 4 to 9
# check plot on the plot window on the right
# ALTERNATIVE - Plot pairwise scatterplot using pairs on base
# (remove hashes below)
#pairs(Cucurbit_Leaf[4:9]), pair =panel.smooth)
# optional - column names
colnames(Cucurbit_Leaf)
# ALTERNATIVE - plot pairwise scatter plot matrix with GGally no color
# (remove hashes below)
#Cucurbit_Leaf %>% ggpairs(columns = c("Blade_Length",
# "Blade_Width_BB", "Blade_Area",
# "Blade_Perimeter", "Blade_Width_IS"),
# upper = list(continuous = wrap('cor', size = 8)))
# Pairwise scatterplot matrix with GGally, coloring by species
Leaf_PW_Scatterplot = Cucurbit_Leaf %>% mutate(Species = factor(Species), scale = TRUE) %>%
ggpairs(columns = c("Blade_Length", "Blade_Width_BB",
"Blade_Area", "Blade_Perimeter", "Blade_Width_IS"),
aes(color = Species),
upper = list(continuous = wrap('cor', size = 3)),
lower = list(combo = wrap("facethist", bins = 30)),
diag = list(continuous = wrap("densityDiag", alpha = 0.5)))
# View Pairwise scatterplot
Leaf_PW_Scatterplot
# Add title to Leaf PW using labs fxn. Rename it to version 2 of your scatterplot
Leaf_PW_Scatterplot2 = Leaf_PW_Scatterplot+labs (title = "Coefficient Matrix of Cucurbitaceae leaves blade data set",
subtitle="scatterplot showing all major leaf blade variables",
colour = "Species")
# View titled biplot
Leaf_PW_Scatterplot2
# PLOT PCA
# Use numerical data not categorical dat
# Use cbind or prcomp then run PCA. I use prcomp so I can supply scale
# Select working columns or subset data for PCA
# The filename is the data frame [4:9] represents columns 4 to 9
# [, -5] or [, -1, -2] represent minus column 5 or minus column 1 and 2
# For specific column use prcomp(-column 1 title + column 2 title, data = file.name)
# Ensure the PCA "<-" name is different from the file name. I use "MyPC"
# Try to always scale your data as TRUE - scale = TRUE
# scaling has no disadvantage. It does not change relationship
# Circle = TRUE can only work if scale is set as TRUE
# Run PCA + select PCA working columns (scaled)
MyPC <- prcomp(Cucurbit_Leaf[4:9], scale = TRUE)
# OPTIONAL - View MyPC for confirmation
MyPC
# OPTIONAL - PCA Summary - importance of components
summary(MyPC)
# Plot screeplot to show variances across each principal components
# Variance is the square of the standard deviation.
# most of the data variability will be accounted for in the 1st and 2nd PC
# Use either bar or lines. (LINE PREFERABLY)
# ALTERNATIVE - plot screeplot in bars (remove hash below)
#plot(MyPC)
# plot screeplot in lines/l
plot(MyPC, type = "l")
# To interpret PC, use biplot or ggbiplot
# It shows how each components and variable agree with each other
# Scale it to zero to make the axis more interpretable
# ALTERNATIVE Plot biplot - biplot(MyPC, scale = 0)
# ALTERNATIVE - Plot ggbiplot without aesthetics - Leaf_bplot <- ggbiplot(MyPC)
# Plot ggbiplot without aesthetics + title using labs fxn.
Leaf_bplot = ggbiplot(pcobj = MyPC, choices = c(1,2),
obs.scale = 1, var.scale = 1,
labels = row.names(Cucurbit_Leaf), labels.size = 6,
varname.size = 8, varname.abbrev = TRUE,
var.axes = TRUE, circle = TRUE,
ellipse = TRUE, groups = Cucurbit_Leaf$Species)
# View the biplot
Leaf_bplot
#Add Title
Leaf_bplot2 = Leaf_bplot+labs (title = "PCA of Cucurbitaceae leaves data set",
subtitle="Space of best fit for each species",
colour = "Species") +
theme(axis.text = element_text(size=20), axis.title = element_text(size = 20),
legend.position = "bottom",legend.key.height = unit(1, 'cm'),
legend.key.width = unit(1, 'cm'), legend.title = element_text(size=20),
legend.text = element_text(size=20))
# View
Leaf_bplot2
########IGNORE FROM HERE
# ALTERNATIVE WAY TO VIEW PCA SCATTERPLOT ON GGPLOT2
# biplot may not the best way to represent or look for patterns in data
# after the data has been projected onto the new PC.
# So, instead, extract PC1 and PC2, attach them to the data frame
# and plot using ggplot
# First examine the structure to see that PCs have values
# for sdev, rotation, center, scale and x
# OPTIONAL - Examine the structure
str(MyPC)
# x values are the PC scores for each observation
# every obs in the dataframe gives score for PC 1 to ....6
# they are coordinates. Where each obs are found
# OPTIONAL - EXTRACT PC SCORES
MyPC$x
# Then take PC score for PC1 and PC2 and attach to the
# file dataframe so that it can be plotted more nicely
# create a new dataframe (a version 2) for the file using cbind
# a version 2 should be another name (filename 2) - M.charantia2 here
# combine dataframes and plot with ggplot2
# Combine dataframes
Cucurbit_Leaf2 <- cbind(Cucurbit_Leaf, MyPC$x[,1:6])
# View combined dataframe
head(Cucurbit_Leaf2)
# before plotting, supply the version2 dataframe
# load the aesthetic (aes) function
# color the species/slice_name and fill species/slice_name
# Layer (+) stat ellipse polygon geom to show the 95% CI of the data
# with color and line
# Layer (+) geom points with shape and color
# Plot with ggplot2
Leaf_biplot_alternative = ggplot(Cucurbit_Leaf2, aes(x=PC1, y=PC2, col = Species, fill = Species)) +
stat_ellipse(geom = "polygon", col = "black", alpha = 0.5) +
geom_point(shape = 21, col = "black") +
labs(title="PCA of Cucurbitaceae leaves data set",
subtitle="Space of best fit for each species")
# View Leaf biplot alternative
Leaf_biplot_alternative
########IGNORE TO HERE
# RUN CORRELTATION COEFFICIENT BETWEEN VARIABLES AND PCS
# Instead of biplot to interpret relationship between each variables and PC,
# statistically, you can look at correlations between the original variables
# and the PCs to interpret how one PC changes, whether the variables go up
# or down and by how much. It's a pearson correlation coefficient
# Correlation between variables and PCs
cor(Cucurbit_Leaf2[4:9], Cucurbit_Leaf2[14:19])
# PLOT CORRELATION MATRIX BETWEEN VARIABLES
# ALTERNATIVE - Plot correlation matrix
# plot your data scaled if the unit of the variables are different
# to plot matric (unscaled) - plot(Cucurbit$Blade_Length, Cucurbit$Blade_Width_BB)
# to plot matrix (scaled) - plot(scale(Cucurbit$Blade_Length), scale(Cucurbit$Blade_Width_BB))
# Add superscript (square) to cm in label - "label"~(cm^2)
# Plot Correlation Matrix within leaves variables
colnames(Cucurbit_Leaf2)
#Length vs Width, Blade perimeter vs PC1
ggplot(Cucurbit_Leaf2, aes(Blade_Length, Blade_Perimeter, col=Species, fill=Species)) +
geom_smooth(method = lm) + geom_point(shape=21) +
labs(title="Blade Length vs Blade Perimeter") +
xlab("Blade Length")+
ylab("Blade Perimeter")