Thursday, April 10, 2014

R: Plotting fold change

This simple script was generated for drawing FC plot. I do not have any plan to improve it as a function right now but maybe later with density / frequency scheme.


Edit lines 1~3 and save it as 'plot.R' then type 'R CMD BATCH plot.R' in command line.
It will color differently for fold-changes and display rho value from the Spearman's rank correlation test. It also generate subset text file for fold-changes


If your file have a header, change the boolean for header to 'F' in line 7.
If your system doesn't support X11 graphics, change file type to PDF.
   ex) pdf(file=paste0("plot_color_",axis_x,"_vs_",axis_y,".pdf"))



 FOLD<-c(4)               # Threshold of fold change
 FILE<-c("data.txt",8,9)  # Your file and two data columns
 SIZE<-0.3                # Size of dot

 x<-as.numeric(FILE[2])
 y<-as.numeric(FILE[3])
 f<-read.table(file=FILE[1], sep="\t", header=T)
 axis_x<-colnames(f)[x]
 axis_y<-colnames(f)[y]
 f.sub_down<-subset(f,f[,x]>f[,y]*FOLD)
 f.sub_up<-subset(f,f[,y]>f[,x]*FOLD)

 #Change png to pdf or jpg if you want
 png(file=paste0("plot_color_",axis_x,"_vs_",axis_y,".png"))      
 plot(log10(f[,x]),log10(f[,y]),ylab=axis_y,xlab=axis_x,
      pch=19,cex=SIZE,xlim=c(0,5),ylim=c(0,5));
 par(new=T)
 plot(log10(f.sub_up[,x]),log10(f.sub_up[,y]),
      ylab=axis_y,xlab=axis_x,pch=19,col="red",cex=SIZE,
      xlim=c(0,5),ylim=c(0,5));
 par(new=T)
 plot(log10(f.sub_down[,x]),log10(f.sub_down[,y]),
      ylab=axis_y,xlab=axis_x,pch=19,col="blue",cex=SIZE,
      xlim=c(0,5),ylim=c(0,5));
 #Remove below one line if you don't want y=x line
 abline(0,1, col="lightgray")                                    
 #You can change 'spearman' to 'pearson' or 'kendall'
 cor.coeff<-cor(f[,x],f[,y],method="spearman")
 text(4,1.5,labels=paste0("rho=",round(cor.coeff,digits=4)))
 invisible(dev.off())

 write.table(f.sub_up,file=paste0("subset_up",FOLD,"_",FILE[1]),
             sep="\t")
 write.table(f.sub_down,file=paste0("subset_down",FOLD,"_",FILE[1]),
             sep="\t")




No comments:

Post a Comment