Nothing
#' Volcano-Plot (Statistical Test Outcome Versus Relative Change)
#'
#' This type of plot is very common in high-throughput biology, see \href{https://en.wikipedia.org/wiki/Volcano_plot_(statistics)}{Volcano-plot}.
#' Basically, Volcano-Plots allows comparing the outcome of a statistical test to the relative change (ie log fold-change, M-value).
#' This version of Volcano-plots supports conveniently results from packages \href{https://CRAN.R-project.org/package=wrMisc}{wrMisc} and \href{https://CRAN.R-project.org/package=wrProteo}{wrProteo}.
#'
#' @details
#' In high-throughput biology data are typically already transformed to log2 and thus, the 'M'-values (obtained by subtracting two group means, 'Minus') represent a relative change (ie fold-change).
#' Output from statistical testing by \code{\link[wrMisc]{moderTestXgrp}} or from package \href{https://CRAN.R-project.org/package=wrProteo}{wrProteo} can be directly read to produce Volcano plots.
#' Please note, that plotting a very high number of points (eg >3000) in transparency may take several seconds.
#'
#' Thresholds for the statistical testing can be set using \code{FdrThrs} which will be using FDR-values (or lfdr-values) from MArrayLM-objects or externaly provided \code{FdrList}
#' Besides, typically thresholds are set on the M-values, too. Here the threshold from argulent \code{FCthrs} will be used. Please note that M-value threshold should be given as _linear scale_,
#' ie \code{FCthrs=1.5} will be shown on the log2-axes at 0.58.
#'
#' Using the argument \code{plotAsFdr} FDR value will be used for plotting instead of p-values. Since selection of 'significant' hits is usually done based on FDR-values, it makes sense to plot them directly instead of inityial p-values.
#' However, FDR values are not fully linear to initial p-values and plateau-phenomena may occur frequently.
#' Thus, resulting plots may appear less spread, so finally drawing p-values (but cutting based on FDR-thersholds) many sometimes result in nicer plots.
#'
#' The argument \code{returnData=TRUE} allows exporting directly all data shown on the plot, plus group-means (if available) filtering-status (if available) and symbol used on figure.
#'
#' @param Mvalue (MArrayLM-object, numeric or matrix) data to plot; M-values are typically calculated as difference of log2-abundance values and 'pValue' the mean of log2-abundance values;
#' M-values and p-values may be given as 2 columsn of a matrix, in this case the argument \code{pValue} should remain NULL.
#' One may also furnish MArrayLM-objects created by packages wrProteo (CRAN) or limma (Bioconductor).
#' @param pValue (numeric, list or data.frame) if \code{NULL} it is assumed that 2nd column of 'Mvalue' contains the p-values to be used
#' @param useComp (integer, length=1) choice of which of multiple comparisons to present in \code{Mvalue} (if generated using \code{moderTestXgrp()})
#' @param filtFin (matrix or logical) The data may get filtered before plotting: If \code{FALSE} no filtering will get applied; if matrix of \code{TRUE}/\code{FALSE} it will be used as optional custom filter, otherwise (if \code{Mvalue} if an \code{MArrayLM}-object eg from limma) a default filtering based on the \code{filtFin} element will be applied
#' @param tit (character) custom title (has priority over \code{ProjNa})
#' @param ProjNa (character) will be added to automatic title (if custom title \code{tit} was not specified)
#' @param FCthrs (numeric) Fold-Change threshold (display as line) give as Fold-change and NOT log2(FC), default at 1.5, set to \code{NA} for omitting
#' @param FdrList (numeric) FDR data (only used when no \code{Mvalue} is not list or MArray-LMobject)
#' @param FdrThrs (numeric) FDR threshold (display as line), default at 0.05, set to \code{NA} for omitting
#' @param FdrType (character) FDR-type to extract if \code{Mvalue} is 'MArrayLM'-object (eg produced by from \code{moderTest2grp} etc);
#' if \code{NULL} it will search for suitable fields/values in this order : 'FDR','BH','lfdr' and 'BY'
#' @param plotAsFdr (logical) rather plot using FDR-values (if available) instead of p-Values
#' @param subTxt (character) custom sub-title
#' @param grayIncrem (logical) if \code{TRUE}, display overlay of points (not exceeding thresholds) as increased shades of gray
#' @param col (character) custom color(s) for points of plot (see also \code{\link[graphics]{par}})
#' @param pch (integer) type of symbol(s) to plot (default=16) (see also \code{\link[graphics]{par}})
#' @param compNa (character) names of groups compared
#' @param batchFig (logical) if \code{TRUE} figure title and axes legends will be kept shorter for display on fewer splace
#' @param cexMa (numeric) font-size of title, as expansion factor (see also \code{cex} in \code{\link[graphics]{par}})
#' @param cexLa (numeric) size of axis-labels, as expansion factor (see also \code{cex} in \code{\link[graphics]{par}})
#' @param cexPt (numeric) size of points, as expansion factor (see also \code{cex} in \code{\link[graphics]{par}})
#' @param cexSub (numeric) size of subtitle, as expansion factor (see also \code{cex} in \code{\link[graphics]{par}})
#' @param cexTxLab (numeric) size of text-labels for points, as expansion factor (see also \code{cex} in \code{\link[graphics]{par}})
#' @param limM (numeric, length=2) range of axis M-values
#' @param limp (numeric, length=2) range of axis FDR / p-values
#' @param annotColumn (character) column names of annotation to be extracted (only if \code{Mvalue} is \code{MArrayLM}-object containing matrix $annot).
#' The first entry (typically 'SpecType') is used for different symbols in figure, the second (typically 'GeneName') is used as prefered text for annotating the best points (if \code{namesNBest} allows to do so.)
#' @param annColor (character or integer) colors for specific groups of annotation (only if \code{Mvalue} is \code{MArrayLM}-object containing matrix $annot)
#' @param expFCarrow (logical, character or numeric) optional adding arrow for expected fold-change; if \code{TRUE} the expected ratio will be extracted from numeric concentration-indications from sample-names
#' if \code{numeric} an arrow will be drawn (M-value as 1st position, color of 2nd position of vector).
#' @param namesNBest (integer or character) for display of labels to points in figure :
#' if \code{namesNBest='pass'}, 'passThr' or 'signif' all points passing thresholds will get labels;
#' if \code{namesNBest=5} this number of best points will get labels;
#' if \code{namesNBest="5 each"} the best n of significant points on each side will get labels;
#' if the initial object \code{Mvalue} contains a list-element called 'annot' the second value of argument \code{annotColumn} will be used (of available in 'annot') as text
#' @param NbestCol (character or integer) colors for text-labels of best points, also used for arrow
#' @param colBySpecType (logical) incase arument \code{Mvalue} is MArrayLM-object it is possible to use different color-codes for points passing thresholds based on Mvalue$annot[,"SpecType"]; use this with multi-species benchmark tests
#' @param sortLeg (character) sorting of 'SpecType' annotation either ascending ('ascend') or descending ('descend'), no sorting if \code{NULL}
#' @param NaSpecTypeAsContam (logical) consider lines/proteins with \code{NA} in Mvalue$annot[,"SpecType"] as contaminants (if a 'SpecType' for contaminants already exits)
#' @param useMar (numeric, length=4) custom margings (see also \code{\link[graphics]{par}})
#' @param returnData (logical) optional returning data.frame with (ID, Mvalue, pValue, FDRvalue, passFilt)
#' @param silent (logical) suppress messages
#' @param callFrom (character) allows easier tracking of messages produced
#' @param debug (logical) additional messages for debugging
#' @return This function simply plots an MA-plot (to the current graphical device), if \code{returnData=TRUE} an optional data.frame with (ID, Mvalue, pValue, FDRvalue, passFilt) can be returned
#' @seealso (for PCA) \code{\link{plotPCAw}})
#' @examples
#' library(wrMisc)
#' set.seed(2005); mat <- matrix(round(runif(900),2), ncol=9)
#' rownames(mat) <- paste0(rep(letters[1:25], each=4), rep(letters[2:26],4))
#' mat[1:50,4:6] <- mat[1:50,4:6] + rep(c(-1,1)*0.1,25)
#' mat[3:7,4:9] <- mat[3:7,4:9] + 0.9
#' mat[11:15,1:6] <- mat[11:15,1:6] - 0.7
#' ## assume 2 groups with 3 samples each
#' gr3 <- gl(3, 3, labels=c("C","A","B"))
#' tRes2 <- moderTest2grp(mat[,1:6], gl(2,3), addResults = c("FDR","means"))
#' # Note: due to the small number of lines only FDR chosen to calculate
#' VolcanoPlotW(tRes2)
#' ## Add names of points passing custom filters
#' VolcanoPlotW(tRes2, FCth=1.3, FdrThrs=0.2, namesNBest="passThr")
#' VolcanoPlotW(tRes2, FCth=1.3, FdrThrs=0.2, namesNBest=3)
#' VolcanoPlotW(tRes2, FCth=1.3, FdrThrs=0.2, namesNBest="2 each side")
#'
#' ## assume 3 groups with 3 samples each
#' tRes <- moderTestXgrp(mat, gr3, useComparison="all", addResults = c("FDR","means"))
#' # Note: due to the small number of lines only FDR chosen to calculate
#' VolcanoPlotW(tRes)
#' VolcanoPlotW(tRes, FCth=1.3, FdrThrs=0.2)
#' VolcanoPlotW(tRes, FCth=1.3, FdrThrs=0.2, useComp=2)
#'
#' @export
VolcanoPlotW <- function(Mvalue, pValue=NULL, useComp=1, filtFin=NULL, tit=NULL, ProjNa=NULL, FCthrs=NULL, FdrList=NULL, FdrThrs=NULL, FdrType=NULL, plotAsFdr=FALSE,
subTxt=NULL, grayIncrem=TRUE, col=NULL, pch=16, compNa=NULL, batchFig=FALSE, cexMa=1.8, cexPt=NULL, cexLa=1.1, cexSub=NULL, cexTxLab=0.7, limM=NULL, limp=NULL,
annotColumn=c("SpecType","GeneName","EntryName","Accession","Species","Contam"), annColor=NULL, expFCarrow=FALSE,
namesNBest=NULL, NbestCol=1, colBySpecType=FALSE, sortLeg="descend", NaSpecTypeAsContam=TRUE, useMar=c(6.2,4,4,2), returnData=FALSE, callFrom=NULL, silent=FALSE, debug=FALSE) {
## Volcano-Plot plot
## optional arguments for explicit title in batch-mode
fxNa <- wrMisc::.composeCallName(callFrom, newNa="VolcanoPlotW")
opar <- graphics::par(no.readonly=TRUE)
## during function changes in $mar,$cex.main,$cex.lab,$las
opar2 <- opar[-which(names(opar) %in% c("fig","fin","font","mfcol","mfg","mfrow","oma","omd","omi"))] #
on.exit(graphics::par(opar2)) # progression ok
if(isTRUE(debug)) silent <- FALSE else debug <- FALSE
if(!isTRUE(silent)) silent <- FALSE
# message("++1++ length tit",length(tit)," : ",tit)
namesIn <- c(deparse(substitute(Mvalue)), deparse(substitute(pValue)), deparse(substitute(filtFin)))
basRGB <- c(0.3, 0.3, 0.3) # grey
fcRGB <- c(1, 0, 0) # red for points passing FC filt line
datOK <- inversedComp <- singleCompSetup <- FALSE # inversedComp: if useComp is given as text it may be inverse of p-values given; singleCompSetup : cases sof single comparison BUT 2 cols of p.values
splNa <- ptType <- colPass <- ptBg <- grpMeans <- pcol <- pwComb <- pwNames <- FDRvalue <- FdrList <- FDRty <- useCompNa <- useL2 <- proNa <- NULL # initialize
annot <- NULL # used ??
if(length(pch) ==0) pch <- 16
if(debug) message(fxNa,"Length Mvalue ",length(Mvalue)," ; length pValue ",length(pValue)," ; useComp ",useComp)
if(identical(col,"FDR")) { FDR4color <- TRUE; col <- NULL} else FDR4color <- FALSE
if(length(FCthrs) <1) { FCthrs <- 1.5 ; if(debug) message(fxNa,"Setting FCthrs to default =1.5")}
if(length(FdrThrs) <1) { FdrThrs <- 0.05 ; if(debug) message(fxNa,"Setting FdrThrs to default =0.05")}
if(length(Mvalue) ==0) message(fxNa,"Nothing to do, 'Mvalue' seems to be empty !") else {
if(("MArrayLM" %in% class(Mvalue) || "list" %in% class(Mvalue)) && length(Mvalue$setup) !=0) setup <- Mvalue$setup else setup <- NULL } ## data seem valid to make VolcanoPlot
if(length(FdrType)==0 || !(FdrType %in% names(Mvalue))) {
chFdrTy <- c("BH","lfdr","BY","Bonferroni")
chFdrTy2 <- chFdrTy %in% names(Mvalue)
if(any(chFdrTy2)) FdrType <- chFdrTy[which(chFdrTy2)[1]]
} # otherwise let wrMisc::volcanoFilter look for suitable list-elemens & columns
merg <- try(wrMisc::volcanoFilter(Mvalue=Mvalue, pValue=pValue, useComp=useComp, filtFin=filtFin,
FCthrs=log2(abs(FCthrs)), FdrList=FdrList, FdrThrs=FdrThrs, FdrType=FdrType, signifOnly=FALSE, annotColumn= annotColumn, silent=!debug, debug=debug, callFrom=fxNa), silent=TRUE)
# Mvalue, pValue=NULL, useComp=1, filtFin=NULL, FCthrs=NULL, FdrList=NULL, FdrThrs=NULL, FdrType=NULL, signifOnly=TRUE, silent=FALSE, debug=FALSE, callFrom=NULL
#if(length(filtFin)==0) filtFin <- merg[,"filtFin"]
if(inherits(merg, "try-error") ) { datOK <- FALSE
warning(fxNa,"Incompatible input: Unable to extract columns for Volcano-Plot via wrMisc::volcanoFilter(), returning NULL")
} else datOK <- length(merg) !=0 && nrow(merg) >1
datOK <- !inherits(merg, "try-error") && length(merg) !=0 && nrow(merg) >1
if(debug) {message(fxNa,"VPW11"); VPW11 <- list(merg=merg,Mvalue=Mvalue,pValue=pValue, datOK=datOK,filtFin=filtFin,FdrType=FdrType,FdrThrs=FdrThrs,FCthrs=FCthrs, pch=pch,ptType=ptType,cexSub=cexSub,setup=setup,usePcol=usePcol,tit=tit)}
if(datOK) {
if(!"FDRvalue" %in% colnames(merg)) plotAsFdr <- FALSE
if(length(FdrType)==0) FdrType <- "FDR"
usePcol <- if(plotAsFdr) "FDRvalue" else "pValue" # switch between using (uncorrected) pValues and FDR
## sort merg, so that legend always gets constructed the same order, ascending ('ascend') or descending ('descend')
sortLeg <- if(identical(sortLeg,"ascend")) FALSE else {if(identical(sortLeg,"descend")) TRUE else NULL}
## sort according to SpecType - if present
if(length(annotColumn) !=0 && length(sortLeg) ==1 && annotColumn[1] %in% colnames(merg)) merg <- merg[order(merg[,annotColumn[1]], decreasing=sortLeg),]
## update ..
nIDco <- sum(c("ID","nredID","uniqID") %in% colnames(merg)) # number of heading columns in 'merg'
if(debug) {message(fxNa,"VPW11b"); VPW11b <- list(merg=merg,Mvalue=Mvalue,pValue=pValue, datOK=datOK,filtFin=filtFin,FdrType=FdrType,FdrThrs=FdrThrs,FCthrs=FCthrs, pch=pch,ptType=ptType,cexSub=cexSub,setup=setup,usePcol=usePcol,sortLeg=sortLeg,nIDco=nIDco,annotColumn=annotColumn)}
pch <- if("pch" %in% colnames(merg)) merg[,"pch"] else rep(pch, nrow(merg)) # update
ptType <- if(annotColumn[1] %in% colnames(merg)) merg[,annotColumn[1]] else rep(1, nrow(merg)) # update "SpecType"
# message(fxNa,"++ useComp ",useComp," VPW12a"); VPW12a <- list(useComp=useComp)
if(debug) {message(fxNa,"VPW12"); VPW12 <- list(merg=merg,Mvalue=Mvalue,pValue=pValue, datOK=datOK,filtFin=filtFin,FdrType=FdrType,FdrThrs=FdrThrs,FCthrs=FCthrs, pch=pch,ptType=ptType,cexSub=cexSub,setup=setup,usePcol=usePcol,sortLeg=sortLeg,nIDco=nIDco,annotColumn=annotColumn,tit=tit)}
## prepare for plotting
if(is.null(cexSub)) cexSub <- cexLa +0.05
xLab <- "M-value (log2 fold-change)"
tit1 <- if(length(tit)==1 && nchar(tit) !=0) tit else paste( if(batchFig) paste(ProjNa, ": ") else "Volcano-Plot",
if(length(setup) !=0) rownames(setup$pwGrpNa)[useComp] )
message(fxNa,"VPW12b7")
if(debug) {message(fxNa,"VPW12c"); VPW12c <- list(merg=merg,FdrList=FdrList,Mvalue=Mvalue,FdrType=FdrType,FDRvalue=FDRvalue,plotAsFdr=plotAsFdr,pValue=pValue,useComp=useComp,grpMeans=grpMeans, col=col,annotColumn=annotColumn,annot=annot, pch=pch,sortLeg=sortLeg,batchFig=batchFig,FCthrs=FCthrs,FdrThrs=FdrThrs,setup=setup,usePcol=usePcol)}
if("retain" %in% colnames(merg)) {
passAll <- as.logical(merg[,"retain"])
} else {
passAll <- merg[,"FDRvalue"] <= FdrThrs & abs(log10(merg[,"Mvalue"])) >= FCthrs # may merg contain other colnames ?
if("filtFin" %in% colnames(merg)) passAll <- passAll & merg[,"filtFin"]
}
if(debug) {message(fxNa,"VPW12d"); VPW12d <- list(merg=merg,FdrList=FdrList,Mvalue=Mvalue,FdrType=FdrType,FDRvalue=FDRvalue,plotAsFdr=plotAsFdr,pValue=pValue,useComp=useComp,grpMeans=grpMeans, col=col,annotColumn=annotColumn,annot=annot,passAll=passAll, pch=pch,sortLeg=sortLeg,batchFig=batchFig,FCthrs=FCthrs,FdrThrs=FdrThrs,setup=setup)}
# message("++ length tit ",length(tit)," : ",tit)
chNA <- is.na(passAll) # passFdr may contain NAs ? => set to FALSE
if(any(chNA)) { passAll[which(chNA)] <- FALSE; if(debug) message(fxNa,"Note : filtering contained ",sum(chNA)," NAs !!")}
if(debug) {message(fxNa," combined passing : ",sum(passAll)," VPW13"); VPW13 <- list(merg=merg,Mvalue=Mvalue,passAll=passAll,col=col,passAll=passAll,cexPt=cexPt,annotColumn=annotColumn,annColor=annColor,grayIncrem=grayIncrem,setup=setup)}
## color for points passing filter
if(length(col) >0 && length(col) != nrow(merg)) { col <- NULL
if(!silent) message(fxNa,"Invalid entry for 'col', should be of length=",nrow(merg),", resetting to default")}
if(length(col) ==0) { # default colors in useCol
alph <- sort(c(0.14, round(0.6/log10(nrow(merg)),2), 0.8))[2] # alph <- round(12/sqrt(nrow(eBayesLst$pValue)),2)
alph2 <- sort(c(round(7/(5 +sum(passAll)^0.7),2), alph,0.9))[2] # for points passing thresholds
useCol <- if(grayIncrem) grDevices::rgb(0.35,0.35,0.35,alph) else grDevices::rgb(0.7,0.7,0.7) # basic color (grey)
cexPt <- if(length(cexPt) == 1 && is.na(cexPt) && is.finite(cexPt)) cexPt else sort(c(round(0.75 + 70/(1 +2*sum(as.logical(merg[,"filtFin"]), na.rm=TRUE)), 2), 0.65,1.9))[2]
chCol <-if(annotColumn[1] %in% colnames(merg)) unique(merg[, annotColumn[1]]) else FALSE # check how many different colors may be needed
#message("++ sum(filtFin)",sum(filtFin)," cexPt ",cexPt)
chNaC <- is.na(chCol)
if(any(chNaC)) chCol[which(chNaC)] <- "NA"
if(length(annColor) >0) {colPass <- annColor} else {
if(length(chCol) >4) {
colPass <- cbind(red=c(141,72,90,171, 220,253,244,255), green=c(129,153,194,221, 216,174,109,0), blue=c(194,203,185,164, 83,97,67,0))
colPass <- grDevices::rgb(red=colPass[,1], green=colPass[,2], blue=colPass[,3], alph2, maxColorValue=255)
if(length(chCol) >8) { colPass <- c(colPass, rep(colPass[8], length(chCol) -8))
if(!silent) message(fxNa," > 8 different groups found, using 8th color after 7th group")}
} else colPass <- grDevices::rgb(c(0.95,0.2,0,0.75), c(0.15,0.2,0.9,0.35), c(0.15,0.95,0,0.8), alph2)} # red, blue, green, purple (luminosity adjusted)
useCol <- rep(useCol[1], nrow(merg)) # fuse basic gray to colors for different types
## integrate names of annColor as order of colPass
if(length(names(annColor)) >0) {
uniTy <- unique(merg[which(passAll), annotColumn[1]])
colPass <- colPass[match(names(annColor), uniTy)]
}
if(debug) {message(fxNa,"VPW13a"); VPW13a <- list(useCol=useCol,colPass=colPass, merg=merg,Mvalue=Mvalue,col=col,passAll=passAll,cexPt=cexPt,annotColumn=annotColumn,annColor=annColor,usePcol=usePcol)}
## assign color for those passing (re-written 2jun26)
if(any(passAll, na.rm=TRUE)) {
useCol[which(passAll)] <- if(annotColumn[1] %in% colnames(merg)) {
colPass[if(length(unique(merg[which(passAll),annotColumn[1]])) >1) wrMisc::levIndex(merg[which(passAll),annotColumn[1]], silent=silent,debug=debug, callFrom=fxNa) else rep(1,sum(passAll))]
} else colPass[1] # assign colors for those passing
}
} else useCol <- col
if(debug) {message(fxNa,"VPW13b"); VPW13b <- list(merg=merg,Mvalue=Mvalue,pValue=pValue,col=col,passAll=passAll,cexPt=cexPt,annotColumn=annotColumn,annColor=annColor,pch=pch,useCol=useCol)}
## adjust fill color for open symbols
chPch <- pch %in% c(21:25)
if(any(chPch, na.rm=TRUE)) { ptBg <- useCol
ptBg[which(chPch)] <- useCol[which(chPch)] # background color for filled symbols
useCol[which(chPch)] <- 1 # contour as black
}
}
if(datOK) {
## main graphics
pl1 <- try(graphics::par(mar=if(length(useMar)==4) useMar else c(6.5,4,4,2), cex.main=cexMa, las=1), silent=TRUE)
if(inherits(pl1, "try-error")) {Mvalue <- NULL; message("UNABLE TO SET PLOT MARGINS !! check plotting device ...")}
if(debug) {message(fxNa,"VPW14a"); VPW14a <- list(pl1=pl1,merg=merg,Mvalue=Mvalue,pValue=pValue,useMar=useMar,FCthrs=FCthrs,FdrThrs=FdrThrs,FdrType=FdrType,plotAsFdr=plotAsFdr, pch=pch,cexPt=cexPt,cexMa=cexMa,limM=limM,limp=limp,ptBg=ptBg,tit1=tit1)}
#check# plot(pValue ~Mvalue, data=VPW14a$merg)
pl1 <- try(graphics::plot(merg[,"Mvalue"], -1*log10( merg[,usePcol]), pch=pch, cex=cexPt, main=tit1,
ylab=if(plotAsFdr) paste("- log10",if(is.null(FdrType)) " FDR" else paste0(FdrType, if(nchar(FdrType) <4) "-FDR")) else "- log10 p-value (uncorrected)", col=useCol, xlab=xLab, cex.lab=cexLa, xlim=limM,ylim=limp, pt.bg=ptBg), silent=TRUE)
if(inherits(pl1, "try-error")) {Mvalue <- NULL; message("UNABLE TO PLOT !! check plotting device ..."); datOK <- FALSE} }
if(debug) {message(fxNa,"VPW14b"); VPW14b <- list(merg=merg,Mvalue=Mvalue,pValue=pValue,passAll=passAll,useMar=useMar,FCthrs=FCthrs,FdrThrs=FdrThrs,useCol=useCol,useComp=useComp,useCompNa=useCompNa,subTxt=subTxt,plotAsFdr=plotAsFdr,setup=setup, pch=pch,col=col,usePcol=usePcol )}
if(datOK) { # useCompNa if(length(Mvalue) >0)
sTxt <- if(length(subTxt) ==1) subTxt else { if(!singleCompSetup) if(length(names(useComp)) >0) paste0(names(useComp),"; ",collapse="") else paste0(if(inversedComp) "inv.","comp=",useComp,"; ")}
sTxt <- paste0(sTxt,"n=",if("filtFin" %in% colnames(merg)) sum(merg[,"filtFin"]) else nrow(merg),
if(!all(is.na(c(FCthrs,FdrThrs)))) paste(";",sum(passAll, na.rm=TRUE),"(color) points passing",
if(!is.na(FCthrs)) paste0("(FCthr>", as.character(FCthrs),", ie as log2>",round(log2(FCthrs), 2),", ") else " (", paste0("FdrThrs<",as.character(FdrThrs),")")))
if(!singleCompSetup && "pwGrpNa" %in% names(setup) && length(dim(setup$pwGrpNa))==2) { sTxt <- paste(rownames(setup$pwGrpNa)[useComp],";", sTxt) }
if(debug) {message(fxNa,"VPW14c"); VPW14c <- list(merg=merg,Mvalue=Mvalue,pValue=pValue,passAll=passAll,useMar=useMar,FCthrs=FCthrs,FdrThrs=FdrThrs,useCol=useCol,useComp=useComp,useCompNa=useCompNa,subTxt=subTxt,sTxt=sTxt,plotAsFdr=plotAsFdr,setup=setup, pch=pch,col=col,alph=alph,alph2=alph2,cexPt=cexPt,usePcol=usePcol )}
graphics::mtext(sTxt, cex=0.75, line=0.2)
if(!all(is.na(c(FCthrs,FdrThrs)))) {
if(debug) message(fxNa," n=",if("filtFin" %in% colnames(merg)) sum(merg[,"filtFin"]) else nrow(merg)," FCthrs=",as.character(FCthrs)," filt.ini=", sum(merg[,"filtFin"], na.rm=TRUE),
" passAll=",sum(passAll,na.rm=TRUE)," ; range Mva ",wrMisc::pasteC(signif(range(merg[,"Mvalue"],na.rm=TRUE),3))," ; alph=",alph," cexPt=",cexPt," alph2=",alph2)
## previous versions : adjusted abline by adding diff(graphics::par("usr")[1:2])/1000)
graphics::abline(v=c(-1,1)* log2(FCthrs) , col=grDevices::rgb(0.87,0.72,0.72), lty=2) } # threshold line for FC
if(debug) {message(fxNa,"VPW15"); VPW15 <- list(merg=merg,Mvalue=Mvalue,filtFin=filtFin,FCthrs=FCthrs,FdrThrs=FdrThrs,annotColumn=annotColumn,xLab=xLab,tit1=tit1,col=col,useCol=useCol,assAll=passAll,grayIncrem=grayIncrem,cexPt=cexPt,annColor=annColor,plotAsFdr=plotAsFdr,limM=limM,limp=limp,ptBg=ptBg,cexLa=cexLa,passAll=passAll,namesNBest=namesNBest)}
passFdr <- sum(merg[,"FDRvalue"] <= FdrThrs, na.rm=TRUE)
if(passFdr !=0) {
# graphics::mtext("Note, that in some special cases FDR and p-value may not correlate perfectly, thus points may appear at good p-value but finally don't get retained",line=5,cex=0.65, side=1)
if(plotAsFdr) {
shiftFa <- diff(graphics::par("usr")[3:4])/150
if(any(passAll, na.rm=TRUE)) graphics::abline(h=-1*log10(max(merg[which(passAll), usePcol], na.rm=TRUE)) -shiftFa, col=grDevices::rgb(0.87,0.72,0.72), lty=2) # threshold line for FDR/p.value
} else {
pRa <- range(merg[which(passAll), usePcol], na.rm=TRUE)
shiftFa <- diff(graphics::par("usr")[3:4])/90
graphics::abline(h=-1*log10(pRa[2]) -shiftFa, col=grDevices::rgb(0.87,0.72,0.72), lty=2) }}
if(debug) {message(fxNa,"VPW15b"); VPW15b <- list(merg=merg,Mvalue=Mvalue,filtFin=filtFin,FCthrs=FCthrs,FdrThrs=FdrThrs,passFdr=passFdr,annotColumn=annotColumn,xLab=xLab,tit1=tit1,col=col,useCol=useCol,assAll=passAll,grayIncrem=grayIncrem,cexPt=cexPt,annColor=annColor,plotAsFdr=plotAsFdr,limM=limM,limp=limp,ptBg=ptBg,cexLa=cexLa,passAll=passAll,namesNBest=namesNBest,pRa=pRa,shiftFa=shiftFa )}
## add names to best points : get names to use (proNa, in order of merg)
namesNBestIni <- namesNBest
chAnnCo <- colnames(merg) %in% annotColumn
if(any(chAnnCo)) { # look for names in annot
ch2 <- colnames(merg) %in% annotColumn[2]
proNa <- merg[ , which(if(any(ch2)) ch2 else chAnnCo)[1]] # normally get 2nd annotColumn, ie 'Description'
} else {
useAnnCol <- colnames(merg) %in% annotColumn
if(any(useAnnCol)) {if(annotColumn[2] %in% colnames(merg)) merg[,annotColumn[2]] else merg[,which(useAnnCol)[1]] }
proNa <- if(any(useAnnCol)) {if(annotColumn[2] %in% colnames(merg)) merg[,annotColumn[2]] else merg[,which(useAnnCol)[1]] } else rownames(merg)
}
## add names to best points : transform namesNBest to integer (sum of names to display)
if(identical(namesNBest, 0) || identical(namesNBest, "") || sum(passAll, na.rm=TRUE)==0) namesNBest <- NULL
if(debug) {message(fxNa,"VPW15c"); VPW15c <- list(merg=merg,Mvalue=Mvalue,filtFin=filtFin,FCthrs=FCthrs,FdrThrs=FdrThrs,passFdr=passFdr,annotColumn=annotColumn,xLab=xLab,tit1=tit1,col=col,useCol=useCol,assAll=passAll,grayIncrem=grayIncrem,cexPt=cexPt,annColor=annColor,plotAsFdr=plotAsFdr,limM=limM,limp=limp,ptBg=ptBg,cexLa=cexLa,passAll=passAll,
namesNBest=namesNBest,pRa=pRa,shiftFa=shiftFa,proNa=proNa,namesNBestIni=namesNBestIni,usePcol=usePcol )}
if(length(namesNBest) ==1) {
if(grepl("each( *side){0,1}$", namesNBestIni)) {
## special case of eg '8 each'
namesNBest <- try(abs(as.integer(sub("each( *side){0,1}$","", namesNBestIni))))
if(inherits(namesNBest, "try-error")) {
warning(fxNa,"Unable to understand content of argument 'namesNBest', ignoring...")
} else {
if(namesNBestIni != 0) {
## determine useL2 for each side
limN <- sort(merg[which(passAll & merg[,"Mvalue"] <0), usePcol])[1:namesNBest]
useL2n <- if(all(is.na(limN))) NULL else which(passAll & merg[,"Mvalue"] <0 & merg[,usePcol] <= max(limN, na.rm=TRUE))
limP <- sort(merg[which(passAll & merg[,"Mvalue"] >0), usePcol])[1:namesNBest]
useL2p <- if(all(is.na(limP))) NULL else which(passAll & merg[,"Mvalue"] >0 & merg[,usePcol] <= max(limP, na.rm=TRUE))
useL2 <- sort(c(useL2n, useL2p)) # combine (index rel to merge)
if(debug) {message("++ VPW15d")}
}
}
} else {
## recognize word-terms, otherwise try converting to digit
if(namesNBestIni %in% c("pass","passThr","passFDR","signif","significant","All significant","all significant","all signif")) namesNBest <- sum(passAll) else {
namesNBest <- try(abs(as.integer(namesNBestIni)), silent=TRUE)
if(inherits(namesNBest, "try-error")) { namesNBest <- NULL
message(fxNa,"Unable to understand argument 'namesNBest', must be integer or 'pass','passThr','passFDR' or 'signif' (for display of labels to points in figure)") }
if(length(namesNBest) !=0 && any(!is.finite(namesNBest))) namesNBest <- NULL
}
if(debug) {message(fxNa,"VPW15d"); VPW15d <- list(merg=merg,Mvalue=Mvalue,filtFin=filtFin,FCthrs=FCthrs,FdrThrs=FdrThrs,passFdr=passFdr,annotColumn=annotColumn,xLab=xLab,tit1=tit1,col=col,useCol=useCol,assAll=passAll,grayIncrem=grayIncrem,cexPt=cexPt,annColor=annColor,plotAsFdr=plotAsFdr,limM=limM,limp=limp,ptBg=ptBg,cexLa=cexLa,passAll=passAll,namesNBest=namesNBest,pRa=pRa,shiftFa=shiftFa,namesNBest=namesNBest,proNa=proNa,namesNBestIni=namesNBestIni )}
if(length(namesNBest) ==1 && namesNBest !=0 && sum(passAll, na.rm=TRUE)) useL2 <- which(passAll)[order(merg[which(passAll), usePcol], decreasing=FALSE)[1:namesNBest]] # index rel to merge
}
if(debug) {message(fxNa,"VPW16"); VPW16 <- list(pch=pch,passAll=passAll,merg=merg,annotColumn=annotColumn,plotAsFdr=plotAsFdr,namesNBest=namesNBest,NbestCol=NbestCol,cexTxLab=cexTxLab,useL2=useL2,proNa=proNa)}
#check#plot(merg[,"Mvalue"], -1*log10( merg[,usePcol]))
if(length(useL2) !=0) {
displTx <- proNa[useL2]
chNA <- is.na(displTx)
if(any(chNA)) {
displTx[which(chNA)] <- "NA" # set misssing names to have "NA" printed in final plot
if(!silent) message(fxNa, sum(chNA), " missing names displayed as 'NA'")
}
## add text-labels to points
xOffs <- signif(diff(graphics::par("usr")[1:2])/170, 3)
yOffs <- signif(diff(graphics::par("usr")[3:4])/90, 3)
datSig <- -1*log10(merg[useL2, usePcol])
txCoor <- cbind(x=merg[,"Mvalue"][useL2] +xOffs, y=yOffs + datSig)
graphics::text(txCoor[,1], txCoor[,2], displTx, cex=cexTxLab, col=NbestCol, adj=0)
}
}
if(debug) {message(fxNa,"VPW17"); VPW17 <- list(pch=pch,passAll=passAll,merg=merg,annot=annot,annotColumn=annotColumn,plotAsFdr=plotAsFdr)}
## legend (if multiple symbols)
pch[which(is.na(pch))] <- -2
ch1 <- unique(pch)
if(length(ch1) >1 && sum(passAll) >0) {
legInd <- which(!duplicated(merg[which(passAll), annotColumn[1]], fromLast=FALSE))
if(length(legInd) <1 && !silent) message(fxNa,"Trouble ahead : Can't find non-duplicated ",annotColumn[1]," for ",sum(passAll)," points passing thresholds ! (ie as 'legInd')")
legPch <- pch[which(passAll)[legInd]]
legCol <- useCol[which(passAll)[legInd]]
legBg <- ptBg[which(passAll)[legInd]]
if(alph2 <1) {legCol <- substr(legCol,1,7); legBg <- substr(legBg,1,7)} # reset to no transparency
legLab <- merg[which(passAll)[legInd], annotColumn[1]]
chNa <- is.na(legLab)
if(any(chNa)) legLab[chNa] <- "NA"
legOr <- if(length(legLab) >1) order(legLab) else 1 # not used so far
legLoc <- checkForLegLoc(cbind(merg[,"Mvalue"], pValue), sampleGrp=legLab, showLegend=FALSE)
legCex <- stats::median(c(cexPt, cexTxLab, 1.2), na.rm=TRUE)
if(length(legLab) >0) { chLeg <- try(graphics::legend(legLoc$loc, legend=legLab, col=legCol, text.col=1, pch=legPch,
if(length(ptBg) >0) pt.bg=ptBg, cex=legCex, pt.cex=1.2*legCex, xjust=0.5, yjust=0.5), silent=TRUE) # as points
if(inherits(chLeg, "try-error") && !silent) message(fxNa,"Note: Failed to add legend .. ",chLeg) }
} else legCol <- NULL
if(debug) {message(fxNa,"VPW18")}
## arrow for expected ratio
## how to extract in smartest way ??
drawArrow <- if(length(expFCarrow) >0) {isTRUE(as.logical(expFCarrow[1])) || grepl("^[[:digit:]]+$", expFCarrow[1])} else FALSE
if(drawArrow) {
regStr <-"[[:space:]]*[[:alpha:]]+[[:punct:]]*[[:alpha:]]*"
if(isTRUE(expFCarrow)) {
## automatic extraction of FC
if(debug) message(fxNa," .. ",names(useComp)," -> ",paste(unlist(strsplit(names(useComp), "-")), collapse=" "),"\n")
expM <- sub(paste0("^",regStr),"", sub(paste0(regStr,"$"), "", unlist(strsplit(names(useComp), "-")))) # assume '-' separator from pairwise comparison
arrCol <- 1
chN2 <- try(as.numeric(expM), silent=TRUE)
if(inherits(chN2, "try-error")) { drawArrow <- FALSE #expM <- arrCol <- NA
} else {
expM <- log2(chN2[2] / chN2[1]); arrCol <- 1 # transform automatic extracted to ratio # expFCarrow <- c(expM, 1)
}
msg <- "Argument 'expFCarrow' was set to TRUE; "
if(!silent) message(fxNa, msg, if(drawArrow) "Extract concentration values of group-names for calculating ratios" else "Failed automatic extraction of FC-values (possibly no numeric values in setup)")
} else {
expM <- try(as.numeric(expFCarrow[1]), silent=TRUE)
if(inherits(expM, "try-error")) {
if(!silent) message(fxNa,"Argument 'expFCarrow' was given, but no numeric content in 1st place found, can't draw FC-arrow") #understand 1st value of'expFCarrow' (should be numeric-like)
drawArrow <- FALSE
} else arrCol <- if(length(expFCarrow) >1) expFCarrow[2] else 1
}
if(length(expFCarrow) >1) {arrCol <- expFCarrow[2] # 2nd value of expFCarrow for color
} else arrCol <- 1 # autom : use 3rd if possible
}
if(drawArrow) {
if(is.finite(expM)) {
figCo <- graphics::par("usr") # c(x1, x2, y1, y2)
figRa <- diff(range(figCo[1:2]))*0.1
if(expM > figCo[2] +figRa || expM < figCo[1] -figRa) {
if(!silent) message(fxNa,"Can't draw arrow, ",round(expM,2)," is too far outside the plotting frame")
expM <- NA }
}
if(is.finite(expM)) {
arr <- c(0.019,0.14) # start- and end-points of arrow (as relative to entire plot)
graphics::arrows(expM, figCo[3] + arr[1]*(figCo[4] -figCo[3]), expM, figCo[3] + arr[2]*(figCo[4] -figCo[3]),
col=arrCol, lwd=1, length=0.1)
graphics::mtext(paste("expect at",signif(expM,3)), at=expM, side=1, adj=0.5, col=arrCol, cex=cexLa*0.7, line=-0.9)
} else { if(!silent) message(fxNa,"Unable to draw arrow for expexted M-value)") }
}
if(debug) {message(fxNa,"VPW19")}
tmp <- try(graphics::par(mar=opar$mar, cex.main=opar$cex.main, las=opar$las), silent=TRUE) # resetto previous
## export data used for plotting
if(returnData) {
annCo <- wrMisc::naOmit(match(annotColumn, colnames(merg)), callFrom=fxNa)
addMeans <- NULL
if(any(c("MArrayLM","list") %in% class(Mvalue)) && "means" %in% names(Mvalue)) {
addMeans <- Mvalue$means
colnames(addMeans) <- paste0(colnames(addMeans),".mean") }
if(length(annCo) !=0 && T) merg <- data.frame(merg[, annCo, drop=FALSE], addMeans, merg[,-annCo, drop=FALSE])
merg }
} ## end of code
}
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.