R/boxpl_function.R

Defines functions boxpl

Documented in boxpl

boxpl <- function(samp, tax, var, xlab = "Gradient", xmin = NULL, xmax = NULL,
                    quantiles = T, log = F, colvline = "red",
                    medlty = "solid", Qlty = "dashed", mintax = 10){

df1        <- setNames(cbind.data.frame(samp, tax, var),c("samp", "tax", "var"))
df1        <- na.omit(df1)
df1        <- df1[df1$tax %in%  names(table(df1$tax))[table(df1$tax) >= mintax],]

if(quantiles == T){
  quant <-  df1[!duplicated(df1$samp),][,3]
   Q2   <-  ggplot2::geom_hline(yintercept = median(quant, na.rm = T), size = 1, colour = colvline, linetype = medlty)
   Q1   <-  ggplot2::geom_hline(yintercept = quantile(quant, 0.25, na.rm = T), size = 1, colour = colvline, linetype = Qlty)
   Q3   <-  ggplot2::geom_hline(yintercept = quantile(quant, 0.75, na.rm = T), size = 1, colour = colvline, linetype = Qlty)}
else if(quantiles == F){Q2  <- NULL; Q1  <- NULL; Q3  <- NULL}
else(stop("The arugment quantiles has to be either TRUE or False."))

if(log == T)
{log <- ggplot2::scale_y_log10()}
else if(log == F)
{log <- NULL}
else{stop("Argument for log has to be either TRUE or FALSE")}

n               <- aggregate(data=df1, var~tax, length)
df2             <- merge(df1, n, by.x = "tax", by.y = "tax")
colnames(df2)[c(3,4)]<-c("var", "n")
df2$tax         <- paste0(df2$tax, " n=", df2$n)

if(is.null(xmin) == T && is.null(xmax) == T)
  {xrange <- NULL}
else if(is.null(xmin) == F && is.null(xmax) == T)
  {xrange <- ylim(xmin, max(df2$var))}
else if(is.null(xmin) == T && is.null(xmax) == F)
  {xrange <- ylim(min(df2$var), xmax)}
else if(is.null(xmin) == F && is.null(xmax) == F)
  {xrange <- ylim(xmin, xmax)}
else{stop("Argument for xmin or xmax need to be nummeric.")}

  ggplot2::ggplot(df2, ggplot2::aes(x=reorder(df2$tax, df2$var, FUN = median), y=df2$var, group=df2$tax))+
  ggplot2::geom_boxplot(outlier.shape = 21, outlier.size = 1)+xrange+
  ggplot2::xlab("")+ggplot2::ylab(xlab)+Q2+Q1+Q3+log+
  ggplot2::theme(axis.line = ggplot2::element_line(colour = "black"),
                 axis.text = ggplot2::element_text(colour = "black"),
                 legend.position = "none",
                 legend.key = element_blank(),
                 panel.background = ggplot2::element_blank(),
                 panel.grid.minor = ggplot2::element_blank()) +
  ggplot2::coord_flip()}
snwikaij/GRASS documentation built on July 29, 2020, 1:54 p.m.