R/create-matrix-plot.R

Defines functions create_matrix_plot

#' @noRd
#' @importFrom ggplot2 ggplot ggplot_add geom_path aes_string scale_x_continuous scale_y_continuous
create_matrix_plot <- function(data) {
  if(!inherits(data, "matrix_tbl"))
    stop("Need a 'matrix_tbl'.", call. = FALSE)
  xlabel <- attr(data, ".col.names")
  ylabel <- rev(attr(data, ".row.names"))
  xlim <- c(0.5, length(xlabel) + 0.5)
  ylim <- c(0.5, length(ylabel) + 0.5)
  tree.data <- attr(data, ".treedata")
  row.tree.data <- tree.data$row.tree.data
  col.tree.data <- tree.data$col.tree.data
  p <- ggplot(data, aes_string(".col.id", ".row.id"), parent.env())
  if(!is.null(row.tree.data)) {
    tree.x.rng <- range(row.tree.data$x, na.rm = TRUE)
    if(tree.x.rng[1] >= 0.5) {
      xlim[2] <- tree.x.rng[2] + length(xlabel) * 0.01
    } else {
      xlim[1] <- tree.x.rng[1] - length(xlabel) * 0.01
    }
    p <- p + geom_path(aes_string("x", "y", group = "id"), row.tree.data)
  }

  if(!is.null(col.tree.data)) {
    tree.y.rng <- range(col.tree.data$y, na.rm = TRUE)
    if(tree.y.rng[1] >= 0.5) {
      ylim[2] <- tree.y.rng[2] + length(ylabel) * 0.01
    } else {
      ylim[1] <- tree.y.rng[1] - length(ylabel) * 0.01
    }
    p <- p + geom_path(aes_string("x", "y", group = "id"), col.tree.data)
  }
  ## setting axis
  p <- p +
    scale_x_continuous(name = NULL, expand = c(0, 0), limits = xlim,
                       breaks = 1:length(xlabel), labels = xlabel) +
    scale_y_continuous(name = NULL, expand = c(0, 0), limits = ylim,
                       breaks = 1:length(ylabel), labels = ylabel)
  class(p) <- c("ggmatrix", class(p))
  p
}
houyunhuang/ggtriangle documentation built on May 11, 2020, 2:02 p.m.