R/graph_layout.R

Defines functions graph_layout .dim_label

# The name of a drawn dimension. A layout that reports how much of the
# network's inertia the dimension holds says so here, since an axis is where
# a reader looks for the scale it is reading against.
.dim_label <- function(k, fit) {
  base <- paste("Dimension", k)
  share <- fit[["inertia"]][k]
  if (is.null(share) || !is.finite(share)) return(base)
  paste0(base, " (", round(share * 100), "% of inertia)")
}

# The number of nodes above which the "stress" layout is run at a looser
# tolerance. See `graph_layout()`.
.stress_large <- 1000

graph_layout <- function(g, layout, labels, node_group, snap, backbone = NULL,
                         ...) {
  name <- NULL
  dots <- list(...)
  if ("x" %in% names(dots) & "y" %in% names(dots)) {
    lo <- ggraph::create_layout(g, layout = "manual",
                                x = dots[["x"]], y = dots[["y"]])
  } else {
    args <- c(list(graph = g, layout = layout), dots)
    # The backbone ties are given the length that draws them shortest, so that
    # the groups they hold together are what the layout pulls apart. A layout
    # that carries meaning in its coordinates, or that reads no tie lengths, is
    # left as it is, and its ties are only faded. A length the user gave
    # themselves is theirs. See `.backbone_layout_weights()`.
    if (!is.null(backbone) && !"weights" %in% names(dots)) {
      weights <- .backbone_layout_weights(g, layout, backbone)
      if (!is.null(weights)) args[["weights"]] <- weights
    }
    # A network that records tie lengths has them drawn as its distances,
    # where nothing else asks for the tie lengths the layout reads.
    if (!"weights" %in% names(args)) {
      weights <- .length_layout_weights(g, layout)
      if (!is.null(weights)) args[["weights"]] <- weights
    }
    # Stress majorization slows sharply on larger networks: 3000 nodes take
    # about 7 seconds at the default tolerance and under 2 at a looser one,
    # with little to see between the two drawings. A tolerance the user gave
    # is theirs.
    if (identical(layout, "stress") && !"tolerance" %in% names(args) &&
        igraph::vcount(g) > .stress_large) {
      args[["tolerance"]] <- 1e-3
      manynet::snet_info(
        "Laying out {igraph::vcount(g)} nodes with a looser stress tolerance",
        "to save time. Use {.code tolerance = 1e-4} for the finer layout.")
    }
    lo <- suppressWarnings(do.call(ggraph::create_layout, args))
  }
  if ("graph" %in% names(attributes(lo))) {
    if (!setequal(names(as.data.frame(attr(lo, "graph"))), names(lo))) {
      for (n in setdiff(names(as.data.frame(attr(lo, "graph"))), names(lo))) {
        lo[[n]] <- igraph::vertex_attr(g, n)
      }
    }
  }
  p <- ggraph::ggraph(lo) + ag_theme_void()
  # A graph has no use for axes, save where its coordinates can be read. The
  # "scaling" layout draws distances that mean something, so it keeps its axes,
  # and keeps them on one scale: a distance read off two axes of different
  # scales is not the distance the layout placed there.
  # The "correspondence" layout draws distances that can be read in the same
  # way, and names the share of inertia each of its dimensions holds.
  # A spatial layout draws distances on the ground, and so keeps one scale on
  # both axes too, though its coordinates are not read off axes.
  if (identical(layout, "spatial")) {
    p <- suppressMessages(p + ggplot2::coord_fixed())
  }
  if (is.character(layout) && length(layout) == 1L &&
      layout %in% c("scaling", "correspondence")) {
    fit <- attr(lo, "fit")
    p <- p + ag_theme_minimal() +
      ggplot2::labs(x = .dim_label(1, fit), y = .dim_label(2, fit))
    # ggraph has already set a coordinate system, and ggplot2 announces the
    # replacement, which is not news to anyone here.
    p <- suppressMessages(p + ggplot2::coord_fixed())
  }
  if (!is.null(node_group)) {
    # manynet::snet_requires("ggforce")
    # A membership matrix repeats a node's coordinates once for each group it
    # belongs to, so a node in several groups is inside several hulls and the
    # hulls overlap. One long data frame draws them all: ggforce draws one hull
    # for each level of the fill.
    if (is.matrix(node_group)) {
      idx <- which(node_group, arr.ind = TRUE)
      hulls <- data.frame(
        x = lo[["x"]][idx[, 1]], y = lo[["y"]][idx[, 1]],
        node_group = factor(colnames(node_group)[idx[, 2]],
                            levels = colnames(node_group)))
      ngroups <- ncol(node_group)
    } else {
      hulls <- lo
      ngroups <- length(unique(p$data[[node_group]]))
    }
    p <- p + 
      ggforce::geom_mark_hull(ggplot2::aes(x, y, fill = node_group,
                                           label = node_group), data = hulls) +
      ggplot2::scale_fill_manual(values = ag_qualitative(ngroups),
                                 guide = ggplot2::guide_legend("Group"))
  }
  if(snap){
    # Some layouts already encode meaning in their coordinates -- a layer, a
    # mode, a generation, or a date along one axis, a scaled distance along
    # both -- which square-grid snapping would collapse. Skip snapping for
    # those and keep the layout as computed.
    if (.is_fixed_layout(layout)) {
      manynet::snet_info(paste0("Skipping snapping: the '", layout,
                                "' layout carries meaning in its coordinates, ",
                                "so they are kept as computed."))
    } else {
    manynet::snet_info("Snapping layout coordinates to grid.")
    # Where the network repeats a structure -- a lattice, or anything else
    # whose ties take a few steps over and over -- those steps map onto the
    # axes and every node lands on its own grid point. Where it does not, each
    # node moves to the nearest vacant point instead.
    p$data[,c("x","y")] <- .snap_layout(p$data, g)
    }
  }
  p
}

Try the autograph package in your browser

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

autograph documentation built on Nov. 16, 2026, 5:08 p.m.