R/plot_dendrogram.R

Defines functions plot_dendrogram

Documented in plot_dendrogram

#' Plot a dendrogram
#' @param dist_method distance method passed to dist
#' @param clust_method clustering method passed to hclust
#' @param log_transform log transform the data?
#' @param groups groups passed to colourize branchs
#' @param title title of the plot
#' @param gg use ggplot?
#' @export

plot_dendrogram <- function(x,
                            dist_method = c("euclidean", "maximum",
                                            "manhattan", "canberra",
                                            "binary", "minkowski"),
                            clust_method = c("ward.D", "ward.D2", "single",
                                             "complete", "average", "mcquitty",
                                             "median", "centroid"),
                            log_transform = TRUE,
                            groups = NULL,
                            title = "",
                            gg = TRUE) {


  dist_method <- match.arg(dist_method)
  clust_method <- match.arg(clust_method)

  if(log_transform) {
    x <- log(t(x)+1)
  } else {
    x <- t(x)
  }

  dist_mat <- dist(x, method = dist_method)
  dend <- hclust(dist_mat, method = clust_method)

  dend <- as.dendrogram(dend)


  if(!is.null(groups)) {

    # match groups and labels
    groups <- groups[match(labels(dend), rownames(x))]
    colors <- RColorBrewer::brewer.pal(9, "Set1")
    my_palette <- colors[as.factor(groups)]
    dend <- dendextend::set(dend, "labels_col", my_palette)
    dend <- dendextend::set(dend, "branches_k_color", my_palette)
  }

  out <- dend

  if(gg) {
    dend <- dendextend::as.ggdend(dend)
    dend <- ggplot2::ggplot(dend, horiz = TRUE, theme = theme_minimal()) +
      ggplot2::ggtitle(title) +
      theme(plot.title = element_text(size=15))
    plot(dend)
  } else {
    plot(dend, main = title)
  }

  out
}
leandroroser/RNASeqFunctions documentation built on May 17, 2019, 7:31 p.m.