-
Notifications
You must be signed in to change notification settings - Fork 0
/
exo_step6.R
1632 lines (1378 loc) · 62.5 KB
/
exo_step6.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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
.libPaths(c(
#"~/vip39/R/x86_64-pc-linux-gnu-library/4.2/",
"~/vip39/R/x86_64-pc-linux-gnu-library/4.1/",
"/home/data/refdir/Rlib/",
"~/vip39/R/x86_64-pc-linux-gnu-library/4.0/",
"/home/data/t030432/R/x86_64-pc-linux-gnu-library/4.2"))
#### ifelse(sub_exo$group=="High","C1","C2")
setwd("~/TCGA/exosome_ccRCC/subcompare")
load("~/vip39/TCGA/exosome_ccRCC/tcgasub.rds")
table(data$group)
# Low High
# 263 263
dim(sub)
# [1] 511 22
#这一步最后只剩下511个样本
###直接load 进行常规分析
sub <- data
sub$cluster <- ifelse(sub$group=="High","C2","C1")
table(sub$cluster)
##进行movics分析
# 显示进程
display.progress = function (index, totalN, breakN=20) {
if ( index %% ceiling(totalN/breakN) ==0 ) {
cat(paste(round(index*100/totalN), "% ", sep=""))
}
}
# 计算组间统计差异
cross_subtype_compr <- function(expr = NULL,
subt = NULL,
subt.label = "Subtype",
two_sam_compr_method = "wilcox",
multi_sam_compr_method = "kruskal",
res.path = NULL) {
if (!is.element(two_sam_compr_method, c("t.test", "wilcox"))) {stop("Two samples comparison should be t.test or wilcox!\n") }
if (!is.element(multi_sam_compr_method, c("anova", "kruskal"))) {stop("multiple samples comparison should be kruskal or anova!\n") }
subt.name <- unique(subt[,subt.label])
n.subt <- length(subt.name)
if(n.subt < 2) {stop("The number of subtype should be greater than 2!\n")}
comprTab <- NULL
# 两个亚型且为非参数检验
if(n.subt == 2 & two_sam_compr_method == "wilcox") {
for (i in 1:nrow(expr)) {
display.progress(index = i,totalN = nrow(expr))
tmp1 <- as.numeric(expr[i,rownames(subt[which(subt[,subt.label] == subt.name[1]),,drop = F])])
tmp2 <- as.numeric(expr[i,rownames(subt[which(subt[,subt.label] == subt.name[2]),,drop = F])])
wt <- wilcox.test(tmp1,tmp2)
comprTab <- rbind.data.frame(comprTab,
data.frame(gene = rownames(expr)[i],
nominal.p.value = wt$p.value,
stringsAsFactors = F),
stringsAsFactors = F)
}
}
# 两个亚型且为参数检验
if(n.subt == 2 & two_sam_compr_method == "t.test") {
for (i in 1:nrow(expr)) {
display.progress(index = i,totalN = nrow(expr))
tmp1 <- as.numeric(expr[i,rownames(subt[which(subt[,subt.label] == subt.name[1]),,drop = F])])
tmp2 <- as.numeric(expr[i,rownames(subt[which(subt[,subt.label] == subt.name[2]),,drop = F])])
tt <- t.test(tmp1,tmp2)
comprTab <- rbind.data.frame(comprTab,
data.frame(gene = rownames(expr)[i],
nominal.p.value = tt$p.value,
stringsAsFactors = F),
stringsAsFactors = F)
}
}
# 多个亚型且为非参数检验
if(n.subt > 2 & multi_sam_compr_method == "kruskal") {
for (i in 1:nrow(expr)) {
display.progress(index = i,totalN = nrow(expr))
tmp.list <- list()
for (n in 1:n.subt) {
tmp.list[[n]] <- data.frame(value = as.numeric(expr[i,rownames(subt[which(subt[,subt.label] == subt.name[n]),,drop = F])]),
subt = subt.name[n],
stringsAsFactors = F)
}
tmp <- do.call(rbind,tmp.list)
kt <- kruskal.test(value ~ subt,data = tmp)
comprTab <- rbind.data.frame(comprTab,
data.frame(gene = rownames(expr)[i],
nominal.p.value = kt$p.value,
stringsAsFactors = F),
stringsAsFactors = F)
}
}
# 多个亚型且为参数检验
if(n.subt > 2 & multi_sam_compr_method == "anova") {
for (i in 1:nrow(expr)) {
display.progress(index = i,totalN = nrow(expr))
tmp.list <- list()
for (n in 1:n.subt) {
tmp.list[[n]] <- data.frame(value = as.numeric(expr[i,rownames(subt[which(subt[,subt.label] == subt.name[n]),,drop = F])]),
subt = subt.name[n],
stringsAsFactors = F)
}
tmp <- do.call(rbind,tmp.list)
at <- summary(aov(value ~ subt,data = tmp))
comprTab <- rbind.data.frame(comprTab,
data.frame(gene = rownames(expr)[i],
nominal.p.value = at[[1]][1,5],
stringsAsFactors = F),
stringsAsFactors = F)
}
}
# 调整p值
comprTab$adjusted.p.value = p.adjust(comprTab$nominal.p.value,method = "BH")
# 按p值排序
#comprTab <- comprTab[order(comprTab$adjusted.p.value, decreasing = F),]
write.table(comprTab,file.path(res.path,"comprTab.txt"),sep = "\t",row.names = F,quote = F)
return(comprTab)
}
##和多个预后 免疫指标关联
#CD8, PD-1 and PD-L1
#相关性分析 绘图 高级版
##外扩到其他队列 免疫治疗队列尤其
##肾癌其他免疫治疗队列 N NR
setwd("~/vip39/TCGA/ex")
#####热图补充 low risk and normal tissue#####
#加上正常组织三组绘图
#dir.create("../complexheatmap")
setwd("/home/data/vip39/TCGA/met_stage1/complexheatmap/")
library(ComplexHeatmap)
library(stringr)
library(pheatmap)
library(gplots)
library(grid)
library(circlize)
Sys.setenv(LANGUAGE = "en") #显示英文报错信息
options(stringsAsFactors = FALSE) #禁止chr转成factor
###准备两个数据 mygene_data 和 Subtype 分组信息
range(KIRC_tpm)
KIRC_tpm[1:4,1:4]
load("~/vip39/TCGA/exosome_ccRCC/exosome_sub.rds")
head(sub)
sub$Sample <- paste0(sub$Sample,"A")
normal_id <- colnames(KIRC_tpm)[str_sub(colnames(KIRC_tpm),14,15)=="11"]
head(sub)
c(normal_id,sub$Sample)
Subtype <- data.frame(Subtype=c(rep("N",length(normal_id)),sub$Cluster),
id=c(normal_id,sub$Sample))
rownames(Subtype) <- Subtype$id
Subtype <- Subtype[-2]
RNA_gene <- gene
mygene_data <- KIRC_tpm[RNA_gene,rownames(Subtype)]
#Subtype <- Subtype[com_sam,,drop = F]
head(Subtype)
table(Subtype$Subtype)
## 用前面的自定义函数计算组间统计差异
setwd("./supplementaryresult/")
comprTab <- cross_subtype_compr(expr = mygene_data, # 或log2(mygene_data + 1),如果用参数检验,请注意对数转化;若非参均可
subt = Subtype,
#two_sam_compr_method = "wilcox", # 两组"t.test", "wilcox"
multi_sam_compr_method = "kruskal", # 多组"anova", "kruskal"
res.path = ".")
# 用全部基因来画
n.show_top_gene <- nrow(mygene_data)
# 按分组排序
subt.order <- Subtype[order(Subtype$Subtype),,drop = F]
indata <- mygene_data[comprTab$gene[1:n.show_top_gene],rownames(subt.order)]
# 数据标准化和边界设置
indata <- log2(indata+1)
plotdata <- t(scale(t(indata)))
plotdata[plotdata > 2] <- 2
plotdata[plotdata < -2] <- -2
# 调整行名
blank <- " " # 行名和p值之间的间隔
p.value <- comprTab$adjusted.p.value[1:n.show_top_gene]
sig.label <- ifelse(p.value < 0.001,"****",
ifelse(p.value < 0.005,"***",
ifelse(p.value < 0.01,"**",
ifelse(p.value < 0.05,"*",""))))
p.label <- formatC(p.value, # 将p值变成保留两位小数的科学计数法
format = "e",
digits = 2)
add.label <- str_pad(paste0(rownames(plotdata),sig.label), # 固定行名宽度并再右侧补齐" "
max(nchar(paste0(rownames(plotdata),sig.label))),
side = "right")
annCol <- subt.order # 获得排序后的亚型注释信息,这里只有一个变量需要注释
colnames(annCol)[1] <- paste(str_pad(colnames(annCol)[1], # 注释列名补上"P-value",宽度和刚才一致
max(nchar(paste0(rownames(plotdata),sig.label))),
side = "right"),
"P-value",
sep = blank)
annColors <- list(c( "C1"="#E31A1CFF", "C2"="#1F78B4FF","N"="#33A02CFF")) # 如果有多个变量要注释颜色请补充c()
names(annColors) <- colnames(annCol)[1] # 如果有多个变量要注释颜色请补充每张list的name
# 绘制热图
library(circlize)
library(stringr)
library(pheatmap)
library(gplots)
library(grid)
Sys.setenv(LANGUAGE = "en") #显示英文报错信息
options(stringsAsFactors = FALSE) #禁止chr转成factor
table(sub$Cluster)
pheatmap(cellheight = 9, cellwidth = 1,
mat = plotdata, # 输入数据
scale = "none", # 不标准化因为数据已经被标准化
annotation_col = annCol, # 列注释信息
annotation_colors = annColors, # 列注释对应的颜色
cluster_cols = F, # 列不聚类
cluster_rows = F, # 行不聚类
show_colnames = F, # 不显示列名
show_rownames = T, # 显示基因名
annotation_legend = F, # 不显示图例
gaps_col = c(258,511),
color = colorRampPalette(c('#4D4398',"white",'#F18D00'))(100),
labels_row = paste(add.label, p.label, sep=blank),
)
######cox分析#####
library(tidyverse)
library(ggplot2)
library(ggstatsplot)
library(survival)
library(stringr)
library(viridis)
library(scales)
dim(sub)
Coxoutput <- data.frame(OS=sub$fustat,
OS.time=sub$futime)
Coxoutput <- data.frame(OS=sub$PFI,
OS.time=sub$PFI.time)
rownames(Coxoutput) <- sub$Sample
Coxoutput2 <- as.data.frame(t(KIRC_tpm[unique(RNA_gene),sub$Sample]))
range(Coxoutput2)
#Coxoutput2 <- log2(Coxoutput2+1)
Coxoutput <- cbind(Coxoutput,Coxoutput2)
realdata <- Coxoutput
realdata[1:3,1:6]
#setwd("~/vip39/TCGA/KIRC_MLcelldeath/result/")
dir.create("COX")
setwd("./COX/")
str(realdata)
Coxoutput=data.frame()
for(i in colnames(realdata[,3:ncol(realdata)])){
cox <- coxph(Surv(OS.time, OS) ~ realdata[,i], data = realdata)
coxSummary = summary(cox)
Coxoutput=rbind(Coxoutput,cbind(gene=i,HR=coxSummary$coefficients[,"exp(coef)"],
z=coxSummary$coefficients[,"z"],
pvalue=coxSummary$coefficients[,"Pr(>|z|)"],
lower=coxSummary$conf.int[,3],
upper=coxSummary$conf.int[,4]))
}
for(i in c(2:6)){
Coxoutput[,i] <- as.numeric(as.vector(Coxoutput[,i]))
}
# Coxoutput <- arrange(Coxoutput,pvalue) %>% #按照p值排序
# filter(pvalue < 0.01)
Coxoutput <- arrange(Coxoutput,pvalue)
#Coxoutput <- Coxoutput[Coxoutput$pvalue<0.01,]
dim(Coxoutput)
#[1] 12 6
#保存到文件
write.csv(Coxoutput,'cox_output.csv', row.names = F)
Coxoutput <- read.csv("cox_output.csv")
head(Coxoutput)
#plotCoxoutput <- filter(Coxoutput,HR <=0.92 | HR>= 1.15) #选择合适的top genes
plotCoxoutput <- Coxoutput
#采用那篇nature的配色
ggplot(data=plotCoxoutput,aes(x=HR,y=gene,color=pvalue))+
geom_errorbarh(aes(xmax=upper,xmin=lower),color="black",height=0,size=1.2)+
geom_point(aes(x=HR,y=gene),size=3.5,shape=18)+ #画成菱形
geom_vline(xintercept = 1,linetype='dashed',size=1.2)+
scale_x_continuous(breaks = c(0.75,1,1.30))+
coord_trans(x='log2')+
ylab("Gene")+ #标签
xlab("Hazard ratios of TDERS in ccRCC of OS")+
labs(color="P value",title ="Univariate Cox regression analysis" )+
scale_color_viridis()+ #nature配色
theme_ggstatsplot()+ #好看的主题,同原文一致
theme(panel.grid =element_blank()) #去除网格线
ggsave('coxplot.pdf',width = 8,height = 8)
ggsave('coxplotPFI.pdf',width = 8,height = 8)
####Riskscore相关性分析蝴蝶图228####
setwd("~/vip39/TCGA/exosome_ccRCC/supplementaryresult/")
library(data.table)
library(GSVA)
library(ggplot2)
library(ggcor)
Sys.setenv(LANGUAGE = "en") #显示英文报错信息
options(stringsAsFactors = FALSE) #禁止chr转成factor
# 读取gmt文件为列表形式,满足pathifier的输入要求
gmt2list <- function(annofile){
if (!file.exists(annofile)) {
stop("There is no such gmt file.")
}
if (tools::file_ext(annofile) == "xz") {
annofile <- xzfile(annofile)
x <- scan(annofile, what="", sep="\n", quiet=TRUE)
close(annofile)
} else if (tools::file_ext(annofile) == "gmt") {
x <- scan(annofile, what="", sep="\n", quiet=TRUE)
} else {
stop ("Only gmt and gmt.xz are accepted for gmt2list")
}
y <- strsplit(x, "\t")
names(y) <- sapply(y, `[[`, 1)
annoList <- lapply(y, `[`, c(-1,-2))
}
# 加载TCGA-KIRC表达谱FPKM
#expr <- read.table("tcga_blca_fpkm.txt",sep = "\t",row.names = 1,check.names = F,stringsAsFactors = F,header = T)
load("/home/data/refdir/database/tcga_counts_fpkm_tpm/TCGA-KIRC_tpm_gene_symbol.Rdata")
expr <-as.data.frame(tpms)
range(expr)
expr[1:4,1:4]
#tumsam <- colnames(expr)[substr(colnames(expr),11,13) == "01A"] # 取出肿瘤样本
# 取出RISKSCORE 分数
#siglec15 <- log2(sub$riskscore + 1)
siglec15 <- scale(sub$gpr_score)
##plod2表达分数 进行分析
siglec15 <- log2( expr["PLOD2",rownames(data)]+ 1)
dim(siglec15)
siglec15 <-data.frame(SIGLEC15=as.numeric(siglec15),
row.names = sub$Sample)
siglec15 <- as.data.frame(t(siglec15))
head(siglec15)
setwd("~/vip39/TCGA/exosome_ccRCC/supplementaryresult/PLOD2/")
write.csv(siglec15, "easy_input_gene.csv")
dim(immPath.score) #[1] 18 535
# 加载immunotherapy-predicted pathways
immPath <- read.table("~/vip39/huitu/FigureYa228linkCor/immunotherapy predicted pathways.txt",sep = "\t",row.names = 1,check.names = F,stringsAsFactors = F,header = T)
immPath.list <- list()
for (i in rownames(immPath)) {
tmp <- immPath[i,"Genes"]
tmp <- toupper(unlist(strsplit(tmp,", ",fixed = T)))
tmp <- gsub(" ","",tmp)
immPath.list[[i]] <- tmp
}
# 加载膀胱癌相关签名
blcaPath <- read.table("~/vip39/huitu/FigureYa228linkCor/bladder cancer signature.txt",sep = "\t",row.names = 1,check.names = F,stringsAsFactors = F,header = T)
blcaPath.list <- list()
for (i in rownames(blcaPath)) {
tmp <- blcaPath[i,"Genes"]
tmp <- toupper(unlist(strsplit(tmp,", ",fixed = T)))
tmp <- gsub(" ","",tmp)
blcaPath.list[[i]] <- tmp
}
# 计算immunotherapy-predicted pathways的富集得分
expr[1:4,1:4]
# sub=data
# sub$Sample <- rownames(sub)
immPath.score <- gsva(expr = as.matrix(log2(expr[,sub$Sample] + 1)),
immPath.list,
method = "ssgsea")
# 保存到文件,便于套用
write.table(immPath.score, "easy_input_immPath.txt",sep = "\t",row.names = T,col.names = NA,quote = F)
# 计算膀胱癌相关签名的富集得分
blcaPath.score <- gsva(expr = as.matrix(log2(expr[,sub$Sample] + 1)),
blcaPath.list,
method = "ssgsea")
# 保存到文件,便于套用
write.table(blcaPath.score, "easy_input_blcaPath.txt",sep = "\t",row.names = T,col.names = NA,quote = F)
# 从gmt文件提取感兴趣的通路
# 例如提取带有`METABOLISM`字样的通路
gset <- gmt2list("~/vip39/huitu/FigureYa228linkCor/c5.all.v7.4.symbols.gmt")
###读取所有通路的文件
gset <- gmt2list("/home/data/t030432/vip39/database/GSEA/human/msigdb.v2023.1.Hs.symbols.gmt")
gset.list <- gset[names(gset) %like% "METABOLISM"]
gset.list <- gset[names(gset) %like% "METABOLISM"]
gset.list <- gset.list[names(gset.list) %like% "KEGG"]
# 计算通路富集得分
gset.score <- gsva(expr = as.matrix(log2(expr[,sub$Sample] + 1)),
IOBR::signature_tumor,
method = "ssgsea")
# 保存到文件
write.table(gset.score, "easy_input_gset.txt",sep = "\t",row.names = T,col.names = NA,quote = F)
library(IOBR)
IOBR::signature_metabolism
length(IOBR::signature_metabolism) #114
length(IOBR::signature_tme)#[1] 119
length(IOBR::signature_tumor) #[1] 16
length(IOBR::signature_collection) #264
# 加载单个基因的表达量,也就是“1对多”的“1”
siglec15 <- read.csv("easy_input_gene.csv", row.names = 1, check.names = F)
# 加载第一组富集得分
immPath.score <- read.table("easy_input_immPath.txt", check.names = F)
# 跟目标基因SIGLEC15的表达量合并
immPath.score <- rbind.data.frame(immPath.score,
siglec15)
dim(immPath.score)
# 加载第二组富集得分
blcaPath.score <- read.table("easy_input_blcaPath.txt", check.names = F)
# 跟目标基因SIGLEC15的表达量合并
blcaPath.score <- rbind.data.frame(blcaPath.score,
siglec15)
# 循环计算相关性并绘制左下角
immCorSiglec15 <- NULL
for (i in rownames(immPath.score)) {
cr <- cor.test(as.numeric(immPath.score[i,]),
as.numeric(siglec15),
method = "pearson")
immCorSiglec15 <- rbind.data.frame(immCorSiglec15,
data.frame(gene = "Siglec15",
path = i,
r = cr$estimate,
p = cr$p.value,
stringsAsFactors = F),
stringsAsFactors = F)
}
immCorSiglec15$sign <- ifelse(immCorSiglec15$r > 0,"pos","neg")
immCorSiglec15$absR <- abs(immCorSiglec15$r)
immCorSiglec15$rSeg <- as.character(cut(immCorSiglec15$absR,c(0,0.25,0.5,0.75,1),labels = c("0.25","0.50","0.75","1.00"),include.lowest = T))
immCorSiglec15$pSeg <- as.character(cut(immCorSiglec15$p,c(0,0.001,0.01,0.05,1),labels = c("<0.001","<0.01","<0.05","ns"),include.lowest = T))
immCorSiglec15[nrow(immCorSiglec15),"pSeg"] <- "Not Applicable"
immCorSiglec15$rSeg <- factor(immCorSiglec15$rSeg, levels = c("0.25","0.50","0.75","1.00"))
immCorSiglec15$pSeg <- factor(immCorSiglec15$pSeg, levels = c("<0.001","<0.01","<0.05","Not Applicable","ns"))
immCorSiglec15$sign <- factor(immCorSiglec15$sign, levels = c("pos","neg"))
p1 <- quickcor(t(immPath.score),
type = "lower",
show.diag = TRUE) +
geom_colour() +
add_link(df = immCorSiglec15,
mapping = aes(colour = pSeg, size = rSeg, linetype = sign),
spec.key = "gene",
env.key = "path",
diag.label = FALSE) +
scale_size_manual(values = c(0.5, 1, 1.5, 2)) +
scale_color_manual(values = c("#19A078","#DA6003","#7570B4","#E8288E","#65A818")) +
scale_fill_gradient2(low = "#9483E1",mid = "white",high = "#F18D00",midpoint=0) +
remove_axis("x")
p1
c('#4D4398','#F18D00')
ggsave(filename = "ggcor plot in bottom left.pdf", width = 10,height = 8)
# 循环计算相关性并绘制右上角
blcaCorSiglec15 <- NULL
for (i in rownames(blcaPath.score)) {
cr <- cor.test(as.numeric(blcaPath.score[i,]),
as.numeric(siglec15),
method = "pearson")
blcaCorSiglec15 <- rbind.data.frame(blcaCorSiglec15,
data.frame(gene = "Siglec15",
path = i,
r = cr$estimate,
p = cr$p.value,
stringsAsFactors = F),
stringsAsFactors = F)
}
blcaCorSiglec15$sign <- ifelse(blcaCorSiglec15$r > 0,"pos","neg")
blcaCorSiglec15$absR <- abs(blcaCorSiglec15$r)
blcaCorSiglec15$rSeg <- as.character(cut(blcaCorSiglec15$absR,c(0,0.25,0.5,0.75,1),labels = c("0.25","0.50","0.75","1.00"),include.lowest = T))
blcaCorSiglec15$pSeg <- as.character(cut(blcaCorSiglec15$p,c(0,0.001,0.01,0.05,1),labels = c("<0.001","<0.01","<0.05","ns"),include.lowest = T))
blcaCorSiglec15[nrow(blcaCorSiglec15),"pSeg"] <- "Not Applicable"
blcaCorSiglec15$rSeg <- factor(blcaCorSiglec15$rSeg, levels = c("0.25","0.50","0.75","1.00"))
blcaCorSiglec15$pSeg <- factor(blcaCorSiglec15$pSeg, levels = c("<0.001","<0.01","<0.05","Not Applicable","ns"))
blcaCorSiglec15$sign <- factor(blcaCorSiglec15$sign, levels = c("pos","neg"))
p2 <- quickcor(t(blcaPath.score),
type = "upper",
show.diag = TRUE) +
geom_colour() +
add_link(df = blcaCorSiglec15,
mapping = aes(colour = pSeg, size = rSeg, linetype = sign),
spec.key = "gene",
env.key = "path",
diag.label = FALSE) +
scale_size_manual(values = c(0.5, 1, 1.5, 2)) +
scale_color_manual(values = c("#19A078","#DA6003","#7570B4","#E8288E","#65A818")) +
scale_fill_gradient2(low = "#9483E1",mid = "white",high = "#F18D00",midpoint=0) +
remove_axis("x")
p2
ggsave(filename = "ggcor plot in top right.pdf", width = 10,height = 8)
# 加载第3组富集得分
blcaPath.score <- read.table("easy_input_gset.txt", check.names = F)
# 跟目标基因SIGLEC15的表达量合并
blcaPath.score <- rbind.data.frame(blcaPath.score,
siglec15)
# 循环计算相关性并绘制右上角
blcaCorSiglec15 <- NULL
for (i in rownames(blcaPath.score)) {
cr <- cor.test(as.numeric(blcaPath.score[i,]),
as.numeric(siglec15),
method = "pearson")
blcaCorSiglec15 <- rbind.data.frame(blcaCorSiglec15,
data.frame(gene = "Siglec15",
path = i,
r = cr$estimate,
p = cr$p.value,
stringsAsFactors = F),
stringsAsFactors = F)
}
blcaCorSiglec15$sign <- ifelse(blcaCorSiglec15$r > 0,"pos","neg")
blcaCorSiglec15$absR <- abs(blcaCorSiglec15$r)
blcaCorSiglec15$rSeg <- as.character(cut(blcaCorSiglec15$absR,c(0,0.25,0.5,0.75,1),labels = c("0.25","0.50","0.75","1.00"),include.lowest = T))
blcaCorSiglec15$pSeg <- as.character(cut(blcaCorSiglec15$p,c(0,0.001,0.01,0.05,1),labels = c("<0.001","<0.01","<0.05","ns"),include.lowest = T))
blcaCorSiglec15[nrow(blcaCorSiglec15),"pSeg"] <- "Not Applicable"
blcaCorSiglec15$rSeg <- factor(blcaCorSiglec15$rSeg, levels = c("0.25","0.50","0.75","1.00"))
blcaCorSiglec15$pSeg <- factor(blcaCorSiglec15$pSeg, levels = c("<0.001","<0.01","<0.05","Not Applicable","ns"))
blcaCorSiglec15$sign <- factor(blcaCorSiglec15$sign, levels = c("pos","neg"))
p3 <- quickcor(t(blcaPath.score),
type = "upper",
show.diag = TRUE) +
geom_colour() +
add_link(df = blcaCorSiglec15,
mapping = aes(colour = pSeg, size = rSeg, linetype = sign),
spec.key = "gene",
env.key = "path",
diag.label = FALSE) +
scale_size_manual(values = c(0.5, 1, 1.5, 2)) +
scale_color_manual(values = c("#19A078","#DA6003","#7570B4","#E8288E","#65A818")) +
scale_fill_gradient2(low = "#9483E1",mid = "white",high = "#F18D00",midpoint=0) +
remove_axis("x")
p3
ggsave(filename = "ggcor plot in top right2.pdf", width = 10,height = 8)
####TIP读入
stepscore <- fread("~/vip39/database/TIP/KIRC/ssGSEA.normalized.score.txt",header = T,data.table = F)
head(stepscore[,1:4])
stepscore <- stepscore%>%
column_to_rownames("Steps")
colnames(stepscore) <- str_sub(colnames(stepscore),1,15)
rownames(stepscore)[1:3] <- c("Step1.Release of cancer cell antigens",
"Step2.Cancer antigen presentation",
"Step3.Priming and activation")
rownames(stepscore)[c(21,22,23)] <- c("Step5.Infiltration of cancer cells into tumors",
"Step6.Recognitioin of cancer cells by T cells",
"Step7.Killing of cancer cells")
stepscore[1:4,1:4]
colnames(stepscore) <- paste0(colnames(stepscore),"A")
blcaPath.score <- stepscore[,sub$Sample]
blcaPath.score <- rbind.data.frame(blcaPath.score,
siglec15)
# 循环计算相关性并绘制右上角
blcaCorSiglec15 <- NULL
for (i in rownames(blcaPath.score)) {
cr <- cor.test(as.numeric(blcaPath.score[i,]),
as.numeric(siglec15),
method = "pearson")
blcaCorSiglec15 <- rbind.data.frame(blcaCorSiglec15,
data.frame(gene = "Siglec15",
path = i,
r = cr$estimate,
p = cr$p.value,
stringsAsFactors = F),
stringsAsFactors = F)
}
blcaCorSiglec15$sign <- ifelse(blcaCorSiglec15$r > 0,"pos","neg")
blcaCorSiglec15$absR <- abs(blcaCorSiglec15$r)
blcaCorSiglec15$rSeg <- as.character(cut(blcaCorSiglec15$absR,c(0,0.25,0.5,0.75,1),labels = c("0.25","0.50","0.75","1.00"),include.lowest = T))
blcaCorSiglec15$pSeg <- as.character(cut(blcaCorSiglec15$p,c(0,0.001,0.01,0.05,1),labels = c("<0.001","<0.01","<0.05","ns"),include.lowest = T))
blcaCorSiglec15[nrow(blcaCorSiglec15),"pSeg"] <- "Not Applicable"
blcaCorSiglec15$rSeg <- factor(blcaCorSiglec15$rSeg, levels = c("0.25","0.50","0.75","1.00"))
blcaCorSiglec15$pSeg <- factor(blcaCorSiglec15$pSeg, levels = c("<0.001","<0.01","<0.05","Not Applicable","ns"))
blcaCorSiglec15$sign <- factor(blcaCorSiglec15$sign, levels = c("pos","neg"))
p3 <- quickcor(t(blcaPath.score),
type = "upper",
show.diag = TRUE) +
geom_colour() +
add_link(df = blcaCorSiglec15,
mapping = aes(colour = pSeg, size = rSeg, linetype = sign),
spec.key = "gene",
env.key = "path",
diag.label = FALSE) +
scale_size_manual(values = c(0.5, 1, 1.5, 2)) +
scale_color_manual(values = c("#19A078","#DA6003","#7570B4","#E8288E","#65A818")) +
scale_fill_gradient2(low = "#9483E1",mid = "white",high = "#F18D00",midpoint=0) +
remove_axis("x")
p3
ggsave(filename = "ggcor plot in top rightstepscores.pdf", width = 10,height = 8)
####经典富集分析 GO term####
###使用easyTCGA版本
library(msigdbr)
m_t2g <- msigdbr(species = "Homo sapiens", category = "C5") %>%
dplyr::select(gs_name, entrez_gene)
head(m_t2g)
# gene_entrezid <- merge(gene_entrezid,diff_limma,by.x = "SYMBOL", by.y = "genesymbol")
# genelist <- gene_entrezid$logFC
# names(genelist) <- gene_entrezid$ENTREZID
# genelist <- sort(genelist,decreasing = T)
head(genelist)
gsea_res <- GSEA(geneList,
TERM2GENE = m_t2g,
minGSSize = 10,
maxGSSize = 500,
pvalueCutoff = 0.05,
pAdjustMethod = "BH",
seed = 456
)
gsea_res_symbol <- setReadable(gsea_res,"org.Hs.eg.db",keyType = "ENTREZID")
library(GseaVis)
terms <- gsea_res@result$ID[1:4]
gseaplot_list <- lapply(terms, function(x){
gseaNb(object = gsea_res,
geneSetID = x,
termWidth = 30,
addPval = T,
pvalX = 0.75,
pvalY = 0.6
)
})
# 可以直接拼
cowplot::plot_grid(plotlist=gseaplot_list, ncol = 2)
terms <- gsea_res@result$ID[57:60]
gseaplot_list <- lapply(terms, function(x){
gseaNb(object = gsea_res,
geneSetID = x,
termWidth = 30,
addPval = T,
pvalX = 0.75,
pvalY = 0.6
)
})
# 可以直接拼
cowplot::plot_grid(plotlist=gseaplot_list, ncol = 2)
terms <- gsea_res@result$ID[1:3]
gseaNb(object = gsea_res,
geneSetID = terms,
subPlot = 2,
termWidth = 35,
legend.position = c(0.8,0.8),
addPval = T,
pvalX = 0.05,pvalY = 0.05)
gseaNb(object = gsea_res,
geneSetID = "GOMF_OLFACTORY_RECEPTOR_ACTIVITY")
#####reactome 分析补充上去
#aaa<-aaa[,-1]
#aaa<-na.omit(aaa)
#aaa$logFC<-sort(aaa$logFC,decreasing = T)
#geneList = aaa[,2]
#names(geneList) = as.character(aaa[,1])
geneList
#GSEA分析——GO
Go_gseresult <- gseGO(geneList, OrgDb = "org.Hs.eg.db", keyType = "ENTREZID", ont="all", minGSSize = 10, maxGSSize = 500, pvalueCutoff=1)
#GSEA分析——KEGG
KEGG_gseresult <- gseKEGG(geneList, nPerm = 1000, minGSSize = 10, maxGSSize = 1000, pvalueCutoff=0.5)
#GSEA分析——Reactome
Go_Reactomeresult <- gsePathway(geneList, nPerm = 1000, minGSSize = 10, maxGSSize = 1000, pvalueCutoff=1)
#波浪图
ridgeplot(KEGG_gseresult,10) #输出前十个结果
ridgeplot(Go_gseresult,10) #输出前十个结果
ridgeplot(Go_Reactomeresult,10)
gseaplot2(Go_Reactomeresult, geneSetID = 1:3, pvalue_table = TRUE,
color = c("#E495A5", "#86B875", "#7DB0DD"), ES_geom = "dot")
gseaplot2(Go_Reactomeresult, geneSetID = 1:5, pvalue_table = TRUE,
color = paletteer_c("scico::berlin", n = 5), ES_geom = "dot")
# go <- enrichGO(gene = geneList, OrgDb = "org.Hs.eg.db", ont="all")
# barplot(go, split="ONTOLOGY")+ facet_grid(ONTOLOGY~., scale="free")
gseaplot2(Go_Reactomeresult, geneSetID = c("R-HSA-381753","R-HSA-418555","R-HSA-1461957",
"R-HSA-8851680","R-HSA-176974"), pvalue_table = TRUE,
color = paletteer_c("scico::berlin", n = 5), ES_geom = "dot")
###GO 分析
library(dplyr)#数据清洗
library(stringr)
library(org.Hs.eg.db)#物种注释(Homo sapiens)
library(clusterProfiler)#富集分析
library(ggplot2)#个性化绘图
library(RColorBrewer)#配色调整
#根据研究目的筛选差异基因(仅上调、下调或者全部):
#yellow_gene <-colnames(dd)#所有差异基因
#ID转换:
#查看可转换的ID类型:
columns(org.Hs.eg.db)
##使用clusterProfiler包自带ID转换函数bitr(基于org.Hs.eg.db):
#diff:
diff_entrez <- bitr(geneID = gene,
fromType = "SYMBOL",
toType = "ENTREZID",
OrgDb = "org.Hs.eg.db")
head(diff_entrez)
#GO(Gene Ontology)富集分析:
##MF(我们以总差异基因的GO富集为例):
GO_MF_diff <- enrichGO(gene = diff_entrez$ENTREZID, #用来富集的差异基因
OrgDb = org.Hs.eg.db, #指定包含该物种注释信息的org包
ont = "MF", #可以三选一分别富集,或者"ALL"合并
pAdjustMethod = "BH", #多重假设检验矫正方法
pvalueCutoff = 0.05,
qvalueCutoff = 0.05,
readable = TRUE) #是否将gene ID映射到gene name
#提取结果表格:
GO_MF_result <- GO_MF_diff@result
#View(GO_MF_result)
#CC:
GO_CC_diff <- enrichGO(gene = diff_entrez$ENTREZID,
OrgDb = org.Hs.eg.db,
ont = "CC",
pAdjustMethod = "BH",
pvalueCutoff = 0.05,
qvalueCutoff = 0.05,
readable = TRUE)
#提取结果表格:
GO_CC_result <- GO_CC_diff@result
#BP:
GO_BP_diff <- enrichGO(gene = diff_entrez$ENTREZID,
OrgDb = org.Hs.eg.db,
ont = "BP",
pAdjustMethod = "BH",
pvalueCutoff = 0.05,
qvalueCutoff = 0.05,
readable = TRUE)
#提取结果表格:
GO_BP_result <- GO_BP_diff@result
#MF、CC、BP三合一:
GO_all_diff <- enrichGO(gene = diff_entrez$ENTREZID,
OrgDb = org.Hs.eg.db,
ont = "ALL", #三合一选择“ALL”
pAdjustMethod = "BH",
pvalueCutoff = 0.05,
qvalueCutoff = 0.05,
readable = TRUE)
#提取结果表格:
GO_all_result <- GO_all_diff@result
##保存GO富集结果:
#save(GO_MF_diff,GO_CC_diff,GO_BP_diff,GO_all_diff,file = "GO_diff_DEG.rds")
#KEGG富集分析,我们以总差异基因(diff_entrez)为例:
KEGG_diff <- enrichKEGG(gene = diff_entrez$ENTREZID,
organism = "hsa",#物种,Homo sapiens (human)
pvalueCutoff = 0.05,
qvalueCutoff = 0.05)
#从KEGG富集分析结果中提取结果表格:
KEGG_result <- KEGG_diff@result
#View(KEGG_result)
#使用ggplot2进行更加自由的可视化呈现:
#先提取富集结果表前Top20:
KEGG_top20 <- KEGG_result[1:20,]
#指定绘图顺序(转换为因子):
KEGG_top20$pathway <- factor(KEGG_top20$Description,levels = rev(KEGG_top20$Description))
#Top20富集数目条形图:
mytheme <- 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))
KEGG_top20 <- na.omit(KEGG_top20)
p <- ggplot(data = KEGG_top20,
aes(x = Count,
y = pathway,
fill = -log10(pvalue)))+
scale_fill_distiller(palette = "RdPu",direction = 1) +
geom_bar(stat = "identity",width = 0.8) +
theme_bw() +
labs(x = "Number of Gene",
y = "pathway",
title = "KEGG enrichment barplot") + mytheme
p
library(topGO)
library(enrichplot)
####使用ggplot2进行可视化:
#取前top20,并简化命名:
MF <- GO_MF_result[1:20,]
CC <- GO_CC_result[1:20,]
BP <- GO_BP_result[1:20,]
#自定义主题
mytheme <- 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))
#在MF的Description中存在过长字符串,我们将长度超过50的部分用...代替:
#MF2 <- MF
#MF2$Description <- str_trunc(MF$Description,width = 50,side = "right")
#MF2$Description
MF$term <- factor(MF$Description,levels = rev(MF$Description))
CC$term <- factor(CC$Description,levels = rev(CC$Description))
BP$term <- factor(BP$Description,levels = rev(BP$Description))
#GO富集柱形图:
GO_bar <- function(x){
y <- get(x)
ggplot(data = y,
aes(x = Count,
y = term,
fill = -log10(pvalue))) +
scale_y_discrete(labels = function(y) str_wrap(y, width = 50) ) + #label换行,部分term描述太长
geom_bar(stat = "identity",width = 0.8) +
labs(x = "Gene Number",
y = "Description",
title = paste0(x," of GO enrichment barplot")) +
theme_bw() +
mytheme
}
#MF:
p1 <- GO_bar("MF")+scale_fill_distiller(palette = "Blues",direction = 1)
p1
#CC:
p2 <- GO_bar("CC")+scale_fill_distiller(palette = "Reds",direction = 1)
p2
#BP:
p3 <- GO_bar("BP")+scale_fill_distiller(palette = "Oranges",direction = 1)
p3
######单细胞补充分析####
library(Seurat)
library(monocle)
library(DDRTree)
library(CellChat)
library(SCENIC)
sce <- readRDS("~/vip39/baiduyunpan/BNTL9/all_cluster.rds")
#sce <- BNTL9
sce <- SeuratObject::UpdateSeuratObject(sce)
###只能addmoudlescore
####使用其中一组的分数 TCGA-KIRC
DefaultAssay(sce) <- "RNA"
DefaultAssay(sce) <- "integrated"
sce@assays$integrated[1:4,1:4]
dim(sce@assays$integrated)
dim(sce@assays$RNA)
colnames(meta)
###细胞分群
Idents(sce) <- "celltype"
DimPlot(sce,reduction = "tsne",group.by = "celltype",label = T)
DimPlot(sce,reduction = "umap",group.by = "celltype",label = T)
DimPlot(sce,reduction = "pca",group.by = "clusterAnn",label = T)
###marker细胞的鉴定 top3 绘图
###美化
meta <- sce@meta.data
meta$celltypemino <- str_split_fixed(meta$clusterAnn,":",2)[,2]
col_df = data.frame(name=unique(meta$celltype)) %>%
arrange(name)
col_df
mycol = c(
"#409079","#52a5c1","#c65341","#425785","#d6873b","#92b8da","#9f2b39",
"#b5aa82","#de9d3d","#347852","#ca8399","#296097","#564b84","#817f7e"
)
mycol =setNames(mycol,col_df$name)
UMAP <- sce@reductions[["umap"]]@cell.embeddings%>%as.data.frame()
meta <- cbind(meta,UMAP)
mid_coord_type = meta %>%
dplyr::select(c('celltype','UMAP_1','UMAP_2')) %>%
group_by(celltype) %>%
summarise(
UMAP_1 = median(UMAP_1),
UMAP_2 = median(UMAP_2)
)
pumap1<-ggplot(meta,aes( UMAP_1 ,UMAP_2))+
geom_point(size=0.01,aes(color=celltype))+
geom_text(data = mid_coord_type,size=5,
aes(UMAP_1,UMAP_2,label=celltype))+
theme_classic()+
theme(legend.title = element_blank())+
guides(color=guide_legend(override.aes = list(size=4)))+
scale_color_manual(values = mycol)
png(paste0(fig_path,'umap_maintype2.png'),width = 8,height = 6,
units = 'in',res = 300)
print(pumap1)
dev.off()
###tsne绘图
TSNE <- sce@reductions[["tsne"]]@cell.embeddings%>%as.data.frame()
head(TSNE)
meta <- cbind(meta,TSNE)
mid_coord_type = meta %>%
dplyr::select(c('celltype','tSNE_1','tSNE_2')) %>%
group_by(celltype) %>%
summarise(
TSNE_1 = median(tSNE_1),
TSNE_2 = median(tSNE_2)
)
head(meta)
pTSNE1<-ggplot(meta,aes( tSNE_1 ,tSNE_2))+
geom_point(size=0.01,aes(color=celltype))+
geom_text(data = mid_coord_type,size=5,
aes(TSNE_1,TSNE_2,label=celltype))+
theme_classic()+
theme(legend.title = element_blank())+
guides(color=guide_legend(override.aes = list(size=4)))+
scale_color_manual(values = mycol)
png(paste0(fig_path,'TSNE_maintype2.png'),width = 8,height = 6,
units = 'in',res = 300)
print(pTSNE1)
dev.off()