分析需求/適用場景
我們常常要比較N個元素的不同狀態(tài)在兩組間的分布情況刻盐,分析富集于一組的元素谤职。那此時就可以對每個元素不同狀態(tài)在兩組的數(shù)量進行Fisher檢驗,然后通過可視化直觀的發(fā)現(xiàn)富集于某一組的元素涮瞻。
分析過程
下面以分析一組基因的突變在兩個人群中分布是否均勻(有沒有基因的突變是顯著富集在其中一個人群中)為例展示分析過程便脊。
對于每個基因都有下面的四聯(lián)表:
image.png
利用上述四聯(lián)表進行Fisher檢驗:
1 Fisher檢驗
腳本存儲在Fisher_volcano_plot.r中,內(nèi)容如下:
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
結(jié)果展示:
image.png
2 Fisher結(jié)果可視化
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')
#給點加標(biāo)簽:geom_text(aes( Pvalue, OR, label = rownames(data)))
#給點加標(biāo)簽(不重疊):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()
結(jié)果示例:
image.png