R/plotTree.R

Defines functions plotTree .representative_tree_layout

Documented in plotTree

.representative_tree_layout <- function(levels, ids) {
  if (!is.numeric(levels) || !is.numeric(ids) || length(levels) == 0L ||
      length(levels) != length(ids) || anyNA(levels) || anyNA(ids) ||
      any(!is.finite(levels)) || any(!is.finite(ids)) ||
      any(levels != floor(levels)) || any(ids != floor(ids)) ||
      any(levels < 0) || any(ids < 0)) {
    stop("Invalid representative-tree levels or node identifiers.", call. = FALSE)
  }

  levels <- as.integer(levels)
  ids <- as.integer(ids)
  keys <- paste(levels, ids, sep = "/")
  if (anyDuplicated(keys)) {
    stop("Representative-tree nodes must have unique level/id pairs.",
         call. = FALSE)
  }

  root <- which(levels == 0L & ids == 0L)
  if (length(root) != 1L || sum(levels == 0L) != 1L) {
    stop("The representative tree must contain exactly one root node.",
         call. = FALSE)
  }

  child_indices <- which(levels > 0L)
  parent_indices <- match(
    paste(levels[child_indices] - 1L, ids[child_indices] %/% 2L, sep = "/"),
    keys
  )
  if (anyNA(parent_indices)) {
    stop("Every non-root representative-tree node must have a parent.",
         call. = FALSE)
  }

  edges <- if (length(child_indices) > 0L) {
    cbind(parent = parent_indices, child = child_indices)
  } else {
    matrix(integer(), nrow = 0L, ncol = 2L,
           dimnames = list(NULL, c("parent", "child")))
  }
  children <- split(child_indices, parent_indices)
  x <- rep(NA_real_, length(levels))
  next_leaf <- 0L

  place_node <- function(node) {
    node_children <- children[[as.character(node)]]
    if (is.null(node_children)) {
      next_leaf <<- next_leaf + 1L
      x[node] <<- next_leaf
      return(invisible(NULL))
    }

    node_children <- node_children[order(ids[node_children])]
    for (child in node_children) {
      place_node(child)
    }
    x[node] <<- mean(range(x[node_children]))
    invisible(NULL)
  }
  place_node(root)

  if (anyNA(x)) {
    stop("The representative tree contains nodes disconnected from the root.",
         call. = FALSE)
  }

  list(
    coordinates = cbind(x = x, y = max(levels) - levels),
    edges = edges
  )
}

#' Plot nodes of the representative tree
#'
#' This function visualizes the representative tree of the output of the \code{\link{mrs}} function.
#' For each node of the representative tree, the posterior probability of difference (PMAP) or the effect size is plotted.
#' Each node in the tree is associated to a region of the sample space.
#' All non-terminal nodes have two children obtained by partitioning the parent
#' region with a dyadic cut along a given direction.
#' The numbers under the vertices represent the cutting direction.
#'
#' @param ans A \code{mrs} object.
#' @param type What is represented at each node.
#' The options are \code{type = c("eff", "prob")}.
#' @param group If \code{type = "eff"}, which group effect size is used.
#' @param legend Color legend for type. Default is \code{legend = FALSE}.
#' @param main Main title. Default is \code{main = ""}.
#' @param node.size Size of the nodes. Default is \code{node.size = 5}.
#' @param abs If \code{TRUE}, plot the absolute value of the effect size.
#' Only used when \code{type = "eff"}.
#' @return Invisibly returns \code{NULL}. The function is called for its side
#' effect of drawing the representative binary partition tree on the current
#' graphics device. Node size and color encode posterior probabilities or
#' effect sizes, and labels beneath non-terminal nodes identify split
#' directions.
#' @references Soriano J. and Ma L. (2017).
#' Probabilistic multi-resolution scanning for two-sample differences.
#'  \emph{Journal of the Royal Statistical Society: Series B (Statistical Methodology)}.
#'  \doi{10.1111/rssb.12180}
#' @references Ma L. and Soriano J. (2018).
#' Analysis of distributional variation through multi-scale Beta-Binomial modeling.
#'  \emph{Journal of Computational and Graphical Statistics}, 27(3), 529--541.
#'  \doi{10.1080/10618600.2017.1402774}
#' @export
#' @examples
#' set.seed(12345)
#' p = 2
#' n1 = 200
#' n2 = 200
#' mu1 = matrix( c(9,9,0,4,-2,-10,3,6,6,-10), nrow = 5, byrow=TRUE)
#' mu2 = mu1; mu2[2,] = mu1[2,] + 1
#'
#' Z1 = sample(5, n1, replace=TRUE)
#' Z2 = sample(5, n2, replace=TRUE)
#' X1 = mu1[Z1,] + matrix(rnorm(n1*p), ncol=p)
#' X2 = mu2[Z2,] + matrix(rnorm(n2*p), ncol=p)
#' X = rbind(X1, X2)
#' colnames(X) = c(1,2)
#' G = c(rep(1, n1), rep(2,n2))
#'
#' ans = mrs(X, G, K=8)
#' plotTree(ans, type = "prob", legend = TRUE)
plotTree <- function(ans, type="prob", group = 1, legend = FALSE, main = "", node.size=5, abs = TRUE)
{
  if (!inherits(ans, "mrs")) {
    stop("'ans' must be an 'mrs' object.", call. = FALSE)
  }
  if (length(ans$RepresentativeTree$Levels) == 0L) {
    stop("'ans' has no representative tree; refit with 'return_tree = TRUE'.",
         call. = FALSE)
  }
  type <- match.arg(type, c("prob", "eff"))
  group <- .validate_integer(group, "group", lower = 1L,
                             upper = ncol(ans$RepresentativeTree$EffectSizes))
  legend <- .validate_flag(legend, "legend")
  abs <- .validate_flag(abs, "abs")
  if (!is.numeric(node.size) || length(node.size) != 1L || is.na(node.size) ||
      !is.finite(node.size) || node.size <= 0) {
    stop("'node.size' must be a positive finite number.", call. = FALSE)
  }
  .pardefault <- par(no.readonly = TRUE)
  on.exit(par(.pardefault), add = TRUE)
  if(legend)
  {
    layout(matrix(c(1,2), nrow=1),widths=c(.85,.15))
    par(mar=c(1.1, 1.1, 3.1, 0.1))
  }
  else
  {
    layout(1)
  }
  if(type == "prob")
  {
    box.size = (ans$RepresentativeTree$AltProbs)*node.size + .2*node.size
    name = round(ans$RepresentativeTree$AltProbs, digits=2)
    col_range <- colorRampPalette(c("white","darkblue"))(100)
    col = col_range[ ceiling( name/max(name + 0.01)*99 + 1) ]
  }
  else if(type == "eff")
  {
    effect_magnitude <- abs(ans$RepresentativeTree$EffectSizes[, group])
    effect_max <- max(effect_magnitude)
    box.size <- if (effect_max > 0) {
      effect_magnitude / effect_max * node.size + 0.2 * node.size
    } else {
      rep(0.2 * node.size, length(effect_magnitude))
    }

    if (abs == TRUE) {
      name = abs(ans$RepresentativeTree$EffectSizes[,group])
      col_range <- colorRampPalette(c("white","darkred"))(100)
      col = col_range[ ceiling( name/max(name + 0.01)*99 + 1) ]
    } else {
      name = ans$RepresentativeTree$EffectSizes[, group]
      col_range <- c(colorRampPalette(c("red","white"))(50),
                     colorRampPalette(c("white","dodgerblue"))(50))
      col = col_range[ ceiling(name/max(abs(name)+0.01)*100/2+50) ]
    }

  }
  else
  {
    box.size = 5
    name = NA
    col = "white"
  }

  tree_layout <- .representative_tree_layout(
    ans$RepresentativeTree$Levels,
    ans$RepresentativeTree$Ids
  )
  co <- tree_layout$coordinates
  vertex.label <- ans$RepresentativeTree$Directions
  vertex.label[vertex.label == 0] <- NA
  terminal_nodes <- setdiff(
    seq_along(vertex.label),
    unique(tree_layout$edges[, "parent"])
  )
  vertex.label[terminal_nodes] <- NA

  xlim <- range(co[, "x"])
  if (diff(xlim) == 0) {
    xlim <- xlim + c(-0.75, 0.75)
  } else {
    xlim <- xlim + c(-0.06, 0.06) * diff(xlim)
  }
  ylim <- range(co[, "y"])
  if (diff(ylim) == 0) {
    ylim <- ylim + c(-0.75, 0.75)
  } else {
    ylim <- ylim + c(-0.35, 0.25)
  }

  plot(
    NA_real_, NA_real_, xlim = xlim, ylim = ylim,
    xlab = "", ylab = "", axes = FALSE, xaxs = "i", yaxs = "i",
    main = main
  )
  if (nrow(tree_layout$edges) > 0L) {
    segments(
      co[tree_layout$edges[, "parent"], "x"],
      co[tree_layout$edges[, "parent"], "y"],
      co[tree_layout$edges[, "child"], "x"],
      co[tree_layout$edges[, "child"], "y"],
      col = "#777777", lwd = 1.2
    )
  }
  points(
    co[, "x"], co[, "y"], pch = 21,
    cex = pmax(0.75, box.size / 2.5),
    bg = col, col = "#333333", lwd = 0.8
  )
  labelled_nodes <- which(!is.na(vertex.label))
  if (length(labelled_nodes) > 0L) {
    text(
      co[labelled_nodes, "x"], co[labelled_nodes, "y"],
      labels = vertex.label[labelled_nodes], pos = 1L,
      offset = 0.5, cex = 0.75, col = "black", family = "Helvetica"
    )
  }

  if(legend)
  {
    plot(NA,type="n",ann=FALSE,xlim=c(1,2),ylim=c(1,2),xaxt="n",yaxt="n",bty="n")
    rect(xleft = 1.25,
         ybottom = head(seq(1,2,1/100),-1),
         xright = 1.75,
         ytop = tail(seq(1,2,1/100),-1),
         col=col_range, border = col_range )
    rect(1.25, 1, 1.75, 2.0)
    if(type == "prob")
      mtext(formatC(seq(0,1,.1), format = "f", digits = 1),side=2,at=seq(1,2.,by=.1),las=2,cex=1, line=0)
    if(type == "eff") {
      effect_limit <- max(abs(name))
      effect_ticks <- if (abs == TRUE) {
        seq(0, effect_limit, length.out = 11L)
      } else {
        seq(-effect_limit, effect_limit, length.out = 11L)
      }
      effect_step <- if (effect_limit > 0) {
        max(diff(effect_ticks))
      } else {
        0
      }
      effect_digits <- if (effect_step > 0) {
        max(1L, min(4L, ceiling(-log10(effect_step))))
      } else {
        1L
      }
      mtext(
        formatC(effect_ticks, format = "f", digits = effect_digits),
        side = 2, at = seq(1, 2, by = 0.1), las = 2,
        cex = 0.85, line = 0
      )
    }

  }

  invisible(NULL)
}

Try the MRS package in your browser

Any scripts or data that you put into this service are public.

MRS documentation built on July 22, 2026, 5:10 p.m.