R/QLines.r

#' @title Plot Quantiles
#'
#' @description Add quantile lines to existing plot. QLines is for long data. QMatLines is for short data.
#'
#' @param x an array of x variable. For QLines, it should be repeating itself,
#' and for QMatLines, non-repeating.
#' @param ys Either an array or matrix of y variable. For QLines, it should be an array,
#' and for QMatLines, a matrix with columns for iterations.
#' @param qs an array of quantiles. Default at c(0.05,0.95).
#' @param mean.lwd An integer for indicating the width of mean. Default at 1.
#' @param mean.col Color for mean. Default at rainbow.f(1,1).
#' @param q.col Color for quantiles. Default at rainbow.f(1,1).
#'
#' @export QLines
#' @export QMatLines
#'
#' @examples
#' # Generate a long table
#' niter <- 100
#' df <- data.frame("Date"=rep(seq(as.Date("2010-1-1"), by="month", length.out = 12),niter)
#' , "Iter" = rep(1:niter,each=12), "Y"=rnorm(12*niter))
#' for (i in 2:nrow(df))if(diff(df$Iter)[i-1]==0) df$Y[i] <- df$Y[i] + df$Y[i-1]
#'
#' plot(df$Date, df$Y, col=red.f(0.05), pch=19)
#' QLines(df$Date, df$Y, mean.lwd = 2)
#'
#' # A short Table
#' df <- cast(df, Date ~ Iter, value="Y")
#' QMatLines(df$Date, df[,-1], qs=c(0.25,0.75), q.col=gray.f(0.5))


# Add quantile lines to existing plot. Data needs to be in a long table.
QLines<- function(x, ys
                  , qs = c(0.05,0.95)
                  , mean.lwd=1
                  , mean.col = rainbow.f(1,1)
                  , q.col=rainbow.f(1,1)){
  m <- aggregate(ys, by=list(x), mean, na.rm=TRUE)
  lines(m, col=mean.col, lwd=mean.lwd)

  qs <- aggregate(ys, by=list(x), quantile, qs, na.rm=TRUE)
  matlines(qs[,1], qs[,-1], col=q.col, lty=1)
}

#' @describeIn QLines for short table
QMatLines<- function(x, ys
                  , qs = c(0.05,0.95)
                  , mean.lwd=1
                  , mean.col = rainbow.f(1,1)
                  , q.col=rainbow.f(1,1)){

  lines(x, apply(ys,1, mean), col=mean.col, lwd=mean.lwd)

  matlines(x, t(apply(ys, 1, quantile, qs)), col=q.col, lty=1)

}
einaooka/tea.eo.plots documentation built on May 16, 2019, 1:25 a.m.