-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSTAT4.R
2737 lines (2412 loc) · 130 KB
/
STAT4.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
#rm(list=ls())
#1.读取数据+处理----
setwd("D:\\研究生科研\\生物信息学\\STAT4\\Subgroup_STAT4\\3.Enrichment")
clinical <- read.csv("clinical_sup3.csv")[,-1] #来自D:\研究生科研\生物信息学\STAT4\Subgroup_STAT4\2.Prognosis #clinical_sup3.csv
clinical <-clinical[,-c(139:336)]#删除139-336 之前的差异基因,1001-174 ;142-154 lassogene
clinical <-clinical[,-c(96:138)]#删除之前的GSVA #1001-131
#后面加入数据后再保存!
exp1 <-read.csv("D:\\研究生科研\\生物信息学\\STAT4\\Subgroup_STAT4\\1.Riskscore\\exp1.csv",row.names = 1)
colnames(exp1) <-gsub("\\.","-",colnames(exp1)) #1067
colnames(exp1)
#取1001样本表达矩阵
exp1 <-exp1[,colnames(exp1) %in% clinical$sample]#1001
#未保存矩阵exp1
#2. 差异分析-limma----
##2.0 检测数据
par(mfrow=c(1,2)) #一式两图
boxplot(exp1,outline=F)
boxplot(log2(exp1+1),outline=F) #0-25 #log2 0-8
#过滤在所有样本都是零表达的基因~2000个
exprSet=exp1[apply(exp1,1, function(x) sum(x>1) > 1),] #17193 1001
dim(exp1);dim(exprSet)
#标准化expr
exprSet <-log2(exprSet+1);dim(exprSet) #无差异基因
#boxplot(exprSet)#0-15
##2.1 limma----
group_list <- ifelse(colnames(exp1) %in% subset(clinical,clinical$Group =="High")$sample,"High","Low")
draw_h_v <- function(exprSet,need_DEG,n='DEseq2',group_list,logFC_cutoff){
## we only need two columns of DEG, which are log2FoldChange and pvalue
## heatmap
need_DEG=nrDEG#降序前50 #nrDEG
library(pheatmap) #nrDEG$log2FoldChange 降序 need_DEG[order(need_DEG$log2FoldChange),]
choose_gene= head(rownames(need_DEG),50)#head(rownames(need_DEG[order(need_DEG$log2FoldChange,decreasing = T),]),50) ## 50 maybe better need_DEG/need_DEG[order(need_DEG$log2FoldChange),]
choose_matrix=exprSet[choose_gene,]#提取前50的表达矩阵
choose_matrix[1:4,1:4]
choose_matrix=t(scale(t(log2(choose_matrix+1)))) #画热图要先归一化
## http://www.bio-info-trainee.com/1980.html
annotation_col = data.frame( group_list=group_list )#变成一个表
rownames(annotation_col)=colnames(exprSet)#再取个名字
pheatmap(choose_matrix,show_colnames = F,cluster_cols = T,cluster_rows = T,annotation_col = annotation_col,
filename = paste0(1,'_need_DEG_top50_heatmap.png'))
library(ggfortify)
df=as.data.frame(t(choose_matrix))#行列转换
choose_matrix
df$group=group_list
png(paste0(2,'_DEG_top50_pca.png'),res=120)#存为什么文件
p=autoplot(prcomp( df[,1:(ncol(df)-1)] ), data=df,colour = "group")+theme_bw()#画图
print(p)
dev.off()
#画火山图
if(! logFC_cutoff){
logFC_cutoff <- with(need_DEG,mean(abs( log2FoldChange)) + 2*sd(abs( log2FoldChange)) )
}#如果没有给定阈值(差异倍数认为多少是上下调),则用平均值加上两倍的方差
logFC_cutoff=0.5 #
need_DEG$change = as.factor(ifelse(need_DEG$pvalue < 0.05 & abs(need_DEG$log2FoldChange) > logFC_cutoff,
ifelse(need_DEG$log2FoldChange > logFC_cutoff ,'UP','DOWN'),'NOT')
)
this_tile <- paste0('Cutoff for logFC is ',round(logFC_cutoff,3),
'\nThe number of up gene is ',nrow(need_DEG[need_DEG$change =='UP',]) ,
'\nThe number of down gene is ',nrow(need_DEG[need_DEG$change =='DOWN',])
)
library(ggplot2)
g = ggplot(data=need_DEG,
aes(x=log2FoldChange, y=-log10(pvalue),
color=change)) +
geom_point(alpha=0.4, size=1.75) +
theme_set(theme_set(theme_bw(base_size=20)))+
xlab("log2 fold change") + ylab("-log10 p-value") +
ggtitle( this_tile ) + theme(plot.title = element_text(size=15,hjust = 0.5))+
scale_colour_manual(values = c('blue','black','red')) ## corresponding to the levels(res$change)
print(g)
ggsave(g,filename = paste0(3,'_volcano.png'))
dev.off()
}
library(edgeR)
if(T){
suppressMessages(library(limma))
design <- model.matrix(~0+factor(group_list))
colnames(design)=levels(factor(group_list))
rownames(design)=colnames(exprSet)
design
dge <- DGEList(counts=exprSet)
dge <- calcNormFactors(dge)
logCPM <- cpm(dge, log=TRUE, prior.count=3)#注意limma包的表达数据是需要经过log的
v <- voom(dge,design,plot=TRUE, normalize="quantile")#说明书需要 normalize
fit <- lmFit(v, design)
group_list
cont.matrix=makeContrasts(contrasts=c('High-Low'),levels = design)#注意这里不要反了,反了就是相反的结果
fit2=contrasts.fit(fit,cont.matrix)
fit2=eBayes(fit2)
tempOutput = topTable(fit2, coef='High-Low', n=Inf)
DEG_limma_voom = na.omit(tempOutput)
head(DEG_limma_voom)
nrDEG=DEG_limma_voom[,c(1,4)]
colnames(nrDEG)=c('log2FoldChange','pvalue')
draw_h_v(exprSet,nrDEG,'limma',group_list,0.5)
}
#log2+1标准化后,logFC=1,无差异;改小logFC=0.5 ,up 1 down 97
#不标准化,logFC=1,up 3, down 53 =56 #热图差异不明显?
#write.csv(DEG_limma_voom,"./output/DEG_limma_voom_fpkm.csv")#保存结果-所有基因
nrDEG1 <- subset(nrDEG,(nrDEG$log2FoldChange >0.5 | nrDEG$log2FoldChange < -0.5)& nrDEG$pvalue <0.05) #56 #0.5 98
##2.2 热图----
#:D:\研究生科研\生物信息学\STAT4\Subgroup_STAT4\1.Riskscore\Riskscore_STAT4.R
library(pheatmap) #nrDEG$log2FoldChange 降序 need_DEG[order(need_DEG$log2FoldChange),]
choose_gene= rownames(nrDEG1)#head(rownames(need_DEG[order(need_DEG$log2FoldChange,decreasing = T),]),50) ## 50 maybe better need_DEG/need_DEG[order(need_DEG$log2FoldChange),]
choose_matrix=exprSet[choose_gene,]#提取差异基因的表达矩阵
choose_matrix[1:4,1:4]
#colnames(choose_matrix) <- group_list#列名改为Low High
choose_matrix=t(scale(t(log2(choose_matrix+1)))) #画热图要先归一化
annotation_col = data.frame( Group=group_list )#变成一个表
rownames(annotation_col)=colnames(exprSet)#再取个名字
pheatmap(choose_matrix,show_colnames = F,cluster_cols = T,cluster_rows = T,annotation_col = annotation_col,
#cutree_col = 2,
color = colorRampPalette(c("navy", "white", "firebrick3"))(25))
#排列表达矩阵顺序-列完全按照annotation_col分布
choose_matrix_1 <- choose_matrix[,ID_high_low]
ID_high_low <- c(rownames(subset(annotation_col,annotation_col$Group =="Low")),#501
rownames(subset(annotation_col,annotation_col$Group =="High")) )
ann_colors <- list(
STAT4 = c(High = "#FF6699", Low = "skyblue"))#分组颜色
pheat<- pheatmap(choose_matrix_1,annotation_legend=T,
gaps_col=500,fontsize = 8,fontsize_col=1,#fontsize_row = 6,
color<- colorRampPalette(c("navy", "white", "firebrick3"))(25),#colorRampPalette(c('#436eee','white','#EE0000'))(25),
annotation_colors = ann_colors,
#filename = "pheatmap_limma_197_fpkm.pdf",
show_rownames = F,show_colnames = F,cluster_cols = F,cluster_rows = T,annotation_col = annotation_col)#,
#cutree_cols = 2 )
pheat
save_pheatmap_pdf <- function(x, filename, width, height) {
library(grid)
x$gtable$grobs[[1]]$gp <- gpar(lwd = 0.02)#修改聚类树线条宽度
stopifnot(!missing(x))
stopifnot(!missing(filename))
pdf(filename, width=width, height=height,family = "serif")
grid::grid.newpage()
grid::grid.draw(x$gtable)
dev.off()
}#保存热图的函数
#save_pheatmap_pdf(pheat, "./output/pheatmap_limma_98_LOGFC0.5_1.pdf",4,3) #10,7
##2.3 火山图volcano----
library("ggthemes")
library("ggplot2")
logFC_cutoff <- 0.5 #所有基因nrDEG
nrDEG$change = as.factor(
ifelse(nrDEG$pvalue < 0.05 & abs(nrDEG$log2FoldChange) > logFC_cutoff,
ifelse(nrDEG$log2FoldChange > logFC_cutoff ,'UP','DOWN'),'NOT') #判断基因变化
)
head(nrDEG) ;table(nrDEG$change)
p <- ggplot(data = nrDEG, aes(x = -log10(as.numeric(pvalue)), y =log2FoldChange) ) + #注意加载data
geom_point(size = 2, aes(color= change), show.legend = T,na.rm =TRUE,alpha = 0.5) + #,alpha = 0.5
scale_color_manual(values = c('#436eee','grey70','#EE0000')) + # 'skyblue', 'grey70', 'pink'
labs(x = '-log10(pvalue)', y = 'Log2(fold change)')+ #设置坐标轴名称
geom_hline(yintercept = c(-0.5, 0.5), linetype = 'dotdash', color = 'grey30') + #设置Y轴虚线
geom_vline(xintercept = -log10(0.05), linetype = 'dotdash', color = 'grey30')+ #设置X轴虚线
theme_bw()+
theme(text=element_text(size=16,family="serif"),#字体改为Times New Roman
axis.text = element_text(size = 15, color = "black",family="serif"),#坐标轴字体
legend.title = element_blank(),legend.background =element_rect(color='grey',linetype = 1),legend.text = element_text(size=15) ,legend.position=c(0.9,0.6))
p
#标出高表达基因
#interest_genes <- nrDEG[which(abs(limma_voom_DEG$logFC) > 5 & limma_voom_DEG$P.Value < 0.05),]
#interest_genes_char <- rownames(nrDEG1) #c(rownames(interest_genes))
#interest_genes <- rownames(subset(nrDEG1,nrDEG1$log2FoldChange >2 | nrDEG1$log2FoldChange < -1 )) #FC >2 < -1
#添加图层来标记兴趣基因-有边框版:注意边框是一个新的数据框!
nrDEG1$color <- ifelse(nrDEG1$change =="UP","pink","skyblue") #pink skyblue
nrDEG2 <- subset(nrDEG1,nrDEG1$log2FoldChange >1.5 | nrDEG1$log2FoldChange < -1 ) #过滤
write.csv(nrDEG1,"./220719/Figure2A_DGEs.csv")
#对所有差异基因标出
nrDEG1$change = as.factor(
ifelse(nrDEG1$pvalue < 0.05 & abs(nrDEG1$log2FoldChange) > logFC_cutoff,
ifelse(nrDEG1$log2FoldChange > logFC_cutoff ,'UP','DOWN'),'NOT') #判断基因变化
)
nrDEG1$color <- ifelse(nrDEG1$change =="UP","pink","skyblue")
p+#geom_point(size=4,data=nrDEG,aes(color= change),alpha = 0.8)+
ggrepel::geom_label_repel(aes(label=rownames(nrDEG1)),data = nrDEG1,color=nrDEG1$color,family="serif",max.overlaps=20)
#ggsave("./output/volcano_limma_98_LOGFC0.5.pdf.pdf",width = 8,height = 6)
#3. 富集分析----
library(clusterProfiler)
eg = bitr(rownames(nrDEG1), fromType="SYMBOL", toType="ENTREZID", OrgDb="org.Hs.eg.db")
head(eg)#差异基因ID转化-98
##3.1 GO富集分析----
go_all <- enrichGO(eg$ENTREZID, "org.Hs.eg.db",
keyType = "ENTREZID",
ont = 'ALL',
pvalueCutoff = 0.05,
pAdjustMethod = "BH",
qvalueCutoff = 0.1, readable=T) #一步到位
#结果处理及GO绘图
go_all_result <- as.data.frame(go_all@result)#所有GO结果-353
#write.csv(go_all_result,"./output/go_all_result.csv")
library(ggplot2)
library(ggrepel)
mf <-subset(go_all_result,go_all_result$ONTOLOGY=="MF")#[1:20,] #mf 总42
mf <-mf[mf$Count > 6,] #10
p <-ggplot(mf,aes(x= -log10(p.adjust),y=reorder(Description,p.adjust) ))+#画图指定x轴与y轴
geom_point(aes(size=Count,color=Description),alpha=0.5)+#指定气泡大小和颜色填充
scale_size(range=c(5,15))+#图的大小设置
theme_bw()+ #设置背景为白色
geom_text_repel(aes(label= Description,color=Description),size= 4,segment.color= "grey", show.legend= T)+
#geom_text( show_guide = F )+#删除图例中的"a"
theme(legend.position= c(0.9,0.65),# "right",#
axis.text.y = element_blank(),
text=element_text(size=16,family="serif"),#字体改为Times New Roman
axis.text = element_text(size = 16, color = "black",family="serif"),
#legend.key.size = unit(0.01, "inches"),#legend之间间距
legend.background = element_rect(fill = NA),
legend.box.background = element_rect(fill = "white",size = 0.05),#填充及边框线宽
legend.text = element_text(color = "blue",size = 10),legend.title = element_text(color = "blue",size = 10),
)+labs(y="Terms")+guides(color = FALSE, #删除color的legend
size = guide_legend(title="Counts",#修改图例标题
override.aes = list(colour = "grey",alpha = 0.5,label = "")) #删除有颜色的legend ,
)+coord_cartesian(xlim = c(2,10))#+
#coord_cartesian(ylim = c(-0.1,11))#拓展Y轴显示范围
p
#保存图片ggsave("./output/GO_MF.pdf",family="serif",width = 6,height = 5)
##3.2 KEGG----
#install.packages('R.utils')
R.utils::setOption("clusterProfiler.download.method","auto")
library(DO.db)
library(clusterProfiler)
library(org.Hs.eg.db)
kegg_all <- enrichKEGG(gene = eg$ENTREZID,
organism ='hsa', #"hsa" #Homo sapiens (human)
pAdjustMethod = "BH",keyType = "kegg",
pvalueCutoff = 0.05,
qvalueCutoff = 0.1,
use_internal_data =FALSE)
#失败
# kegg_all <- enrichKEGG(gene= eg$ENTREZID,organism = 'hsa', qvalueCutoff = 0.05)
# kegg_all <- enrichKEGG(eg$ENTREZID, organism = 'hsa', keyType = 'kegg', pvalueCutoff = 0.05, pAdjustMethod = 'BH', minGSSize = 3, maxGSSize = 500, qvalueCutoff = 0.2, use_internal_data = FALSE)
# write.table(eg,"eg.txt")
# fail to download KEGG data...
# Error in download.KEGG.Path(species) :
# 'species' should be one of organisms listed in 'http://www.genome.jp/kegg/catalog/org_list.html'..
kegg_all_results <- as.data.frame(kegg_all@result)#148
#write.csv(kegg_all_results,"./output/kegg_all_results.csv")#保存未过滤的KEGG结果
##3.2.1 KEGG可视化----
#a.服务器运行KEGG,本地可视化
kegg_all_results <-read.table("./output/kegg_all_results.txt")#98
kegg <- subset(kegg_all_results,kegg_all_results$pvalue <0.05) #26 全部统一为P值
#b.数据处理:手动挑选15个 immune and cancer-related pathways
#kegg <-kegg[c("hsa04514","hsa04060","hsa04658","hsa04659","hsa04612","hsa04062","hsa04672","hsa05340","hsa04660","hsa04650","hsa0462","hsa05235","hsa04064","hsa04210","hsa04668"),]
kegg <- subset(kegg,kegg$Count > 6)#8 个
kegg <- kegg[-c(3,4),]#6,删除Hematopoietic cell lineage Viral protein interaction with cytokine and cytokine receptor
library(DOSE)
kegg$GeneRatio <- c(parse_ratio(kegg$GeneRatio) )
#c. 可视化
#气泡图bubble
library(ggplot2) #pvalue
ggplot(kegg,aes(GeneRatio,reorder(Description,Count)))+ #reorder(Description,Count),Description
geom_point(aes(size=Count,color=-1*log10(pvalue)))+
scale_color_gradient(low="green",high="red")+
labs(color=expression(-log10(pvalue) ),size="Count",x="GeneRatio",y="",title="KEGG")+#添加图注
theme_bw(base_family = "serif") +
theme(text=element_text(size=15,family="serif"),axis.text=element_text(size=15))
#ggsave("./output/KEGG_bubble.pdf",width = 8,height = 4)
#条形图barplot
ggplot(kegg,aes(y=reorder(Description,Count),x=Count,fill=-1*log10(pvalue)))+
geom_bar(stat = "identity")+
scale_fill_gradient(low = "skyblue",high = "pink")+ #默认pvalue,勿加kegg_results_p
labs(title = "KEGG",
x = "Counts",
y = "",
fill="-log10(pvalue)",family = "serif")+#fill修改图例名称
theme_bw(base_family = "serif")+
annotate("text",x=15.5,y=3.7,label="-log10(pvalue)",size=5,family = "serif")+ #手动添加注释legend
theme(text=element_text(size=16,family="serif"),axis.text=element_text(size=16),
panel.grid = element_blank(),legend.position = c(0.9,0.3),legend.title = element_blank(),
legend.background = element_blank() ) #legend.text.align=1 legend对齐, 太长无效
#ggsave("./output/KEGG_barplot.pdf",width = 8,height = 4)
#write.csv(kegg,"./220719/Figure2B_kegg.csv")
##3.3 GSEA----
##a,处理数据:在差异结果中注释一行ENTREZID :https://cloud.tencent.com/developer/article/1838918
eg #98
nrDEG1$SYMBOL <- rownames(nrDEG1)
library(dplyr)
data_all <- nrDEG1 %>%
inner_join(eg,by="SYMBOL")
dim(data_all)#98 6
head(data_all)
##b, 排序:将基因按照logFC进行从高到低排序,只需要基因列和logFC即可
data_all_sort <- data_all %>%
arrange(desc(log2FoldChange))
head(data_all_sort)
geneList = data_all_sort$log2FoldChange #把foldchange按照从大到小提取出来
names(geneList) <- data_all_sort$ENTREZID #给上面提取的foldchange加上对应上ENTREZID
head(geneList) #"numeric"
##c,特定参考基因集GSEA分析
library(org.Hs.eg.db)
library(clusterProfiler)
library(pathview)
library(enrichplot)
gsea_gmt <- read.gmt("./output/c7.all.v7.5.1.entrez.gmt") #读gmt文件 c7.all.v7.5.1.entrez.gmt富集失败
gsea <- GSEA(geneList, # h.all.v7.5.1.entrez.gmt 富集2个
TERM2GENE = gsea_gmt) #GSEA分析
head(gsea) #no term enriched under specific pvalueCutoff...
##d,所有基因集富集分析
library(msigdbr)
msigdbr_species()
Hs_msigdbr <- msigdbr(species="Homo sapiens")
colnames(Hs_msigdbr)
Hs_df <- as.data.frame(Hs_msigdbr[,c('gs_name','entrez_gene','gene_symbol')])
head(Hs_df)
# MSigDb数据富集分析:https://blog.csdn.net/qq_27390023/article/details/121301371
em_msig <- GSEA(geneList,pvalueCutoff = 0.1,TERM2GENE=Hs_df[,c(1,2)]) #约1分钟
head(em_msig,20) # sorted by pvalue #no term enriched under specific pvalueCutoff.
em_msig@result$Description #32
gsea_results <- em_msig@result #未富集到GSEA
##3.4 GSVA----
##3.4.1.准备及运行
library(GSVA)
library(GSEABase)
library(clusterProfiler)
#加载注释gmt
gsea_gmt <- read.gmt("D:/研究生科研/生物信息学/STAT4/Subgroup_STAT4/1.Riskscore/fig_tab/enrichment/h.all.v7.5.1.symbols.gmt") #读gmt文件
gsea_gmt_list = split(gsea_gmt$gene, gsea_gmt$term) ##分隔成list
gsva_gsea_gmt<- gsva(as.matrix (log2(exp1+1) ), #标准化矩阵log2(exp1+1)
gset.idx.list=gsea_gmt_list, #基因集
kcdf="Gaussian", #CPM, RPKM, TPM数据就用默认值"Gaussian", read count数据则为"Poisson",
method = "gsva",
parallel.sz=12) # 并行线程数目 5000+ 30min, 50 3min
dim(gsva_gsea_gmt) #50!
gsva_gsea_gmt <- as.data.frame(gsva_gsea_gmt)
#注意保存Rdata
#3.4.2绘制热图
library(pheatmap)
pheatmap(gsva_gsea_gmt,cluster_rows = T,scale = "row",
show_colnames=F,
cutree_cols=2) #不要运行太大的热图数据!!!
##3.4.3.差异的GSVA基因集-heatmap-volcano
library(limma)
head(design) #分组
compare <- makeContrasts(High - Low, levels = design)
fit <- lmFit(gsva_gsea_gmt, design)
fit2 <- contrasts.fit(fit, compare)
fit3 <- eBayes(fit2)
Diff_gsva <- topTable(fit3, coef = 1, number = 10000)
head(Diff_gsva ) #https://blog.csdn.net/weixin_41368414/article/details/123967524
#hallmark基因集,差异分析-|FC|小于0.2,自定义cutoff
#write.csv(Diff_gsva,"./output/Diff_gsva_hallmark_limma.csv")
##3.4.4 可视化差异GSVA
Diff_gsva_padjust <- subset(Diff_gsva,Diff_gsva$adj.P.Val < 0.05) #43
gsva_gsea_gmt_padjust <- subset(gsva_gsea_gmt,rownames(gsva_gsea_gmt) %in% rownames(Diff_gsva_padjust) )#43
#删除去掉"HALLMARK_"
library(stringr)
rownames(gsva_gsea_gmt_padjust) <- str_replace(rownames(gsva_gsea_gmt_padjust), "HALLMARK_","")
rownames(Diff_gsva_padjust) <- str_replace(rownames(Diff_gsva_padjust), "HALLMARK_","")
#c.2.1 差异热图
pheatmap(gsva_gsea_gmt_padjust,cluster_rows = T,scale = "row",
show_colnames=F,cutree_cols=2,
annotation_col = annotation_col)
#排列表达矩阵顺序-列完全按照annotation_col分布
gsva_gsea_gmt_padjust_1 <- gsva_gsea_gmt_padjust[,ID_high_low]
# ID_high_low <- c(rownames(subset(annotation_col,annotation_col$STAT4 =="Low")),#534
# rownames(subset(annotation_col,annotation_col$STAT4 =="High")) )
#ann_colors <- list(STAT4 = c(High = "#FF6699", Low = "skyblue"))#分组颜色
p0 <- pheatmap(gsva_gsea_gmt_padjust_1 ,annotation_legend=T,gaps_col=500,#cutree_cols=2,#gaps_col=533,
fontsize = 7,fontsize_col=1,
color<- colorRampPalette(c('skyblue','white','firebrick'))(25),#colorRampPalette(c('#436eee','white','#EE0000'))(25),
annotation_colors = ann_colors,
#filename = "pheatmap_limma_197_fpkm.pdf",
show_rownames = T,show_colnames = F,cluster_cols = F,cluster_rows = T,annotation_col = annotation_col)#,
p0 #gsva 分组热图
save_pheatmap_pdf_1 <- function(x, filename, width=6, height=4.5) {
stopifnot(!missing(x))
stopifnot(!missing(filename))
pdf(filename, width=width, height=height,family = "serif")
grid::grid.newpage()
grid::grid.draw(x$gtable)
dev.off()
}
save_pheatmap_pdf_1(p0, "./output/gsva_diff_heatmap.pdf")
write.csv(gsva_gsea_gmt_padjust_1,"./220719/Figure2C_gsva.csv")
##GSVA结果解度与展示?score gsva_gsea_gmt_padjust cell cycle EMT and metabtasis
#合并43个显著差异到临床数据中
gsva_gsea_gmt_padjust_1 <- as.data.frame(t(gsva_gsea_gmt_padjust))
gsva_gsea_gmt_padjust_1$sample <- rownames(gsva_gsea_gmt_padjust_1)
clinical_1 <- merge(clinical,gsva_gsea_gmt_padjust_1,by="sample")#1001-174
#EMT通路与riskscore
cor(clinical_1$lasso.risk.score,clinical_1$EPITHELIAL_MESENCHYMAL_TRANSITION) #-0.19
plot(clinical_1$lasso.risk.score,clinical_1$EPITHELIAL_MESENCHYMAL_TRANSITION)
boxplot(factor(clinical_1$Group),clinical_1$EPITHELIAL_MESENCHYMAL_TRANSITION)
library(ggplot2);library(ggpubr)
clinical_1$STAT4_group
ggplot(data=clinical_1,aes(x=STAT4_group,y=EPITHELIAL_MESENCHYMAL_TRANSITION,color=STAT4_group))+ #fill
# geom_point(alpha=0.5,size=1.5,
# position=position_jitterdodge(jitter.width = 0.35,
# jitter.height = 0,
# dodge.width = 0.8))+
geom_boxplot(alpha=0.2,width=0.45,
position=position_dodge(width=0.8),
size=0.05,outlier.colour = NA)+
geom_violin(alpha=0.2,width=0.9,
position=position_dodge(width=0.8),
size=0.25)+
scale_color_manual(values = c("#CC79A7", "#56B4E9") )+ #color
theme_bw() +ylab("EMT gasv score")+xlab("")+
#theme(legend.position="none")
theme(axis.title = element_text(size=16), axis.text = element_text(size=12),legend.position ="top",
panel.grid = element_blank(),legend.key = element_blank() ) +
labs(color="STAT4")+
stat_compare_means(#aes(group = Group) ,
comparisons=list(c("High","Low")),#my_comparisons,
label = "p.signif",#"p.format p.signif 9.4e-12
method = "wilcox",
show.legend= F,#删除图例中的"a"
label.x=1.5,bracket.size=0.1,vjust=0.2,
#label.y = max(log2(GDSC2$Camptothecin_1003)),
hide.ns = T,size=5)
##全部GSVA BOXPLOT
##cox gsva
##COX GSVA boxplot
#A.循环分组!!
group_df<-list()
for (i in 133:175){
gene <- colnames(clinical_1)[i] #
group_name <- paste0(gene,"_gsva_group")
group=ifelse(clinical_1[,gene] >= median(clinical_1[,gene] ),"High","Low")
#print(group_name)
#print(group)
group_df[[group_name]] <- group #list()
}
View(group_df)
group_df <- as.data.frame(group_df)
rownames(group_df) <-clinical_1$sample
#添加临床信息
group_df$sample <- rownames(group_df)
group_df<- merge(group_df,clinical_1[,c("OS.time.y","OS.x","sample")],by="sample")
rownames(group_df) <-group_df$sample
#B ##批量OS
pFilter=0.05 #定义单因素显著性
library(survival)
sigGenes=c("OS.time.y","OS.x","sample")#注意修改此处及和下面,需要取出的列
outTab_TF=data.frame()
for(i in colnames(group_df[,2:44]) ){ #注意此处为参与COX的名称
cox <- coxph(Surv(OS.time.y, OS.x) ~ group_df[,i], data = group_df) #as.numeric
coxSummary = summary(cox)
coxP=coxSummary$coefficients[,"Pr(>|z|)"]
outTab_TF=rbind(outTab_TF,
cbind(id=i,
HR=coxSummary$conf.int[,"exp(coef)"],
HR.95L=coxSummary$conf.int[,"lower .95"],
HR.95H=coxSummary$conf.int[,"upper .95"],
pvalue=coxSummary$coefficients[,"Pr(>|z|)"])
)
if(coxP<pFilter){
sigGenes=c(sigGenes,i)
}
}
View(outTab_TF)
#write.table(outTab_TF,file="./output/uniCox_outTab_GSVA.xls",sep="\t",row.names=F,quote=F)
outTab_TF_sig <- subset(outTab_TF,outTab_TF$pvalue <0.05)#6 gsva
outTab_TF_sig$id
gsub("_gsva_group","",outTab_TF_sig$id)
##C. OS显著KM绘图 :tnfa_nfkb[1] apoptosis[2] 勉强mycv1 [5] angiogenesis[6]
library(survminer)
for (i in outTab_TF_sig$id[6] ){
group_name <- paste0(i,"_TF_group")
fit<-survfit(Surv(OS.time.y/365, OS.x) ~ group_df[[i]], data =group_df)#group_df[[group_name]]
#print(fit)#查看median风险50%生产率对应的时间!
p<-ggsurvplot(fit,#palette=c("#FC8D62","#66C2A5"),
data=group_df,
risk.table = F,
risk.table.col = 'strata',
risk.table.y.text = T,
risk.table.title = "",#group_name,#paste0('Number at risk',i),
pval = T,pval.size=6,pval.method = T,pval.method.size=6,
conf.int = T, #置信区间
xlab = 'Time (years)',
ggtheme = theme_light(),
font.x=c(16),font.y=c(16),font.lenged=c(16),font.tickslab = c(16), #Y轴数字大小
size=0.5,censor.size=3,censor.shape=NA,#NA不要+号
surv.median.line = 'none',#不要中位值竖线
title=gsub("_gsva_group","",i),#paste0("Riskscore",' Survival Curve'),
legend.title = "Group",
legend.labs = c("High", "Low")#, fontsize=20,font.family="serif"
)
}
p #theme(text = element_text(size=16)) #+guides(color = FALSE)
#ggsave("./output/gsva_OS_angiogenesis.pdf",family="serif")
##D. os cox forest
#准备森林图数据
forest_data <- outTab_TF_sig
colnames(forest_data)<- c("id","HR","Low_95CI","High_95CI","Pvalue")#,"Coeffcient")
forest_data$Pvalue <- round(as.numeric(forest_data$Pvalue),4)
#forest_data$Coeffcient <- round(as.numeric(forest_data$Coeffcient),4)
#forest_data$Pvalue <- ifelse(as.numeric(forest_data$Pvalue)>0.05,"ns",ifelse(as.numeric(forest_data$Pvalue)>0.01,"*",ifelse(as.numeric(forest_data$Pvalue)>0.001,"**","***")))
forest_data$HR <-round(as.numeric(forest_data$HR),3)
forest_data$id <- gsub("_gsva_group","",forest_data$id)
forest_data$yend1 <-nrow(forest_data):1
forest_data[,3:7] <- as.data.frame(sapply(forest_data[,3:7] ,as.numeric))
forest_data <- forest_data[order(forest_data$HR),] #HR排序
rownames(forest_data) <- 1:6 #排序有效
forest_data$yend <-1:nrow(forest_data)
library(ggplot2)
ggplot(data = forest_data,aes(x = HR, y = reorder(id,HR),group = id)
) +
geom_segment( aes(x =Low_95CI, xend = High_95CI, y = id, yend = id),color = "black",size=0.1 )+ # 主要横线
#geom_segment( aes(x =as.numeric(Low_95CI), xend = as.numeric(Low_95CI), y = yend, yend = yend+0.2),color = "black" ,size=0.1)+
#geom_segment( aes(x =as.numeric(Low_95CI), xend = as.numeric(Low_95CI), y = yend, yend = yend-0.2),color = "black" ,size=0.1)+
#geom_segment( aes(x =as.numeric(High_95CI), xend = as.numeric(High_95CI), y = yend, yend = yend+0.2),color = "black",size=0.1 )+
#geom_segment( aes(x =as.numeric(High_95CI), xend = as.numeric(High_95CI), y = id, yend =yend-0.2 ),color = "black" ,size=0.1)+
geom_segment( aes(x=1,xend=1,y=0.5,yend=6.5),color="grey",linetype='dashed',size=0.1)+ #HR=1
geom_point(size=4,aes(color = 100*Pvalue),pch=15)+
#scale_fill_manual(values = c("#93cc82","#88c4e8"))+ # c("#93cc82","#88c4e8") #"#CC79A7", "#56B4E9" 天蓝,浅紫 #"#238b45","#2171b5"深蓝,绿
labs(x = 'Hazard Ratio', y = ''#,color="Sign."
)+theme_bw()+
theme(text = element_text(size=16,family = "serif"),#legend.position = c(0.8,0.8),
panel.grid = element_blank() )
ggsave("./output/Forestplot_GSVA_2.pdf",width=8, height=3.5)
##类似SSGSVA画法--挑OS通路
gsva_boxplot <- merge(gsva_gsea_gmt_padjust_1,clinical_1[,c("sample","STAT4_group")],by="sample")
rownames(gsva_boxplot) <- gsva_boxplot[,1]
gsva_boxplot <- gsva_boxplot[,-1] #1-43
library(reshape2)
gsva_New = melt(gsva_boxplot[,c(forest_data$id,"STAT4_group")])# 融合数据:宽数据变成长数据43043-3 取OS GSVA!!!!! 6006-3
colnames(gsva_New )=c("group_stat4","Celltype","Score") #设置行名 #无sample?
head(gsva_New )
# 按免疫细胞占比中位数排序绘图(可选)
library(dplyr)
plot_order_1 = gsva_New [gsva_New $group_stat4=="High",] %>%
group_by(Celltype) %>%
summarise(m = median(Score)) %>% #
arrange(desc(m)) %>%
pull(Celltype)
gsva_New$Celltype = factor(gsva_New $Celltype,levels = plot_order_1)
if(T){
mytheme <- theme(plot.title = element_text(size = 12,color="black",hjust = 0.5),
axis.title = element_text(size = 12,color ="black"),
axis.text = element_text(size= 12,color = "black"),
panel.grid.minor.y = element_blank(),
panel.grid.minor.x = element_blank(),
axis.text.x = element_text(angle = 0, hjust = 1 ),
panel.grid=element_blank(),
legend.position = "top",
legend.text = element_text(size= 12),
legend.title= element_text(size= 12)
) }
library(ggplot2);library(ggpubr)
box_TME <- ggplot(gsva_New , aes(x = Celltype, y = Score))+ ##Celltype/T cells follicular /helper Neutrophils
labs(y="ssGSEA score",x= NULL)+
geom_boxplot(aes(fill = group_stat4),outlier.size = 0.02,size=0.02,outlier.alpha = 0)+
#geom_bar(stat = "identity")+
scale_fill_manual(values = c("skyblue","pink") )+ #"#1CB4B8", "#EB7369" "skyblue","pink"
guides(fill = guide_legend(title = 'STAT4'))+
theme_bw()+ mytheme +
#ylim(-0.4,0.65)+
stat_compare_means(aes(group = group_stat4),
label = "p.signif",
#label.y = 0.6,
size=3,#0.6
method = "wilcox.test",
hide.ns = T)+
coord_flip()
# geom_signif(annotations = c(""),color="black",size = 0.1, #手动加括号
# y_position = c(0.12,0.12),
# xmin = c(8.81,21.81),
# xmax = c(9.188,22.188),
# tip_length = c(0.01,0.02,0.1,0.1))
box_TME
ggsave("./immune/ssGSEA_box_OS6_2.pdf",box_TME,height=5,width=6,family="serif")
write.csv(gsva_New,"./220719/Figure2E_gsva_boxplot.csv")
###
plotList_3 <- list()
corPlotNum <- 50
if(nrow(outTab)<corPlotNum){
corPlotNum=nrow(gsva_boxplot[,1:43])
} #同样,定义一个空的列表plotList_2用于保存输出结果
for(i in 1:corPlotNum){ #1:corPlotNum
Gene <- Gene
Drug <- gsva_boxplot[,i]#outTab_GDSC2[abs(as.numeric(outTab_GDSC2$cor)) > 0.4 ,][i,2] #3 个#outTab_GDSC2[i,2]
#x <- as.numeric(exp[Gene,])
#y <- as.numeric(drug[Drug,])
df1 <- as.data.frame(cbind(Gene,gsva_boxplot[,Drug]))
colnames(df1)[2] <- "IC50" #GSVA
df1$IC50 <- as.numeric(df1$IC50)
#df1$group <- ifelse(df1$x > median(df1$x), "high", "low")
df1$group <- gsva_boxplot$STAT4_group #subset(GDSC2,colnames(GDSC2)== Drug)$STAT4_group
compaired <- list(c("Low", "High"))
p1 <-ggplot(df1,aes(x =group, y =IC50,color =group))+ #,palette = c("firebrick3","skyblue")
labs(title= gsub("\\_.*","",Drug),ylab="Log2(IC50)")+
geom_point(alpha=0.2,size=1.5,
position=position_jitterdodge(jitter.width = 0.45,
jitter.height = 0,
dodge.width = 0.8))+
geom_boxplot(alpha=0.5,width=0.55,
position=position_dodge(width=0.8),
size=0.05,outlier.colour = NA)+
# geom_violin(alpha=0.2,width=0.9,
# position=position_dodge(width=0.8),
# size=0.25)+
scale_color_manual(values = c("#CC79A7", "#56B4E9") )+ #color
# stat_compare_means(comparisons = compaired,vjust=0.4,
# method = "wilcox.test",size=4, #设置统计方法
# symnum.args=list(cutpoints = c(0, 0.001, 0.01, 0.05, 1),
# symbols = c("***", "**", "*", "ns")))+
#coord_cartesian(ylim = c( NA,max(log2(df1$IC50))+1.5 ) )+ #否则*显示不全,log2(0)=inf
ylim(c( NA,max(log2(df1$IC50))+1.5 ))+
stat_compare_means(#aes(group = Group) ,
comparisons=list(c("High","Low")),#my_comparisons,
label = "p.signif",#"p.format p.signif 9.4e-12
method = "wilcox",
show.legend= F,#删除图例中的"a"
label.x=1.5,bracket.size=0.1,vjust=0.1,
#label.y = max(log2(GDSC2$Camptothecin_1003)),
hide.ns = T,size=4)+
theme_bw()+
theme(axis.title = element_text(size=12), axis.text = element_text(size=12),legend.position ="none",
panel.grid = element_blank(),legend.key = element_blank(),axis.title.x =element_blank() )
plotList_3[[i]]=p1
}
ggarrange(plotlist=plotList_3,nrow=5,ncol=5) #STAT4_group
#ggsave("./output/GSVA_boxplot_1.pdf",family="serif",width = 6,height = 2)
#放弃:high riskscore should be more higher EMT gsva score, but the fact is opposite.
#3.5 EMT 评分----
#3.5.1 log2 Z scores https://zhuanlan.zhihu.com/p/366181769 ;#https://www.sciencedirect.com/science/article/pii/S0169500219306932#sec0095
#EMT genes:
Epithelial_genes <- c("CDH1","CDH3","CLDN4","EPCAM","ST14","MAL2") #6
Mesencyhmal_genes<-c("VIM","SNAI2","ZEB2","FN1","MMP2","AGER","SNAI1","TWIST1","ZEB1","FOXC1","TWIST2","CDH2")#12
EMT_genes_logZ <- data.frame(genes=Epithelial_genes,
group="Epithelial")
EMT_genes_logZ <- rbind(EMT_genes_logZ, data.frame(genes=Mesencyhmal_genes,
group="Mesencyhmal") )
#a. 选取高表达六个基因计算
EMT_exp_logZ <- subset(exp1,rownames(exp1) %in% EMT_genes_logZ$genes) #18 1001
boxplot(log2(EMT_exp_logZ[1,] ))#查看基因表达
for (i in 1:18){
print(rownames(EMT_exp_logZ[i,]))
print(mean(as.numeric(EMT_exp_logZ[i,]) ))
} #查看均值
#计算EMT Zscore
zscore <- matrix(nrow = 18,ncol = 1001)
zscore <- as.data.frame(zscore)
for (i in 1:1001){ #1001
for (j in 1:18){
varname = rownames(EMT_exp_logZ)[j]
zscore0 = (EMT_exp_logZ[varname,i] - mean(as.numeric(EMT_exp_logZ[varname,])) )/ sd(as.numeric(EMT_exp_logZ[varname,]) ) #!注意公式!
zscore[j,i] <- zscore0
rownames(zscore)[j]<-varname
colnames(zscore)[i]<-colnames(EMT_exp_logZ)[i]
}
} #时间较久~10min
boxplot(zscore[1,] ) #查看zscore与log2 zscore
boxplot(log2(zscore[1,]) )
zscore_mean_1 <-data.frame()
for (i in 1:18){
# ifelse(rownames(zscore[i,]) %in% Epithelial_genes,
# print(rownames(zscore[i,])+ mean(as.numeric(zscore[i,]) )),
# "")
# #print(mean(as.numeric(zscore[i,]) ))
zscore_mean <- data.frame(mean=mean(as.numeric(zscore[i,])),gene= rownames(zscore[i,]) )
zscore_mean_1 <- rbind(zscore_mean_1,zscore_mean)
} #查看均值
zscore_mean_1 <- subset(zscore_mean_1,zscore_mean_1$gene %in% Mesencyhmal_genes) #12 #选取高表达六个Mesencyhmal_genes基因
#score EMT
zscore1<- subset(zscore,rownames(zscore) %in%c("VIM","FN1","MMP2","SNAI2","FOXC1","TWIST1",
"CDH1","CDH3","CLDN4","EPCAM","ST14","MAL2") ) #最终EMT 基因 12-1001
#计算每个样本的EMT score; log2 Z
#zscore1<-log2(zscore1) #负数取log2 会有NA??
zscore1<- as.data.frame(t(zscore1))
zscore1$EMT_Zscore <- rowSums(zscore1[,c("VIM","FN1","MMP2","SNAI2","FOXC1","TWIST1")])-rowSums(zscore1[,c("CDH1","CDH3","CLDN4","EPCAM","ST14","MAL2")])
#合并结果到clinical
#3.5.2 https://zhuanlan.zhihu.com/p/442875983
#a.读取基因
emt315 <- readxl::read_xlsx("./emt/EMT315.xlsx",col_names = NA)
colnames(emt315) <- c("gene","group")
Epithelial_genes145 <- subset(emt315,emt315$group=="Epi")$gene #145
Mesencyhmal_genes170 <- subset(emt315,emt315$group=="Mes")$gene #170
#b. 计算得分
emt315_exp <- subset(exp1,rownames(exp1) %in% c(emt315$gene,"GZMA","PRF1") ) #取EMT+"GZMA","PRF1"基因矩阵:305-1001
emt315_exp <- as.data.frame(t(emt315_exp))#转置矩阵后计算得分-1001-305
Mesencyhmal_genes163<- colnames(emt315_exp)[colnames(emt315_exp) %in% Mesencyhmal_genes170] #163 -7
Epithelial_genes140<- colnames(emt315_exp)[colnames(emt315_exp) %in% Epithelial_genes145] #140 -5
emt315_exp$EMT_score <-(rowSums(emt315_exp[,Mesencyhmal_genes163])/1001-rowSums(emt315_exp[,Epithelial_genes140])/1001 ) #/ (sd(emt315_exp[,Mesencyhmal_genes163])-sd(emt315_exp[,Epithelial_genes140]) )#计算EMT315
sd(emt315_exp[2,Mesencyhmal_genes163])
EMT_score_df <- data.frame()
for (i in 1:1001){ #i 为样本数
mes_exp <- emt315_exp[,colnames(emt315_exp) %in% Mesencyhmal_genes163][i,]#1001-163
epi_exp <- emt315_exp[,colnames(emt315_exp) %in% Epithelial_genes140][i,]
EMT_score <- (mean(as.numeric(mes_exp)) -mean(as.numeric(epi_exp)) )/(sd(mes_exp)-sd(epi_exp) )##-mean(emt315_exp[i,Epithelial_genes140]) )#/()
CYT=sqrt(emt315_exp[i,]$GZMA * emt315_exp[i,]$PRF1)
EMT_score_df <- rbind(data.frame(sample=rownames(emt315_exp)[i],EMT_score=EMT_score,CYT=CYT),EMT_score_df)
}
emt <- (EMT_score_df$EMT_score - mean(EMT_score_df$EMT_score) )/sd(EMT_score_df$EMT_score)
cyt <- (EMT_score_df$CYT - mean(EMT_score_df$CYT) )/sd(EMT_score_df$CYT)
EMT_score_df$ECI <- log( exp(emt) / exp(cyt)) #CALCULATE ECI
##合并2个EMT到临床数据中:EMT_score_df,zscore1,clinical_1
#clinical_1 <- merge(clinical,gsva_gsea_gmt_padjust_1,by="sample")#1001-174
clinical_1 <-merge(clinical_1,EMT_score_df,by="sample") #1001-177
clinical_1 <- cbind(clinical_1,as.data.frame(zscore1$EMT_Zscore)) #1001-178
colnames(clinical_1)[178] <- "EMT_Zscore"
#write.csv(clinical_1,"clinical_1.csv") #保存clinical_1 ,以后直接读取!!!
clinical_1 <-read.csv("clinical_1.csv")
##3.5.3 EMT score 与临床
library(ggplot2);library(ggpubr) #ECI CYT Group
ggplot(data=clinical_1,aes(x=STAT4_group,y=log2(EMT_Zscore),color=STAT4_group))+ #fill
geom_point(alpha=0.5,size=1.5,
position=position_jitterdodge(jitter.width = 0.35,
jitter.height = 0,
dodge.width = 0.8))+
geom_boxplot(alpha=0.2,width=0.5,
position=position_dodge(width=0.8),
size=0.05,outlier.colour = NA) +
# geom_violin(alpha=0.2,width=0.9,
# position=position_dodge(width=0.8),
# size=0.25)+
#scale_color_manual(values = c("#CC79A7", "#56B4E9") )+ #color
theme_bw() +#ylab("EMT gasv score")+xlab("")+
#theme(legend.position="none")
theme(axis.title = element_text(size=16), axis.text = element_text(size=12),legend.position ="top",
panel.grid = element_blank(),legend.key = element_blank() ) +
stat_compare_means(#aes(group = Group) ,
comparisons=list(c("High","Low")),#my_comparisons,
label = "p.signif",#"p.format p.signif 9.4e-12
method = "wilcox",
show.legend= F,#删除图例中的"a"
label.x=1.5,bracket.size=0.1,vjust=0.2,
#label.y = max(log2(GDSC2$Camptothecin_1003)),
hide.ns = T,size=5)
#RISKSCORE GROUP ECI 合理;EMT RIKSCORE/ EMT zscore 无显著性;STAT4 group趋势相反
# ECI,CYT 结果不受log2影响;
#CYT 预后:https://www.ncbi.nlm.nih.gov/pmc/articles/PMC8332854/#!po=20.4545
#解释CYT,EMT,ECI与riskscore ?或者放弃
#4. 免疫评分----
#4.1 estimate ----
##安装包:下次使用,请设置工作目录
# library(utils)
# rforge <- "http://r-forge.r-project.org"
# install.packages("estimate", repos=rforge, dependencies=TRUE)
library(estimate)#引用包
##输入表达矩阵,基因在行,sample在列。检查文件格式
#write.table(exp1,"exp1.txt",sep = "\t",quote=F)#输入矩阵:https://www.jianshu.com/p/e72914fbcfaf
in.file2 <- "D:/\u7814\u7a76\u751f\u79d1\u7814/\u751f\u7269\u4fe1\u606f\u5b66/STAT4/Subgroup_STAT4/3.Enrichment/exp1.txt"
filterCommonGenes(input.f=in.file2,output.f="./immune/breast_19551genes.gct")#9876 genes (536 mismatched)
##计算评分
estimateScore("./immune/breast_19551genes.gct", "./immune/brca_estimate_score.gct", platform="illumina") #illumina
##读取结果及可视化
estimatescores=read.table("./immune/brca_estimate_score.gct",skip = 2,header = T)
rownames(estimatescores)=estimatescores[,1]
estimatescores.final=t(estimatescores[,3:ncol(estimatescores)])
#save(estimatescores.final, file="estimatescores.final.Rda")
#write.table(estimatescores.final, file = "./immune/estimatescores.final.txt",sep = "\t",row.names = T,col.names = NA,quote = F) # 保存并覆盖score
#D:\研究生科研\生物信息学\STAT4\Subgroup_STAT4\3.Enrichment\immune
##合并结果:https://www.jianshu.com/p/800ab6347d7e
rownames(estimatescores.final)<- gsub("\\.","-",rownames(estimatescores.final) )#处理结果
estimatescores.final <- as.data.frame(estimatescores.final)
estimatescores.final$sample <- rownames(estimatescores.final) #1003-4
clinical_1 <- merge(clinical_1,estimatescores.final,bvy="sample")#合并到临床数据中-178->181
##简要可视化
#画图
library(ggpubr)
ggboxplot(clinical_1, x = "STAT4_group", y = "StromalScore",#"ESTIMATEScore",# ImmuneScore StromalScore
fill = "STAT4_group", palette = "lancet")+
stat_compare_means(aes(group = STAT4_group),
method = "wilcox.test",
label = "p.signif",label.x = 1.5,
symnum.args=list(cutpoints = c(0, 0.001, 0.01, 0.05, 1),
symbols = c("***", "**", "*", "ns")))+
theme(text = element_text(size=10),
axis.text.x = element_text(angle=0, hjust=1)) #重新绘制
#ESTIMATEScore= ImmuneScore + StromalScore #合理:STAT4 LOW均低于STAT HIGH !!!
##可视化二:宽数据转为长数据,绘图!https://www.jianshu.com/p/800ab6347d7e
estimate_test <-clinical_1[,c("sample","Group","STAT4_group","StromalScore","ESTIMATEScore","ImmuneScore")] #estimatescores.final
estimate_test <-tidyr::gather(estimate_test,key=category,value = score,ESTIMATEScore,ImmuneScore,StromalScore,-STAT4_group)
#画图
ggboxplot(estimate_test, x = "category", y = "score",
fill = "STAT4_group", palette = "lancet",outlier.shape=NA,size=0.1,alpha=0.5 )+
#labs(ylab="Estimate Score",xlab="")+
ylab("Scores")+xlab("")+
scale_fill_manual(values = c("#CC79A7", "#56B4E9") )+
guides(fill = guide_legend(title = 'STAT4'))+
stat_compare_means(aes(group = STAT4_group),#
method = "wilcox.test",
label = "p.signif",size=5,
symnum.args=list(cutpoints = c(0, 0.001, 0.01, 0.05, 1),
symbols = c("***", "**", "*", "ns")))+
theme_bw()+
theme(text = element_text(size=14)#,axis.text.x = element_text(angle=30, hjust=1)
)
#ggsave("./immune/estimate_box.pdf",family="serif",width = 6,height = 4)
#write.csv(estimate_test,"./220719/Figure3B_estimate_box.csv")
##图丑,重新画
library(ggplot2);library(ggpubr)
ggplot(estimate_test,aes(x =category, y =score,color =STAT4_group))+ #,palette = c("firebrick3","skyblue")
ylab("Score")+
geom_point(alpha=0.1,size=1.0,
position=position_jitterdodge(jitter.width = 0.2,
jitter.height = 0,
dodge.width = 0.8))+
geom_boxplot(alpha=0.5,width=0.45,
position=position_dodge(width=0.8),
size=0.05,outlier.colour = NA)+
# geom_violin(alpha=0.2,width=0.9,
# position=position_dodge(width=0.8),
# size=0.25)+
scale_color_manual(values = c("#56B4E9","#CC79A7") )+ #color "#56B4E9","#CC79A7" 天蓝 朱红
#coord_cartesian(ylim = c(NA,max(estimate_test$score)+100 ))+
stat_compare_means(aes(group = STAT4_group),label = "p.signif",size=3,show.legend = F,label.y = c(5200,3500,3000))+
geom_signif(annotations = c("","",""),color="black",size = 0.1, #手动加括号
y_position = c(5200,3500,3000),
xmin = c(0.8,1.8,2.8),
xmax = c(1.2,2.2,3.2),
tip_length = c(0.02,0.2,0.02,0.18,0.04,0.1))+
guides(color = guide_legend(title = 'STAT4'))+ ##/ labs(fill/ color="")+ # legend https://www.jianshu.com/p/b50c8393e3ed
theme_bw()+
theme(axis.title = element_text(size=12), #axis.text = element_text(size=12),#legend.position ="none",
axis.text.x = element_text(size=10),#angle=0, hjust=0,
legend.position = "top",
panel.grid = element_blank(),legend.key = element_blank(),axis.title.x =element_blank() )
#list(c("High","Low")) 需要TRUE/FALSE值的地方不可以用缺少值 可能与长数据有关
ggsave("./immune/estimate_boxplot_1.pdf",family="serif",width = 5,height = 3)
##4.2 cibersort----
#a.安装包:https://blog.csdn.net/m0_58549466/article/details/124255582
devtools::install_github('shenorrlab/bseqsc')
library(bseqsc)
if(!require(CIBERSORT))devtools::install_github("Moonerss/CIBERSORT")
library(CIBERSORT) #version 0.1.0
#b. 加载数据
data(LM22) ;LM22
data(mixed_expr);mixed_expr#TCGA的演示数据,正式情况下就用自己的数据:matrix
# 分别定义signature矩阵LM22和我的数据(演示)矩阵mixed_expr
results <- cibersort(sig_matrix = LM22, mixture_file = exp1_matrix)#表达矩阵-1001时间较久~10min
#按行(样本内部)标准化可以看出在各类样本内部,M2浸润程度(占比)最高
rowscale <- results[,1:ncol(LM22)]#只是相当于备份了一下results
rowscale <- rowscale[,apply(rowscale, 2, function(x){sum(x)>0})]#删除全是0的列
rowscale <- as.data.frame(rowscale) #cibersort结果
rowscale1 <- cbind(estimatescores.final[1:1001,1:3],rowscale) #cibersort+合并estimate结果[,1:3] [,3:25]
rowscale1[,1:3] <- as.data.frame(sapply(rowscale1[,1:3],as.numeric))
library(pheatmap)
annotation_col1 <- data.frame( Group= clinical_1$Group,STAT4=clinical_1$STAT4_group,PAM50=clinical_1$PAM50)#1001
row.names(annotation_col1) <- rownames(rowscale1)
pheatmap::pheatmap(t(rowscale1[,1:3]),
#scale = 'row',#按行标准化,不标准化就会按绝对值显示,很诡异
#cluster_col=T,#是否对列聚类,不聚类,坐标轴就按照原来的顺序显示
#cluster_row=F,#是否对行聚类
#angle_col = "315",#调整X轴坐标的倾斜角度
show_colnames = F,
annotation_col = annotation_col1) #注意方向!Error in check.length("fill") : 'gpar' element 'fill' must not be length 0
# 各类样本之间也具有自己占比高的特异性免疫细胞
pheatmap(rowscale,
scale = 'column',
cluster_col=F,
cluster_row=T,
angle_col = "315")
# 堆积比例图
# results <- as.data.frame(results)
# results$sample <- rownames(results)
# results<- merge(results,clinical_1[,c("sample","Group","STAT4_group")],by="sample")
my36colors <-c('#E5D2DD', '#53A85F', '#F1BB72', '#F3B1A0', '#D6E7A3', '#57C3F3', '#476D87','#E95C59', '#E59CC4', '#AB3282', '#23452F', '#BD956A', '#8C549C', '#585658','#9FA3A8', '#E0D4CA', '#5F3D69', '#C5DEBA', '#58A4C3', '#E4C755', '#F7F398','#AA9A59', '#E63863', '#E39A35', '#C1E6F3', '#6778AE', '#91D0BE', '#B53E2B', '#712820', '#DCC1DD', '#CCE0F5', '#CCC9E6', '#625D9E', '#68A180', '#3A6963','#968175'
)
cellnum <- results[,1:22] #ncol(LM22)
cell.prop<- apply(cellnum, 1, function(x){x/sum(x)})
data4plot <- data.frame()
for (i in 1:ncol(cell.prop)) {
data4plot <- rbind(
data4plot,
cbind(cell.prop[,i],rownames(cell.prop),
rep(colnames(cell.prop)[i],nrow(cell.prop)
)
)
)
}
colnames(data4plot)<-c('proportion','celltype','sample')
data4plot$proportion <- as.numeric(data4plot$proportion)
library(ggplot2)
ggplot(data4plot,aes(sample,proportion,fill=celltype) )+
geom_bar(stat="identity",position="fill",alpha=0.8)+
scale_fill_manual(values=my36colors)+#自定义fill的颜色
ggtitle("cell portation")+ylab("Cell propotion")+
theme_bw()+
theme(axis.ticks.length=unit(0.5,'cm'),axis.title.x=element_text(size=1))+
theme(axis.text.x = element_text(angle = 45, hjust = 0.5, vjust = 0.5))+#把x坐标轴横过来
guides(fill=guide_legend(title=NULL)) #样本太大,分组?堆叠图