R/amp_function.R

Defines functions amp_function

Documented in amp_function

#' Generate a function table
#'
#' Generate a function table that is sorted based on an input heatmap.
#'
#' @usage amp_function(heatmap)
#'
#' @param heatmap (required) A heatmap generated by amp_heatmap.
#' @param functions A data frame that associates functions with a genus names (default: "MiDAS").
#' @param adjust Adjust the whitespace added in the bottom of the plot in mm (default: 10).
#' @param genus.pos Specify which part of the name that contains the genus name (default: 1).
#' @param point.size Size of the plotted points (default: 6)
#' @param selection A vector with the functions to be displayed e.g. c("FIL","NOB").
#' 
#' @return A ggplot2 object.
#' 
#' @export
#' @import ggplot2
#' @import dplyr
#' @import reshape2
#' @import phyloseq
#' 
#' @author Mads Albertsen \email{MadsAlbertsen85@@gmail.com}

amp_function <- function(heatmap, functions = NULL, adjust = 10, genus.pos = 1, point.size = 6, selection=NULL){
  
  # Retrieve the genus names from the plot
  names <- data.frame(do.call('rbind', strsplit(levels(droplevels(heatmap$data$Display)),'; ',fixed=TRUE)))
  names <- data.frame(Genus = names[,genus.pos])
  names$Genus <- as.character(names$Genus)
  
  # Retrieve the function data if not provided
  if (is.null(functions)) {
    data(MiF)
    functions <- MiF
  }
  
  # Define some nice colors for plotting
  POS <- "#31a354"
  VAR <- "orange"
  NEG <- "#f03b20"
  NT <- "grey90"
  
  # Make selection if not plotting all functions
  if (!is.null(selection)){
    functions <- functions[,c("Genus",selection)]
  } else{
    functions <- functions[,c("Genus",c("FIL", "AOB", "NOB", "PAO", "GAO", "HET", "FER"))]
  }
  
  # Merge the genus and function information
  
  nameFunc <- merge(x = names, y = functions, all.x = T, all.y = F) 
  
  nameFunc[is.na(nameFunc)] <- "NT"
  
  nameFuncM <- melt(nameFunc, id.vars = "Genus", value.name = "Value", variable.name = "Function")
  
  nameFuncM$Value <- factor(nameFuncM$Value, levels = c("POS", "VAR", "NEG", "NT"))
  nameFuncM$Genus <- factor(nameFuncM$Genus, levels = names$Genus)
  
  
  # Generate the plot
  
  p <- ggplot(nameFuncM, aes(x = Function, y = Genus, color = Value)) +
    geom_point(size = point.size) +
    scale_color_manual(values = c(POS, VAR, NEG, NT), drop = F) +
    theme(axis.text.x = element_text(size = 12, color = "black", angle = 90, hjust = 1, vjust = 0.4),
          axis.text.y = element_blank(),
          axis.title = element_blank(),
          legend.title = element_blank(),
          axis.ticks.length = unit(1, "mm"),
          axis.ticks = element_blank(),
          plot.margin = unit(c(0,0,adjust,0), "mm"),
          panel.background = element_blank(),
          panel.grid.major = element_line(color = "grey95"),
          legend.key = element_blank()
    )
  
    return(p)
}
MadsAlbertsen/ampvis documentation built on May 7, 2019, 2:08 p.m.