分析需求/适用场景
我们常常要比较N个元素的不同状态在两组间的分布情况,分析富集于一组的元素。那此时就可以对每个元素不同状态在两组的数量进行Fisher检验,然后通过可视化直观的发现富集于某一组的元素。
分析过程
下面以分析一组基因的突变在两个人群中分布是否均匀(有没有基因的突变是显著富集在其中一个人群中)为例展示分析过程。
对于每个基因都有下面的四联表:
image.png
利用上述四联表进行Fisher检验:
1 Fisher检验
脚本存储在Fisher_volcano_plot.r中,内容如下:
args = commandArgs(T)
if (length(args) !=2){
print("Rscript this R <infile> <outfile>")
q()
}
library(plyr)
data<-read.table(args[1],header=TRUE,sep='\t')
Pvalue<-apply(subset(data, select=c(Mut_genecast,Wt_genecast,Mut_occidental,Wt_occidental)),1,function(x) {fisher.test(matrix(c(x),nrow=2),alternative ="two.sided",workspace =900000000)}$p.value)
OR<-apply(subset(data, select=c(Mut_genecast,Wt_genecast,Mut_occidental,Wt_occidental)),1,function(x) {fisher.test(matrix(c(x),nrow=2),alternative ="two.sided",workspace =900000000)}$estimate)
out<-cbind(data,Pvalue,OR)
write.table(out,file=args[2],sep='\t',quote=F,row.names=FALSE)
运行命令:
Rscript Fisher_volcano_plot.r overlap_gene_for_fisher overlap_gene_for_fisher.result
输入文件示例:
image.png
结果展示:
image.png
2 Fisher结果可视化
library(plyr)
library(ggplot2)
library(ggrepel)
setwd("D:/work_tmp/point_plot/")
data<-read.table("overlap_gene_for_fisher.result",header=TRUE,row.name=1,sep='\t')
data$Pvalue<- -log10(data$Pvalue)
vline=-log10(0.00001)
sub<-data[data$OR>1,]
sub2<-data[data$Pvalue>vline,]
pdf("overlap_gene_for_fisher.result.pdf",width=12,height=6)
ggplot(data) +geom_point(aes(Pvalue, OR), color = 'red') + theme_classic(base_size = 13)+geom_hline(aes(yintercept=1), colour="grey", linetype="dashed") +geom_vline(aes(xintercept=vline), colour="grey", linetype="dashed") + geom_text_repel(data=sub,aes( Pvalue, OR, label = rownames(sub)),segment.size = 0.1,size=2) + geom_text_repel(data=sub2,aes( Pvalue, OR, label = rownames(sub2)),segment.size = 0.1,size=1.8)+xlab('-log10( Pvalue )')+ylab('Odds ratio')
#给点加标签:geom_text(aes( Pvalue, OR, label = rownames(data)))
#给点加标签(不重叠):geom_text_repel(aes( Pvalue, OR, label = rownames(data)))
#为图形添加直线:geom_hline(aes(yintercept=1), colour="grey", linetype="dashed") +geom_vline(aes(xintercept=vline), colour="grey", linetype="dashed")
#ggplot(data) +geom_point(aes(Pvalue, OR), color = 'red') + geom_text(aes(Pvalue+0.8, OR+0.03, label = rownames(data))) + theme_classic(base_size = 16)
dev.off()
结果示例:
image.png
网友评论