Nothing
graph_edges <- function(p, g, edge_color, edge_size, node_size,
edge_bundle = FALSE, layout = NULL, shared = NULL,
backbone = NULL, edge_arrows = TRUE) {
bundle_geom <- .infer_bundle_geom(edge_bundle)
fan <- .has_parallel_ties(g)
diagonal <- .draws_diagonals(g, layout)
if (manynet::is_directed(g)) {
out <- .infer_directed_edge_mapping(g, edge_color, edge_size, node_size,
layout, shared, backbone)
# One arrowhead size for the layer, read from the widths the ties are
# drawn at, which `graphs()` scales across all of its panels.
arrow <- .infer_arrow(out[["esize"]], edge_arrows, shared[["esize"]])
if (!is.null(bundle_geom)) {
p <- .map_bundled_edges(p, g, out, bundle_geom, arrow = arrow)
} else if (fan) {
p <- .map_fanned_edges(p, g, out, directed = TRUE, arrow = arrow)
} else if (diagonal) {
p <- .map_diagonal_edges(p, g, out, directed = TRUE, arrow = arrow)
} else {
p <- .map_directed_edges(p, g, out, arrow)
}
} else {
out <- .infer_edge_mapping(g, edge_color, edge_size, layout, shared,
backbone)
if (!is.null(bundle_geom)) {
p <- .map_bundled_edges(p, g, out, bundle_geom)
} else if (fan) {
p <- .map_fanned_edges(p, g, out, directed = FALSE)
} else if (diagonal) {
p <- .map_diagonal_edges(p, g, out, directed = FALSE)
} else {
p <- .map_edges(p, g, out)
}
}
if (manynet::is_looped(g)) {
# Resolved here rather than inside aes(), which would evaluate it lazily
# against whatever `p` held by the time the plot was built.
loop_strength <- .infer_loop_strength(p)
p <- p + ggraph::geom_edge_loop0(ggplot2::aes(strength = loop_strength),
edge_alpha = 0.4)
}
# Check legends
# A `graphs()` panel is scaled against every network beside it rather than
# against its own ties alone (see `.shared_aes()`), so that the guides can be
# collected and a weight is drawn at the same width in each panel.
if (is.null(shared[["esize"]]) && length(unique(out[["esize"]])) == 1) {
p <- p + ggplot2::guides(edge_width = "none")
} else p <- p + ggraph::scale_edge_width_continuous(range = .edge_width_range(),
limits = shared[["esize"]],
guide = ggplot2::guide_legend(
ifelse(is.null(edge_size) &
manynet::is_weighted(g),
"Weight", "Width")))
ecolor_title <- .infer_ecolor_title(g, edge_color)
elevels <- shared[["ecolor"]]
if (is.null(elevels)) elevels <- unique(as.character(out[["ecolor"]]))
if (length(elevels) == 1) {
p <- p + ggplot2::guides(edge_colour = "none")
} else {
# The values are named by the categories, and the scale given those
# categories as its limits, so that a category keeps its colour and its key
# even in a panel whose ties do not include it.
evalues <- if (length(elevels) == 2)
getOption("snet_highlight", default = c("grey","black")) else
ag_qualitative(length(elevels))
p <- p + ggraph::scale_edge_colour_manual(
values = stats::setNames(evalues, elevels), limits = elevels,
drop = FALSE, guide = ggplot2::guide_legend(ecolor_title))
}
# When linetype varies across ties (signed networks) it is mapped through
# aes() as literal "solid"/"dashed" strings, so an identity scale is needed to
# use them verbatim. Such a scale draws no legend by default, which was right
# while the colours said "Sign" too, but leaves the dashes unexplained now
# that they may be the only thing showing the sign.
if (length(unique(out[["line_type"]])) > 1) {
if (identical(ecolor_title, "Sign")) {
p <- p + ggraph::scale_edge_linetype_identity()
} else {
p <- p + ggraph::scale_edge_linetype_identity(
name = "Sign", guide = "legend",
breaks = c("solid", "dashed"), labels = c("Positive", "Negative"))
}
}
p
}
# Helper functions for .graph_edges()
.infer_directed_edge_mapping <- function(g, edge_color, edge_size, node_size,
layout = NULL, shared = NULL,
backbone = NULL) {
list("ecolor" = .infer_ecolor(g, edge_color, shared[["ecolor"]]),
"esize" = .infer_esize(g, edge_size),
"line_type" = .infer_line_type(g),
"ealpha" = .infer_ealpha(g, layout, backbone),
"end_cap" = .infer_end_cap(g, node_size, layout))
}
.infer_edge_mapping <- function(g, edge_color, edge_size, layout = NULL,
shared = NULL, backbone = NULL) {
list("ecolor" = .infer_ecolor(g, edge_color, shared[["ecolor"]]),
"esize" = .infer_esize(g, edge_size),
"line_type" = .infer_line_type(g),
"ealpha" = .infer_ealpha(g, layout, backbone))
}
# .infer_ecolor/.infer_esize/.infer_arrow/.infer_line_type live in
# R/graph_aes.R, shared with grapht(). These arguments have already been checked
# against the network's attributes by graphr()/grapht() (see R/graph_checks.R).
# A self-loop's `strength` is its diameter, measured in the same units as the
# layout's coordinates, and `geom_edge_loop0()` defaults it to 1. Since layouts
# differ by orders of magnitude in how far their coordinates spread, that one
# number draws a loop that is either invisible or, as for the "levels"
# layout whose coordinates span about one unit in each direction, a circle
# wider than the network it belongs to -- which then stretches the panel to
# fit, leaving the plot squeezed against its legend. Sized as a fraction of
# the layout instead, a loop reads as a loop whatever the layout.
#
# Note that `strength` is an aesthetic of the loop geoms rather than a layer
# parameter: passed as a parameter it is silently dropped ("Ignoring unknown
# parameters"), so it has to be mapped through `aes()`.
.infer_loop_strength <- function(p) {
spread <- max(diff(range(p[["data"]][["x"]], na.rm = TRUE)),
diff(range(p[["data"]][["y"]], na.rm = TRUE)))
# A network drawn at a single point has no spread to take a fraction of.
if (!is.finite(spread) || spread <= 0) return(1)
spread * 0.06
}
# A multilevel layout draws each level as a plane, and in an interlocking
# network the ties running between those planes typically outnumber the ties
# within them: `fict_marvel` has 683 against 558. Drawn at the same strength
# they curtain over both planes, so they are faded well back, and the ties
# within each level brought forward, so that the structure of each level and
# the shape of the interlock can both be seen.
#
# A backbone works the same way and is applied on top: a tie the filter does
# not keep is drawn at a fifth of whatever it would have been drawn at, which
# takes the usual 0.4 down to the same 0.08. A tie the filter keeps is left
# alone, so that a backbone changes what is faded rather than what is normal.
.infer_ealpha <- function(g, layout = NULL, backbone = NULL) {
out <- if (identical(layout, "levels") && manynet::is_twomode(g) &&
manynet::net_ties(g) > 0)
ifelse(manynet::tie_is_twomode(g), 0.08, 0.5) else 0.4
if (is.null(backbone)) return(out)
out * ifelse(backbone, 1, 0.2)
}
.infer_end_cap <- function(g, node_size, layout = NULL) {
# A "lineage" scales its nodes to the sizes they are drawn at, so the end of
# each tie is capped at the edge of the node it points to, with the
# arrowhead clear of it. See `.drawn_nsize()`.
if (identical(layout, "lineage")) {
nsize <- .drawn_nsize(g, node_size, layout) / 2 + 0.5
if (length(nsize) == 1L) return(rep(nsize, manynet::net_ties(g)))
to <- igraph::as_edgelist(manynet::as_igraph(g), names = FALSE)[, 2]
return(nsize[to])
}
nsize <- .infer_nsize(g, node_size, layout)/2
# Accounts for rescaling
if (length(unique(nsize)) == 1) {
out <- rep(unique(nsize), manynet::net_ties(g))
} else {
# Each tie's end cap is sized from the node it points to, so index the node
# sizes by the edgelist's target column (kept as node indices, not names).
out <- nsize[igraph::as_edgelist(manynet::as_igraph(g), names = FALSE)[, 2]]
out <- ((out - min(out)) / (max(out) - min(out))) *
((1 / manynet::net_nodes(g) * 100) - (1 / manynet::net_nodes(g)*50)) +
(1 / manynet::net_nodes(g) * 50)
}
out
}
# Route the four vectorisable edge aesthetics (colour, width, linetype, alpha)
# either through aes() -- when they vary across ties, so ggraph's edge stats
# expand and subset them alongside the geometry (point expansion in
# geom_edge_arc, loop removal, faceting) -- or as a constant layer parameter
# when they are a single value. Passing a per-tie vector as a constant parameter
# is what breaks signed multiplex/longitudinal networks: it recycles against the
# wrong length or feeds NA/malformed values straight to grid ("invalid hex digit
# in 'color' or 'lty'").
.split_edge_aes <- function(out) {
# `mapping` holds unevaluated expressions (not the vectors themselves) so that
# do.call(aes, mapping) captures them as quosures resolved lazily against
# `out` in the caller's environment -- the same way the aesthetics were
# written literally before -- rather than as pre-evaluated constants.
keys <- c(ecolor = "edge_colour", esize = "edge_width",
line_type = "edge_linetype", ealpha = "edge_alpha")
exprs <- list(ecolor = quote(out[["ecolor"]]),
esize = quote(out[["esize"]]),
line_type = quote(out[["line_type"]]),
ealpha = quote(out[["ealpha"]]))
mapping <- list(); params <- list()
# A category is mapped however few ties there are: a `graphs()` panel with a
# single tie still has its colour named by a category, such as "Negative",
# which only the scale can turn into a colour.
for (nm in names(keys)) {
if (length(out[[nm]]) > 1 || is.factor(out[[nm]]))
mapping[[keys[[nm]]]] <- exprs[[nm]]
else params[[keys[[nm]]]] <- out[[nm]]
}
list(mapping = mapping, params = params)
}
# A varying alpha is mapped through aes() as the literal values themselves, so
# an identity scale is needed to use them verbatim. They distinguish the levels
# of a multilevel layout, which the layout already makes plain, so no alpha
# legend is drawn.
.scale_edge_aes <- function(p, parts) {
if ("edge_alpha" %in% names(parts$mapping))
p <- p + ggraph::scale_edge_alpha_identity()
p
}
.map_directed_edges <- function(p, g, out, arrow = NULL) {
parts <- .split_edge_aes(out)
parts$mapping$end_cap <- quote(ggraph::circle(c(out[["end_cap"]]), 'mm'))
args <- c(list(mapping = do.call(ggplot2::aes, parts$mapping),
strength = .infer_arc_strength(g, p),
arrow = arrow),
parts$params)
.scale_edge_aes(p + do.call(ggraph::geom_edge_arc, args), parts)
}
.infer_arc_strength <- function(g, p) {
# `geom_edge_arc()` reciprocated dyads apart (0.2) and draws single ties
# straight (0). Its stat removes every tie whose two ends sit at the same
# point before drawing, but `strength` is a length-preserving parameter
# rather than an aesthetic, so it must leave the same ties out. Otherwise a
# full-length (net_ties) vector recycles against the shorter edge set and
# emits "longer object length is not a multiple" warnings.
strength <- ifelse(igraph::which_mutual(manynet::as_igraph(g)), 0.2, 0)
strength[!.tie_is_coincident(g, p)]
}
# Which ties `ggraph:::remove_loop()` drops, tested the way it tests them:
# on the coordinates rather than on the network. That is every self-loop, which
# `geom_edge_loop0()` draws instead, and also every tie between two nodes that
# the layout placed at one point, as the "scaling" layout does where two nodes
# hold the same distances to every other node.
.tie_is_coincident <- function(g, p) {
el <- igraph::as_edgelist(manynet::as_igraph(g), names = FALSE)
xy <- p[["data"]]
out <- xy[["x"]][el[, 1]] == xy[["x"]][el[, 2]] &
xy[["y"]][el[, 1]] == xy[["y"]][el[, 2]]
# A node without coordinates is not a node drawn on top of another one, and
# `remove_loop()` keeps its ties too.
out[is.na(out)] <- FALSE
out
}
# Whether any two ties join the same pair of nodes in the same way, so that a
# straight line or a single arc would draw one on top of the other. This is not
# `is_multiplex()`, which asks only whether the ties carry a layer column
# (see `.has_layers()` in R/graph_aes.R), and it is not
# `which_mutual()`, which flags the two ties of a reciprocated dyad that
# `geom_edge_arc()` already draws apart. `which_multiple()` respects direction:
# it flags a repeated undirected pair, and a repeated directed pair, but not a
# reciprocated dyad.
.has_parallel_ties <- function(g) {
any(igraph::which_multiple(manynet::as_igraph(g)))
}
# `geom_edge_fan()` groups the ties by the unordered node pair, gives each tie in
# a group its own side of the pair, and draws a group of one straight. Its
# `strength` is a scalar layer parameter, so the length-preserving problem that
# `.infer_arc_strength()` solves does not arise here: the fan stat drops the same
# ties (self-loops, and a tie whose two ends sit at one point) without a vector
# to keep in step with.
#
# The constant is calibrated against the arcs drawn for a reciprocated dyad. For
# a chord of length one, `geom_edge_arc(strength = 0.2)` bends 0.1159 away from
# the chord, and a two-tie fan at `strength = 1` bends 0.0625, so 1.85 draws two
# parallel ties about as far apart as two reciprocated ties.
.fan_strength <- function() 1.85
.map_fanned_edges <- function(p, g, out, directed = FALSE, arrow = NULL) {
parts <- .split_edge_aes(out)
args <- c(list(strength = .fan_strength()), parts$params)
if (directed) {
parts$mapping$end_cap <- quote(ggraph::circle(c(out[["end_cap"]]), 'mm'))
args$arrow <- arrow
}
if (length(parts$mapping))
args$mapping <- do.call(ggplot2::aes, parts$mapping)
.scale_edge_aes(p + do.call(ggraph::geom_edge_fan, args), parts)
}
# A "lineage" runs its layers left to right, so a tie runs from one layer to a
# later or an earlier one. A curve that leaves and meets each node flat, along
# the layers, shows which way a tie runs, and where several ties share a node
# they fan out from it instead of lying on top of each other. That is how a
# historiograph draws its citations. The two ties of a reciprocated dyad
# would draw the same curve, so a network with any keeps its arcs, which draw
# the two apart.
.draws_diagonals <- function(g, layout) {
identical(layout, "lineage") && manynet::net_ties(g) > 0 &&
!any(igraph::which_mutual(manynet::as_igraph(g)) &
manynet::is_directed(g))
}
# Less than `geom_edge_diagonal()`'s full strength, so that a tie between two
# nodes far apart in one layer does not run along the layer before it turns.
.diagonal_strength <- function() 0.6
.map_diagonal_edges <- function(p, g, out, directed = FALSE, arrow = NULL) {
parts <- .split_edge_aes(out)
# `flipped` since the layers run along x rather than down y, as in a tree.
args <- c(list(strength = .diagonal_strength(), flipped = TRUE),
parts$params)
if (directed) {
parts$mapping$end_cap <- quote(ggraph::circle(c(out[["end_cap"]]), 'mm'))
args$arrow <- arrow
}
if (length(parts$mapping))
args$mapping <- do.call(ggplot2::aes, parts$mapping)
.scale_edge_aes(p + do.call(ggraph::geom_edge_diagonal, args), parts)
}
.infer_bundle_geom <- function(edge_bundle) {
# Resolves the `edge_bundle` argument to one of ggraph's edge-bundling geom
# functions, or NULL when bundling is switched off. `TRUE` is treated as the
# force-directed default; a string selects a specific algorithm.
if (is.null(edge_bundle) || isFALSE(edge_bundle)) return(NULL)
type <- if (isTRUE(edge_bundle)) "force" else tolower(as.character(edge_bundle))
type <- .check_choice(type, c("force", "path", "minimal"), "edge_bundle")
switch(type,
force = ggraph::geom_edge_bundle_force,
path = ggraph::geom_edge_bundle_path,
minimal = ggraph::geom_edge_bundle_minimal)
}
.map_bundled_edges <- function(p, g, out, bundle_geom, arrow = NULL) {
# Edge-bundling geoms draw paths that are pulled together into bundles, so the
# arc `strength`/`end_cap` treatment used for straight/arced edges does not
# apply. Directed networks keep the arrowheads `graph_edges()` chose for
# them; undirected networks have none. Colour/width mapping is preserved to
# the extent the geom's aesthetics allow.
parts <- .split_edge_aes(out)
# Bundling merges edges into shared paths whose stat inserts NA-separated
# break points, so a per-tie linetype cannot be represented (the NAs reach
# grid as invalid linetypes). Drop a varying linetype and draw bundles solid;
# a linetype shared by every tie is already in `parts$params` and is kept.
# A per-tie alpha cannot survive that merging either, so bundles are drawn at
# the usual constant instead.
parts$mapping[["edge_linetype"]] <- NULL
if ("edge_alpha" %in% names(parts$mapping)) {
parts$mapping[["edge_alpha"]] <- NULL
parts$params[["edge_alpha"]] <- 0.4
}
args <- c(list(arrow = arrow), parts$params)
if (length(parts$mapping)) args$mapping <- do.call(ggplot2::aes, parts$mapping)
p + do.call(bundle_geom, args)
}
.map_edges <- function(p, g, out) {
parts <- .split_edge_aes(out)
args <- parts$params
if (length(parts$mapping)) args$mapping <- do.call(ggplot2::aes, parts$mapping)
.scale_edge_aes(p + do.call(ggraph::geom_edge_link0, args), parts)
}
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.