R/plot.R

#' Plotting a package adjacency matrix.
#'
#' This function provides helpful defaults for plotting a package adjacency
#' matrix. The default settings attempt to maximize the space between dense
#' parts of the graph. Private, non-exported functions are prefixed by a
#' ":" in the graph labels.
#'
#' @param adj_matrix An adjacency matrix generated by `adjacency_matrix()`
#' @param col_called Graphical parameter for the color of functions that are
#' called by other functions, defaults to "skyblue2"
#' @param col_caller Graphical parameter for the color of functions that only
#' call other functions, defaults to "darkgoldenrod1".
#' @param col_orphan Graphical parameter for the color of functions that neither
#' call nor are called, defaults to "lightgrey"
#' @param space_multiplier Numeric that affects how much space between nodes in
#' the plot.
#' @param ... Other graphical arguments, see `?qgraph` for more information.
#' @importFrom qgraph qgraph.layout.fruchtermanreingold qgraph
#' @export
plot_adjacency_matrix = function(adj_matrix,
                                 col_called = "skyblue2",
                                 col_caller = "darkgoldenrod1",
                                 col_orphan = "lightgrey",
                                 space_multiplier = 1,
                                 ...) {

  # Basic info needed to setup the label.
  num_vertices = nrow(adj_matrix)
  edge_list = which(unname(as.matrix(adj_matrix > 0)), TRUE)

  # Setup layout: repulse.rad slightly overpowered, gives more space
  # in dense places.
  layout = qgraph.layout.fruchtermanreingold(
    edge_list, vcount=num_vertices,
    area = 8 * space_multiplier * (num_vertices^2),
    repulse.rad = (num_vertices ^ (3.1 * space_multiplier))
  )

  # Which functions are callers, which are called, which are orphans
  row_sum = apply(adj_matrix, 2, sum)
  col_sum = apply(adj_matrix, 1, sum)

  # Strip out package info from vertex names
  vertex_labels = unlist(lapply(strsplit(colnames(adj_matrix), "::"),
                         function(x) { x[2] }))

  # Color waterfall
  vertex_color = ifelse(row_sum > 0,
                        col_called,
                        ifelse(col_sum > 0,
                               col_caller,
                               col_orphan))

  # Vertex size
  vertex_size = 8

  # Call qgraph to graph this adjacency matrix.
  qgraph(adj_matrix,
         layout=layout,
         color=vertex_color,
         vsize=vertex_size,
         shape="rectangle",
         vsize2 = vertex_size / 3,
         labels=vertex_labels,
         ...
  )
}
aaronrudkin/werner documentation built on May 23, 2019, 6:03 a.m.