R/plots.R

#' Make boxplot of taxon abundance stratified by one sample metadata item.
#'
#' @param physeq Phyloseq object.
#' @param group Metadata column to stratify.
#' @param taxon Name of taxon whose abundance should be drawn.
#'
#' @return ggplot object.
#' @export
#'
#' @examples
#' \dontrun{
#' boxplot_taxon(physeq, taxon="Prevotella", group="Enterotype")
#' }
boxplot_taxon <- function(physeq, taxon = NULL, group = NULL) {
  if (is.null(group) | is.null(taxon)) {
    stop("boxplot_taxon(): group and taxon cannot be NULL")
  }
  if (is.null(sample_data(physeq)[[group]])) {
    stop(paste("boxplot_taxon(): Requested column", group, "does not exist in physeq object"))
  }

  abund <- as.data.frame(otu_table(physeq))
  annot <- tax_table(physeq)
  colnames(abund) <- apply(annot, 1, get_pretty_taxon_name)
  abund[[group]] <- sample_data(physeq)[[group]]
  ggplot(abund, aes(get(group), get(taxon))) + geom_boxplot() + scale_y_log10() + xlab(group) + ylab(taxon)
}
TBrach/MicrobiomeX documentation built on May 14, 2019, 2:28 p.m.