-
Notifications
You must be signed in to change notification settings - Fork 1
/
EAChat_Test_EADemo.R
563 lines (495 loc) · 20.1 KB
/
EAChat_Test_EADemo.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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
## Ref: https://zhuanlan.zhihu.com/p/432284358
## Ref: https://zhuanlan.zhihu.com/p/377356510 #With GOCluster
################################################################################
##### Presetting ######
rm(list = ls()) # Clean variable
memory.limit(150000)
Set_TarGenename <- "TOP2A"
Save_Path <- paste0("20231213_EAChat_Test_",Set_TarGenename)
if (!dir.exists(Save_Path)){dir.create(Save_Path)} ## Create new folder
SetExport_Name <- "20231213_2"
##### Load Packages #####
source("FUN_Package_InstLoad.R")
PKG_Basic.set <- c("tidyverse","ggplot2","Seurat","SeuratData","patchwork","plyr","eoffice","DT")
PKG_BiocManager.set <- c("clusterProfiler","enrichplot","pathview","limma")
FUN_Package_InstLoad(Basic.set = PKG_Basic.set, BiocManager.set = PKG_BiocManager.set)
##### Function setting #####
## Call function
source("FUN_DistrPlot_GE.R")
source("FUN_Beautify_ggplot.R")
# source("FUN_Find_Markers.R")
# source("FUN_GSEA_LargeGeneSet.R")
# source("FUN_GSEA_ggplot.R")
source("FUN_ggPlot_vline.R")
source("FUN_GSEA_ANAL.R")
source("FUN_VolcanoPlot.R")
##### Import setting and data loading* #####
## Set Import path
SetInputPath_FOL <- "Input_TCGA" # Input Folder Name
SetInput_GE <- "Xena_TCGA_LGG_GE"
SetInput_Meta <- "TCGA.LGG.sampleMap_LGG_clinicalMatrix"
## Load Gene expression file
GeneExp.df <- read.table(paste0(SetInputPath_FOL,"/",SetInput_GE), header=T, row.names = 1, sep="\t")
colnames(GeneExp.df) <- gsub("\\.", "-", colnames(GeneExp.df))
## Load Metadata file
Metadata.df <- read.table(paste0(SetInputPath_FOL,"/",SetInput_Meta), header=T, sep="\t")
row.names(Metadata.df) <- Metadata.df[,1]
## Reorder the Metadata.df
Metadata.df <- left_join(data.frame("sampleID"=colnames(GeneExp.df)),
Metadata.df)
row.names(Metadata.df) <- Metadata.df[,1]
##### Conditions setting* #####
Set_Species <- "Homo sapiens"
Set_GroupMode <- "GoupByGeneExp" # "GoupByPheno", "GoupByGeneExp"
if(Set_GroupMode == "GoupByPheno"){
Set_GroupCond <- list(GroupType = "sample_type",
GroupPair = c("Primary Tumor","Recurrent Tumor"))
}else if(Set_GroupMode == "GoupByGeneExp"){
Set_TarGene_name = Set_TarGenename
Set_TarGene <- list(TarGeneName = Set_TarGene_name,
GEGroupMode = "Mean", # c("Mean","Mean1SD","Mean2SD","Mean3SD","Median","Quartile","Customize"))
UpCutoff = 1, LowerCutoff = 1)
Set_GroupCond <- list(GroupType = Set_TarGene_name, GroupPair = c("High","Low") ) ## DEG by GeneExp group
}else{
print("Please set Set_GroupMode by GoupByPheno or GoupByGeneExp")
}
##### Grouping by GeneExp #####
if(Set_GroupMode == "GoupByGeneExp"){
source("FUN_Group_GE.R")
GeneExp_group.set <- FUN_Group_GE(GeneExp.df, Metadata.df,
TarGeneName = Set_TarGene_name, GroupSet = Set_TarGene,
Save.Path = Save_Path, ExportName = SetExport_Name)
Metadata.df <- GeneExp_group.set[["AnnoNew.df"]]
GeneExp_high.set <- GeneExp_group.set[["GeneExp_high.set"]]
GeneExp_low.set <- GeneExp_group.set[["GeneExp_low.set"]]
}
## Set DEG Analysis
Set_DEGThr.lt <- list(LogFC = c("logFC",1), pVal = c("PValue",0.05) )
## - [] Add Metric for ranking gene
## - [] Modify DGE
##### Run Differential Expression Gene(DEG) analysis in R #####
#### Run DEG ####
source("RUN_DEG_Analysis.R")
DEG_Extract.df <- DEG_ANAL.lt[["DEG_Extract.df"]]
DEG_Extract_S.df <- DEG_Extract.df[abs(DEG_Extract.df$logFC) > 1.5 & DEG_Extract.df$FDR < 0.01,]
write.table(DEG_Extract_S.df, file = paste0(Save_Path,"/DEG_Extract_S_",SetExport_Name,".tsv"),
sep="\t", row.names= F, quote = FALSE)
dif_mat <- DEG_Extract_S.df
# dif_mat <- GeneExp.df[1:1000,]
################################################################################
library(clusterProfiler) # Enrichment analysis R package
library(stringr) # Line break for labels
library(AnnotationDbi)
library(org.Hs.eg.db) # Reference species gene annotation database (hg19)
library(DOSE)
library(ggplot2) # Plotting
library(ggrepel) # Label-related
# Convert gene symbols to Entrez IDs to prevent analysis errors
id_list <- mapIds(org.Hs.eg.db, rownames(dif_mat), "ENTREZID", "SYMBOL")
# Remove cases where the conversion was not successful, i.e., id = NA
id_list <- na.omit(id_list)
# GO enrichment analysis
go <- enrichGO(gene = id_list, # Entrez ID list
OrgDb = org.Hs.eg.db, # Specify species database
keyType = "ENTREZID", # Specify the given name type
ont = "ALL", # Optional: BP (Biological Process) / CC (Cellular Component) / MF (Molecular Function) / ALL (Specify all)
pAdjustMethod = "BH", # P-value adjustment method, can also be FDR
pvalueCutoff = 0.05, qvalueCutoff = 0.2, # p/q value thresholds
readable = TRUE # Convert ID to symbol
)
go.res <- data.frame(go) # Convert GO results to a data frame for subsequent analysis (optional, depends on personal preference)
# write.csv(go.res, "Table_GO_result.csv", quote = FALSE) # Output GO enrichment analysis results
# Create a barplot for GO enrichment analysis. By default, select the top ten terms sorted by q-value for plotting.
goBP <- subset(go.res, subset = (ONTOLOGY == "BP"))[1:20,]
goCC <- subset(go.res, subset = (ONTOLOGY == "CC"))[1:20,]
goMF <- subset(go.res, subset = (ONTOLOGY == "MF"))[1:20,]
go.df <- rbind(goBP, goCC, goMF)
# Ensure that the order of GO terms in the plot matches the input
go.df$Description <- factor(go.df$Description, levels = rev(go.df$Description))
go.df <- go.df[!is.na(go.df$ONTOLOGY),]
# Create the plot
go_bar_ori <- ggplot(data = go.df, # Data for plotting
aes(x = reorder(Description, Count), y = Count)) +
geom_bar(stat = "identity", width = 0.9) + # Create a bar chart with specified width
coord_flip() + theme_bw() + # Flip the x and y axes and remove background color
scale_x_discrete(labels = function(x) str_wrap(x, width = 50)) + # Wrap term names when they are too long
labs(x = "GO terms", y = "Gene Number", title = "Barplot of Enriched GO Terms") + # Set axis labels and title
theme(axis.title = element_text(size = 13), # Axis title size
axis.text = element_text(size = 11), # Axis label size
plot.title = element_text(size = 14, hjust = 0.5, face = "bold"), # Title settings
legend.title = element_text(size = 13), # Legend title size
legend.text = element_text(size = 11), # Legend label size
plot.margin = unit(c(0.5, 0.5, 0.5, 0.5), "cm")) # Plot margins
go_bar_ori
# Create the plot
go_bar <- ggplot(data = go.df, # Data for plotting
aes(x = Description, y = Count, fill = ONTOLOGY)) + # X-axis and color fill classification
geom_bar(stat = "identity", width = 0.9) + # Create a bar chart with specified width
coord_flip() + theme_bw() + # Flip the x and y axes and remove background color
scale_x_discrete(labels = function(x) str_wrap(x, width = 50)) + # Wrap term names when they are too long
labs(x = "GO terms", y = "Gene Number", title = "Barplot of Enriched GO Terms") + # Set axis labels and title
theme(axis.title = element_text(size = 13), # Axis title size
axis.text = element_text(size = 11), # Axis label size
plot.title = element_text(size = 14, hjust = 0.5, face = "bold"), # Title settings
legend.title = element_text(size = 13), # Legend title size
legend.text = element_text(size = 11), # Legend label size
plot.margin = unit(c(0.5, 0.5, 0.5, 0.5), "cm")) # Plot margins
go_bar
## Sort
library(dplyr)
go.df <- go.df %>%
arrange(ONTOLOGY, Count) %>%
mutate(Description = factor(Description, levels = unique(Description)))
go_bar <- ggplot(data = go.df, # Data for plotting
aes(x = Description, y = Count, fill = ONTOLOGY)) +
geom_bar(stat = "identity", width = 0.9) +
coord_flip() + theme_bw() +
scale_x_discrete(labels = function(x) str_wrap(x, width = 50)) +
labs(x = "GO terms", y = "Gene Number", title = "Barplot of Enriched GO Terms") +
theme(axis.title = element_text(size = 13),
axis.text = element_text(size = 11),
plot.title = element_text(size = 14, hjust = 0.5, face = "bold"),
legend.title = element_text(size = 13),
legend.text = element_text(size = 11),
plot.margin = unit(c(0.5, 0.5, 0.5, 0.5), "cm"))
go_bar
go_bar_ori[["data"]] %>% head()
write.table(go_bar_ori[["data"]], file = paste0(Save_Path,"/GO_Result_",SetExport_Name,".tsv"),
sep="\t", row.names= F, quote = FALSE)
pdf(file = paste0(Save_Path,"/BarPlot_",SetExport_Name,".pdf"),
width = 10, height = 8)
go_bar_ori %>% print()
go_bar %>% print()
dev.off()
save.image(paste0(Save_Path,"/EAChat_",SetExport_Name,".RData"))
# ggsave(go_bar, filename = "GO_Barplot.pdf", width = 9, height = 7)
####################################################################################################
# Load the necessary library if not already loaded
# install.packages("data.table")
library(data.table)
# Define the terms
terms <- c(
"vesicle transport along actin filament",
"actin filament-based transport",
"GPI anchor biosynthetic process",
"GPI anchor metabolic process",
"glycolipid biosynthetic process",
"protein lipidation",
"cell adhesion mediated by integrin",
"phosphatidylinositol biosynthetic process",
"phosphatidylinositol metabolic process",
"glycerophospholipid biosynthetic process",
"sodium:potassium-exchanging ATPase complex",
"messenger ribonucleoprotein complex",
"complex of collagen trimers",
"SCF ubiquitin ligase complex",
"microvillus",
"myosin complex",
"integrin complex",
"protein complex involved in cell adhesion",
"actin-based cell projection",
"external side of plasma membrane",
"chromatin-protein adaptor activity",
"complement component C3b binding",
"voltage-gated chloride channel activity",
"insulin-like growth factor I binding",
"voltage-gated monoatomic anion channel activity",
"P-type ion transporter activity",
"opsonin binding",
"insulin-like growth factor binding",
"microfilament motor activity",
"integrin binding"
)
# Create groups based on common themes or categories
groups <- list(
"Actin Filament" = c(
"vesicle transport along actin filament",
"actin filament-based transport",
"microfilament motor activity"
),
"GPI Anchor" = c(
"GPI anchor biosynthetic process",
"GPI anchor metabolic process",
"glycolipid biosynthetic process",
"protein lipidation"
),
"Cell Adhesion" = c(
"cell adhesion mediated by integrin",
"protein complex involved in cell adhesion",
"integrin binding"
),
"Phosphatidylinositol" = c(
"phosphatidylinositol biosynthetic process",
"phosphatidylinositol metabolic process",
"glycerophospholipid biosynthetic process"
),
"Protein Complex" = c(
"sodium:potassium-exchanging ATPase complex",
"messenger ribonucleoprotein complex",
"complex of collagen trimers",
"SCF ubiquitin ligase complex",
"myosin complex",
"integrin complex"
),
"Membrane" = c(
"microvillus",
"external side of plasma membrane",
"voltage-gated chloride channel activity",
"voltage-gated monoatomic anion channel activity",
"P-type ion transporter activity"
),
"Binding" = c(
"chromatin-protein adaptor activity",
"complement component C3b binding",
"insulin-like growth factor I binding",
"opsonin binding",
"insulin-like growth factor binding"
)
)
# Create a dataframe with an additional "Group" column
go.df$Group <- unlist(lapply(terms, function(term) {
for (group in names(groups)) {
if (term %in% groups[[group]]) {
return(group)
}
}
return("Other") # Set to NA if term does not belong to any group
}))
# Print the updated dataframe
print(go.df)
## Sort
library(dplyr)
go.df <- go.df %>%
arrange(Group, Count) %>%
mutate(Description = factor(Description, levels = unique(Description)))
go_bar_GPT <- ggplot(data = go.df, # Data for plotting
aes(x = Description, y = Count, fill = Group)) +
geom_bar(stat = "identity", width = 0.9) +
coord_flip() + theme_bw() +
scale_x_discrete(labels = function(x) str_wrap(x, width = 50)) +
labs(x = "GO terms", y = "Gene Number", title = "Barplot of Enriched GO Terms") +
theme(axis.title = element_text(size = 13),
axis.text = element_text(size = 11),
plot.title = element_text(size = 14, hjust = 0.5, face = "bold"),
legend.title = element_text(size = 13),
legend.text = element_text(size = 11),
plot.margin = unit(c(0.5, 0.5, 0.5, 0.5), "cm"))
go_bar_GPT
###############################################################################
#### Cancer Related ####
# Load the necessary library if not already loaded
# install.packages("data.table")
library(data.table)
# Define the terms
terms <- c(
"vesicle transport along actin filament",
"actin filament-based transport",
"GPI anchor biosynthetic process",
"GPI anchor metabolic process",
"glycolipid biosynthetic process",
"protein lipidation",
"cell adhesion mediated by integrin",
"phosphatidylinositol biosynthetic process",
"phosphatidylinositol metabolic process",
"glycerophospholipid biosynthetic process",
"sodium:potassium-exchanging ATPase complex",
"messenger ribonucleoprotein complex",
"complex of collagen trimers",
"SCF ubiquitin ligase complex",
"microvillus",
"myosin complex",
"integrin complex",
"protein complex involved in cell adhesion",
"actin-based cell projection",
"external side of plasma membrane",
"chromatin-protein adaptor activity",
"complement component C3b binding",
"voltage-gated chloride channel activity",
"insulin-like growth factor I binding",
"voltage-gated monoatomic anion channel activity",
"P-type ion transporter activity",
"opsonin binding",
"insulin-like growth factor binding",
"microfilament motor activity",
"integrin binding"
)
# Create groups based on cancer-related mechanisms
cancer_mechanisms <- list(
"Cell Adhesion and Migration" = c(
"cell adhesion mediated by integrin",
"protein complex involved in cell adhesion",
"integrin binding"
),
"Signal Transduction" = c(
"chromatin-protein adaptor activity",
"complement component C3b binding",
"insulin-like growth factor I binding",
"opsonin binding",
"insulin-like growth factor binding"
),
"Cellular Transport" = c(
"vesicle transport along actin filament",
"actin filament-based transport",
"sodium:potassium-exchanging ATPase complex",
"microvillus",
"myosin complex",
"integrin complex",
"external side of plasma membrane",
"voltage-gated chloride channel activity",
"voltage-gated monoatomic anion channel activity",
"P-type ion transporter activity"
),
"Protein Modification" = c(
"GPI anchor biosynthetic process",
"GPI anchor metabolic process",
"glycolipid biosynthetic process",
"protein lipidation"
),
"Cellular Complexes" = c(
"messenger ribonucleoprotein complex",
"complex of collagen trimers",
"SCF ubiquitin ligase complex"
),
"Cytoskeletal Changes" = c(
"actin-based cell projection",
"microfilament motor activity"
)
)
# Create a dataframe with an additional "Cancer Mechanism" column
go.df$Cancer_Mechanism <- unlist(lapply(terms, function(term) {
for (mechanism in names(cancer_mechanisms)) {
if (term %in% cancer_mechanisms[[mechanism]]) {
return(mechanism)
}
}
return("Other") # Set to NA if term does not belong to any cancer mechanism group
}))
# Print the updated dataframe
print(go.df)
## Sort
library(dplyr)
go.df <- go.df %>%
arrange(Cancer_Mechanism, Count) %>%
mutate(Description = factor(Description, levels = unique(Description)))
go_bar_GPT_Cancer <- ggplot(data = go.df, # Data for plotting
aes(x = Description, y = Count, fill = Cancer_Mechanism)) +
geom_bar(stat = "identity", width = 0.9) +
coord_flip() + theme_bw() +
scale_x_discrete(labels = function(x) str_wrap(x, width = 50)) +
labs(x = "GO terms", y = "Gene Number", title = "Barplot of Enriched GO Terms") +
theme(axis.title = element_text(size = 13),
axis.text = element_text(size = 11),
plot.title = element_text(size = 14, hjust = 0.5, face = "bold"),
legend.title = element_text(size = 13),
legend.text = element_text(size = 11),
plot.margin = unit(c(0.5, 0.5, 0.5, 0.5), "cm"))
go_bar_GPT_Cancer
################################################################################
# Load the necessary library if not already loaded
# install.packages("data.table")
library(data.table)
# Define the terms
terms <- c(
"vesicle transport along actin filament",
"actin filament-based transport",
"GPI anchor biosynthetic process",
"GPI anchor metabolic process",
"glycolipid biosynthetic process",
"protein lipidation",
"cell adhesion mediated by integrin",
"phosphatidylinositol biosynthetic process",
"phosphatidylinositol metabolic process",
"glycerophospholipid biosynthetic process",
"sodium:potassium-exchanging ATPase complex",
"messenger ribonucleoprotein complex",
"complex of collagen trimers",
"SCF ubiquitin ligase complex",
"microvillus",
"myosin complex",
"integrin complex",
"protein complex involved in cell adhesion",
"actin-based cell projection",
"external side of plasma membrane",
"chromatin-protein adaptor activity",
"complement component C3b binding",
"voltage-gated chloride channel activity",
"insulin-like growth factor I binding",
"voltage-gated monoatomic anion channel activity",
"P-type ion transporter activity",
"opsonin binding",
"insulin-like growth factor binding",
"microfilament motor activity",
"integrin binding"
)
# Create groups based on COVID-19 related mechanisms
covid_mechanisms <- list(
"Viral Entry and Attachment" = c(
"cell adhesion mediated by integrin",
"protein complex involved in cell adhesion",
"integrin binding"
),
"Host-Pathogen Interaction" = c(
"chromatin-protein adaptor activity",
"complement component C3b binding",
"opsonin binding",
"insulin-like growth factor binding"
),
"Cellular Transport" = c(
"vesicle transport along actin filament",
"actin filament-based transport",
"sodium:potassium-exchanging ATPase complex",
"microvillus",
"myosin complex",
"integrin complex",
"external side of plasma membrane",
"voltage-gated chloride channel activity",
"voltage-gated monoatomic anion channel activity",
"P-type ion transporter activity"
),
"Protein Modification" = c(
"GPI anchor biosynthetic process",
"GPI anchor metabolic process",
"glycolipid biosynthetic process",
"protein lipidation"
),
"Cellular Complexes" = c(
"messenger ribonucleoprotein complex",
"complex of collagen trimers",
"SCF ubiquitin ligase complex"
),
"Cytoskeletal Changes" = c(
"actin-based cell projection",
"microfilament motor activity"
)
)
# Create a dataframe with an additional "Covid Mechanism" column
go.df$Covid_Mechanism <- unlist(lapply(terms, function(term) {
for (mechanism in names(covid_mechanisms)) {
if (term %in% covid_mechanisms[[mechanism]]) {
return(mechanism)
}
}
return("Other") # Set to NA if term does not belong to any COVID-19 mechanism group
}))
# Print the updated dataframe
print(go.df)
## Sort
library(dplyr)
go.df <- go.df %>%
arrange(Covid_Mechanism, Count) %>%
mutate(Description = factor(Description, levels = unique(Description)))
go_bar_GPT_Covid <- ggplot(data = go.df, # Data for plotting
aes(x = Description, y = Count, fill = Covid_Mechanism)) +
geom_bar(stat = "identity", width = 0.9) +
coord_flip() + theme_bw() +
scale_x_discrete(labels = function(x) str_wrap(x, width = 50)) +
labs(x = "GO terms", y = "Gene Number", title = "Barplot of Enriched GO Terms") +
theme(axis.title = element_text(size = 13),
axis.text = element_text(size = 11),
plot.title = element_text(size = 14, hjust = 0.5, face = "bold"),
legend.title = element_text(size = 13),
legend.text = element_text(size = 11),
plot.margin = unit(c(0.5, 0.5, 0.5, 0.5), "cm"))
go_bar_GPT_Covid
################################################################################
#### Preliminary verification ####