PageRenderTime 32ms CodeModel.GetById 18ms app.highlight 9ms RepoModel.GetById 1ms app.codeStats 1ms

/test-data/rgtestouts/rgManQQ/rgManQQtest1.R

https://bitbucket.org/cistrome/cistrome-harvard/
R | 195 lines | 157 code | 13 blank | 25 comment | 35 complexity | 47f8561eb86dd7290164372e91c26efd MD5 | raw file
  1
  2# generalised so 3 core fields passed as parameters ross lazarus March 24 2010 for rgenetics
  3# Originally created as qqman with the following 
  4# attribution:
  5#--------------
  6# Stephen Turner
  7# http://StephenTurner.us/
  8# http://GettingGeneticsDone.blogspot.com/
  9
 10# Last updated: 19 July 2011 by Ross Lazarus
 11# R code for making manhattan plots and QQ plots from plink output files. 
 12# With GWAS data this can take a lot of memory. Recommended for use on 
 13# 64bit machines only, for now. 
 14
 15#
 16
 17library(ggplot2)
 18
 19coloursTouse = c('firebrick','darkblue','goldenrod','darkgreen')
 20# not too ugly but need a colour expert please...
 21
 22
 23DrawManhattan = function(pvals=Null,chrom=Null,offset=Null,title=NULL, max.y="max",suggestiveline=0, genomewide=T, size.x.labels=9, 
 24              size.y.labels=10, annotate=F, SNPlist=NULL,grey=0) {
 25        if (annotate & is.null(SNPlist)) stop("You requested annotation but provided no SNPlist!")
 26        genomewideline=NULL # was genomewideline=-log10(5e-8)
 27        n = length(pvals)
 28        if (genomewide) { # use bonferroni since might be only a small region?
 29            genomewideline = -log10(0.05/n) }
 30        offset = as.integer(offset)
 31        if (n > 1000000) { offset = offset/10000 }
 32        else if (n > 10000) { offset = offset/1000}
 33        chro = as.integer(chrom) # already dealt with X and friends?
 34        pvals = as.double(pvals)
 35        d=data.frame(CHR=chro,BP=offset,P=pvals)
 36        if ("CHR" %in% names(d) & "BP" %in% names(d) & "P" %in% names(d) ) {
 37                d=d[!is.na(d$P), ]
 38                d=d[!is.na(d$BP), ]
 39                d=d[!is.na(d$CHR), ]
 40                #limit to only chrs 1-22, x=23,y=24,Mt=25?
 41                d=d[d$CHR %in% 1:25, ]
 42                d=d[d$P>0 & d$P<=1, ]
 43                d$logp = as.double(-log10(d$P))
 44                dlen = length(d$P)
 45                d$pos=NA
 46                ticks=NULL
 47                lastbase=0
 48                chrlist = unique(d$CHR)
 49                chrlist = as.integer(chrlist)
 50                chrlist = sort(chrlist) # returns lexical ordering 
 51                if (max.y=="max") { maxy = ceiling(max(d$logp)) } 
 52                   else { maxy = max.y }
 53                nchr = length(chrlist) # may be any number?
 54                maxy = max(maxy,1.1*genomewideline)
 55                if (nchr >= 2) {
 56                    for (x in c(1:nchr)) {
 57                        i = chrlist[x] # need the chrom number - may not == index
 58                        if (x == 1) { # first time
 59                            d[d$CHR==i, ]$pos = d[d$CHR==i, ]$BP # initialize to first BP of chr1
 60                            dsub = subset(d,CHR==i)
 61                            dlen = length(dsub$P)
 62                            lastbase = max(dsub$pos) # last one
 63                            tks = d[d$CHR==i, ]$pos[floor(length(d[d$CHR==i, ]$pos)/2)+1]
 64                            lastchr = i
 65                        } else {
 66                            d[d$CHR==i, ]$pos = d[d$CHR==i, ]$BP+lastbase # one humongous contig
 67                            if (sum(is.na(lastchr),is.na(lastbase),is.na(d[d$CHR==i, ]$pos))) { 
 68                                cat(paste('manhattan: For',title,'chrlistx=',i,'lastchr=',lastchr,'lastbase=',lastbase,'pos=',d[d$CHR==i,]$pos))
 69                             }   
 70                            tks=c(tks, d[d$CHR==i, ]$pos[floor(length(d[d$CHR==i, ]$pos)/2)+1])
 71                            lastchr = i
 72                            dsub = subset(d,CHR==i)
 73                            lastbase = max(dsub$pos) # last one
 74                        }
 75                    ticklim=c(min(d$pos),max(d$pos))
 76                    xlabs = chrlist
 77                    }
 78                } else { # nchr is 1
 79                   nticks = 10
 80                   last = max(d$BP)
 81                   first = min(d$BP)
 82                   tks = c(first)
 83                   t = (last-first)/nticks # units per tick
 84                   for (x in c(1:(nticks))) { 
 85                        tks = c(tks,round(x*t)+first) }
 86                   ticklim = c(first,last)
 87                } # else
 88                if (grey) {mycols=rep(c("gray10","gray60"),max(d$CHR))
 89                           } else {
 90                           mycols=rep(coloursTouse,max(d$CHR))
 91                           }
 92                dlen = length(d$P)
 93                d$pranks = rank(d$P)/dlen
 94                d$centiles = 100*d$pranks # small are interesting
 95                d$sizes = ifelse((d$centile < 1),2,1)
 96                if (annotate) d.annotate=d[as.numeric(substr(d$SNP,3,100)) %in% SNPlist, ]
 97                if (nchr >= 2) {
 98                        manplot=qplot(pos,logp,data=d, ylab=expression(-log[10](italic(p))) , colour=factor(CHR),size=factor(sizes))
 99                        manplot=manplot+scale_x_continuous(name="Chromosome", breaks=tks, labels=xlabs,limits=ticklim) 
100                        manplot=manplot+scale_size_manual(values = c(0.5,1.5)) # requires discreet scale - eg factor
101                        #manplot=manplot+scale_size(values=c(0.5,2)) # requires continuous 
102                        }
103                else {
104                        manplot=qplot(BP,logp,data=d, ylab=expression(-log[10](italic(p))) , colour=factor(CHR))
105                        manplot=manplot+scale_x_continuous(name=paste("Chromosome",chrlist[1]), breaks=tks, labels=tks,limits=ticklim) 
106                     }                 
107                manplot=manplot+scale_y_continuous(limits=c(0,maxy), breaks=1:maxy, labels=1:maxy)
108                manplot=manplot+scale_colour_manual(value=mycols)
109                if (annotate) {  manplot=manplot + geom_point(data=d.annotate, colour=I("green3")) } 
110                manplot=manplot + opts(legend.position = "none") 
111                manplot=manplot + opts(title=title)
112                manplot=manplot+opts(
113                     panel.background=theme_blank(), 
114                     axis.text.x=theme_text(size=size.x.labels, colour="grey50"), 
115                     axis.text.y=theme_text(size=size.y.labels, colour="grey50"), 
116                     axis.ticks=theme_segment(colour=NA)
117                )
118                if (suggestiveline) manplot=manplot+geom_hline(yintercept=suggestiveline,colour="blue", alpha=I(1/3))
119                if (genomewideline) manplot=manplot+geom_hline(yintercept=genomewideline,colour="red")
120                manplot
121        }       else {
122                stop("Make sure your data frame contains columns CHR, BP, and P")
123        }
124}
125
126
127
128qq = function(pvector, title=NULL, spartan=F) {
129        # Thanks to Daniel Shriner at NHGRI for providing this code for creating expected and observed values
130        o = -log10(sort(pvector,decreasing=F))
131        e = -log10( 1:length(o)/length(o) )
132        # you could use base graphics
133        # plot(e,o,pch=19,cex=0.25, xlab=expression(Expected~~-log[10](italic(p))), 
134        # ylab=expression(Observed~~-log[10](italic(p))), xlim=c(0,max(e)), ylim=c(0,max(e)))
135        # lines(e,e,col="red")
136        #You'll need ggplot2 installed to do the rest
137        qq=qplot(e,o, xlim=c(0,max(e)), ylim=c(0,max(o))) + stat_abline(intercept=0,slope=1, col="red")
138        qq=qq+opts(title=title)
139        qq=qq+scale_x_continuous(name=expression(Expected~~-log[10](italic(p))))
140        qq=qq+scale_y_continuous(name=expression(Observed~~-log[10](italic(p))))
141        if (spartan) plot=plot+opts(panel.background=theme_rect(col="grey50"), panel.grid.minor=theme_blank())
142        qq
143}
144
145rgqqMan = function(infile="/data/tmp/tmpNaxDwH/database/files/000/dataset_1.dat",chromcolumn=2, offsetcolumn=3, pvalscolumns=c(8), 
146title="rgManQQtest1",grey=0) {
147rawd = read.table(infile,head=T,sep='\t')
148dn = names(rawd)
149cc = dn[chromcolumn]
150oc = dn[offsetcolumn] 
151rawd[,cc] = sub('chr','',rawd[,cc],ignore.case = T) # just in case
152rawd[,cc] = sub(':','',rawd[,cc],ignore.case = T) # ugh
153rawd[,cc] = sub('X',23,rawd[,cc],ignore.case = T)
154rawd[,cc] = sub('Y',24,rawd[,cc],ignore.case = T)
155rawd[,cc] = sub('Mt',25,rawd[,cc], ignore.case = T)
156nams = c(cc,oc) # for sorting
157plen = length(rawd[,1])
158print(paste('###',plen,'values read from',infile,'read - now running plots',sep=' '))
159rawd = rawd[do.call(order,rawd[nams]),]
160# mmmf - suggested by http://onertipaday.blogspot.com/2007/08/sortingordering-dataframe-according.html
161# in case not yet ordered
162if (plen > 0) {
163  for (pvalscolumn in pvalscolumns) {
164  if (pvalscolumn > 0) 
165     {
166     cname = names(rawd)[pvalscolumn]
167     mytitle = paste('p=',cname,', ',title,sep='')
168     myfname = chartr(' ','_',cname)
169     myqqplot = qq(rawd[,pvalscolumn],title=mytitle)
170     ggsave(filename=paste(myfname,"qqplot.png",sep='_'),myqqplot,width=8,height=6,dpi=96)
171     ggsave(filename=paste(myfname,"qqplot.pdf",sep='_'),myqqplot,width=8,height=6,dpi=96)
172     print(paste('## qqplot on',cname,'done'))
173     if ((chromcolumn > 0) & (offsetcolumn > 0)) {
174         print(paste('## manhattan on',cname,'starting',chromcolumn,offsetcolumn,pvalscolumn))
175         mymanplot= DrawManhattan(chrom=rawd[,chromcolumn],offset=rawd[,offsetcolumn],pvals=rawd[,pvalscolumn],title=mytitle,grey=grey)
176         ggsave(filename=paste(myfname,"manhattan.png",sep='_'),mymanplot,width=8,height=6,dpi=96)
177         ggsave(filename=paste(myfname,"manhattan.pdf",sep='_'),mymanplot,width=8,height=6,dpi=96)
178         print(paste('## manhattan plot on',cname,'done'))
179         }
180         else {
181              print(paste('chrom column =',chromcolumn,'offset column = ',offsetcolumn,
182              'so no Manhattan plot - supply both chromosome and offset as numerics for Manhattan plots if required'))
183              } 
184     } 
185  else {
186        print(paste('pvalue column =',pvalscolumn,'Cannot parse it so no plots possible'))
187      }
188  } # for pvalscolumn
189 } else { print('## Problem - no values available to plot - was there really a chromosome and offset column?') }
190}
191
192rgqqMan() 
193# execute with defaults as substituted
194
195#R script autogenerated by rgenetics/rgutils.py on 04/08/2011 11:46:16