ggtangle: Draw Network with Data

Guangchuang Yu
School of Basic Medical Sciences, Southern Medical University

2026-12-03

ggtangle draws networks with the grammar of graphics: a graph is converted into a data frame of node coordinates, and edges and nodes are added as ordinary ggplot2 layers. Every node or edge attribute can therefore be mapped to an aesthetic, and the result can be combined with other ggplot2 layers.

The examples below use one small random graph and a consistent colour palette, so that the differences between the figures come from the code being demonstrated rather than from the styling.

Setup

library(yulab.utils)
library(igraph)
library(ggplot2)
library(ggtangle)
library(aplot)
library(ggfun)

## a small palette reused in the figures below
node_col  <- "#3B6FB6"
high_col  <- "#D1495B"
other_col <- "#C9D2DB"

Simple network visualization

ggplot() gains a method for igraph objects. It computes a layout, stores the node coordinates in the plot data, and leaves the drawing to the usual layers: geom_edge() for edges and geom_point() for nodes.

set.seed(2)
net <- sample_gnp(10, .5)

V(net)$name <- letters[1:10]
E(net)$weight <- abs(rnorm(length(E(net))))
E(net)$type <- sample(LETTERS[1:3], length(E(net)), replace = TRUE)
V(net)$selected <- V(net)$name %in% letters[1:5]

## compute one layout and reuse it, so the figures below differ only in
## the attributes that are mapped
lay <- igraph::layout_with_fr(net)
net_layout <- function(graph) lay

p <- ggplot(net, layout = net_layout) + geom_edge(color = "grey60", linewidth = .45)

p + geom_point(size = 4.5, color = node_col)

A random graph drawn with geom_edge() and geom_point().

Flow chart

A flow chart is a directed graph, so a from/to edge list is enough: ggflow() converts the list to an igraph object, lays it out with igraph::layout_as_tree() by default, and draws the edges with arrowheads. Any igraph layout function can be supplied through layout.

flow_data <- data.frame(
    from = c("A", "A", "A", "B", "C", "F"),
    to   = c("B", "C", "D", "E", "F", "G")
)

## horizontal version of the tree layout
flow_lr <- function(g) {
    m <- igraph::layout_as_tree(g)
    cbind(-m[, 2], m[, 1])
}

boxes <- function(width = .62) {
    list(
        ggfun::geom_scatter_rect(fill = "#EDF2F8", color = node_col,
                                 linewidth = .5, width = width, asp = .55),
        geom_text(aes(label = label), size = 4.2, color = "#1F2D3D")
    )
}

p1 <- ggflow(flow_data, arrow = arrow(type = "closed", length = unit(1.8, "mm"))) +
    boxes()
p2 <- ggflow(flow_data, layout = flow_lr,
             arrow = arrow(type = "closed", length = unit(1.8, "mm"))) +
    boxes()

plot_list(p1, p2)

A from/to edge list drawn with ggflow(). Left: the default tree layout. Right: a custom layout that puts the flow left to right.

Node colour and size

Node attributes are available in the plot data, so colour, size and shape can be mapped exactly as in any other ggplot2 plot.

p1 <- p + geom_point(size = 5, color = node_col)

p2 <- p + geom_point(aes(color = selected), size = 5) +
    scale_color_manual(values = c(`FALSE` = other_col, `TRUE` = high_col),
                       labels = c("other", "a-e"), name = "Node set")

p3 <- p + geom_point(aes(size = degree(net)), color = node_col) +
    scale_size(name = "Degree", range = c(2.5, 8))

p4 <- p + geom_point(aes(shape = selected), color = node_col, size = 5) +
    scale_shape_manual(values = c(`FALSE` = 16, `TRUE` = 17),
                       labels = c("other", "a-e"), name = "Node set")

plot_list(p1, p2, p3, p4, ncol = 2)

Colour, size and shape are ordinary ggplot2 aesthetics; here they encode a node set, the node degree and a second node set.

Node labels

Labels are ordinary text layers. ggrepel keeps them from sitting on top of each other, and the usual data argument limits a layer to a subset of the nodes.

p5 <- p + geom_point(size = 6, color = node_col) +
    ggrepel::geom_label_repel(
        aes(label = label, color = selected),
        size = 4.3, fill = "white", label.size = .15,
        label.padding = unit(.12, "lines"),
        box.padding = .5, point.padding = .4, force = 1.5,
        min.segment.length = 0, segment.color = "grey65", segment.size = .5,
        max.overlaps = Inf, show.legend = FALSE
    ) +
    scale_color_manual(values = c(`FALSE` = "grey30", `TRUE` = high_col)) +
    coord_cartesian(clip = "off") +
    theme(plot.margin = margin(12, 12, 12, 12))

p6 <- p + geom_point(size = 6, color = node_col) +
    ggrepel::geom_label_repel(
        aes(label = label),
        data = ggtree::td_filter(label %in% letters[1:5]),
        size = 4.3, fill = "white", label.size = .15,
        label.padding = unit(.12, "lines"),
        box.padding = .5, point.padding = .4, force = 1.5,
        min.segment.length = 0, segment.color = "grey65", segment.size = .5,
        max.overlaps = Inf, seed = 1
    ) +
    coord_cartesian(clip = "off") +
    theme(plot.margin = margin(12, 12, 12, 12))

plot_list(p5, p6)

Node labels drawn with ggrepel. The second panel labels only the nodes in a to e.

Edges

Edge attributes can be mapped in the same way. Edges are drawn by a single geom_edge() layer, so weights control the line width and categorical attributes control colour or line type.

edge_legend <- theme(legend.position = "bottom",
                     legend.title = element_text(size = 9),
                     legend.text = element_text(size = 9),
                     legend.key.width = unit(1.1, "cm"))

p7 <- ggplot(net, layout = net_layout) +
    geom_edge(aes(linewidth = weight), color = "grey40", alpha = .85) +
    geom_point(size = 3.5, color = node_col) +
    scale_linewidth(name = "Weight", range = c(.2, 1.6), breaks = c(.5, 1.5)) +
    edge_legend

p8 <- ggplot(net, layout = net_layout) +
    geom_edge(aes(color = type), linewidth = .8) +
    geom_point(size = 3.5, color = node_col) +
    scale_color_manual(name = "Type",
                       values = c(A = "#3B6FB6", B = "#E6A23C", C = "#5DA271")) +
    edge_legend

p9 <- ggplot(net, layout = net_layout) +
    geom_edge(aes(linetype = type), color = "grey30", linewidth = .6) +
    geom_point(size = 3.5, color = node_col) +
    scale_linetype_discrete(name = "Type") +
    edge_legend

plot_list(p7, p8, p9, ncol = 3)

Edge weight maps to line width, and edge type maps to colour and to line type.

Layouts

Circular layout

A layout name can be passed directly to ggplot(). The circular layout places all nodes on a circle; fixing the aspect ratio keeps the circle round.

ggplot(net, layout = "circular") +
    geom_edge(color = "grey65", linewidth = .4) +
    geom_point(size = 10, color = node_col) +
    geom_text(aes(label = label), color = "white", size = 2.8, fontface = "bold") +
    coord_fixed()

Nodes placed on a circle with layout = "circular".

Linear layout

The linear layout arranges the nodes along one axis. Sorting by a node attribute turns the layout into an ordered chain.

set.seed(123)
g <- sample_pa(20)
V(g)$degree <- degree(g)
V(g)$name <- as.character(1:20)

p1 <- ggplot(g, layout = "linear") +
    geom_edge(geom = geom_curve, color = "grey65", linewidth = .35, curvature = .25) +
    geom_point(size = 2.6, color = node_col) +
    ggtitle("Default linear layout") +
    theme(plot.title = element_text(size = 11, hjust = .5, face = "bold"))

p2 <- ggplot(g, layout = "linear", sort.by = "degree") +
    geom_edge(geom = geom_curve, color = "grey75", linewidth = .35, curvature = .25) +
    geom_point(aes(size = degree), color = node_col) +
    scale_size(name = "Degree", range = c(1.8, 5)) +
    ggtitle("Sorted by degree") +
    theme(plot.title = element_text(size = 11, hjust = .5, face = "bold"))

plot_list(p1, p2, ncol = 1)

The linear layout before and after sorting the nodes by degree.

Network with external data

%<+% joins a data frame to the graph by node label, which makes external measurements available to the layers.

set.seed(123)
expr <- abs(rnorm(10))
d <- data.frame(label = V(net)$name, expression = expr)

p %<+% d +
    geom_point(aes(color = expression), size = 6) +
    scale_color_viridis_c(name = "Expression") +
    coord_fixed()

A data frame joined to the graph with %<+%; node colour encodes the joined value.

Network with pies

Because a node is just a position, any ggplot2 layer can be drawn there. scatterpie adds a pie chart at each node, with the slices coming from columns of the joined data.

flow_info <- data.frame(from = LETTERS[c(1, 2, 3, 3, 4, 5, 6)],
                        to   = LETTERS[c(5, 5, 5, 6, 7, 6, 7)])

dd <- data.frame(
    label = LETTERS[1:7],
    v1 = abs(rnorm(7)),
    v2 = abs(rnorm(7)),
    v3 = abs(rnorm(7))
)

flow_graph <- igraph::graph_from_data_frame(flow_info)

p_pie <- ggplot(flow_graph, layout = "kk") +
    geom_edge(color = "grey60", linewidth = .45)

library(scatterpie)

p_pie %<+% dd +
    geom_scatterpie(cols = c("v1", "v2", "v3"), pie_scale = 2,
                    color = "white", linewidth = .35) +
    ggrepel::geom_text_repel(aes(label = label), size = 3.6, seed = 2,
        nudge_y = .18, box.padding = .35, point.padding = .1, force = 2,
        min.segment.length = .15, segment.color = "grey80") +
    scale_fill_brewer(palette = "Set2", name = "Variable") +
    coord_fixed()

Pie charts at the nodes, drawn with scatterpie; slice colour encodes the variable.

Category-item association plot

cnetplot() draws a bipartite graph between categories and their items (for example gene sets and genes). Category nodes are sized by the number of items in the set; node_label selects which nodes are labelled.

set.seed(123)
x <- list(A = letters[1:10], B = letters[5:12], C = letters[sample(1:26, 15)])

no_size <- guides(size = "none")
## keep repel labels that sit at the panel edge from being clipped
room <- list(coord_cartesian(clip = "off"),
             scale_x_continuous(expand = expansion(mult = .12)),
             scale_y_continuous(expand = expansion(mult = .12)),
             theme(plot.margin = margin(6, 6, 6, 6)))

p1 <- cnetplot(x, node_label = "none", color_category = "#E5C494",
               color_item = "#B3B3B3", node_label_size = 3) + no_size + room
p2 <- cnetplot(x, node_label = "all", size_category = 1.5,
               node_label_size = 3) + no_size + room
p3 <- cnetplot(x, node_label = "category", node_label_size = 3) + no_size + room
p4 <- cnetplot(x, node_label = "item", node_label_size = 3) + no_size + room
p5 <- cnetplot(x, node_label = "share", node_label_size = 3) + no_size + room
p6 <- cnetplot(x, node_label = "exclusive", node_label_size = 3) + no_size + room

plot_list(p1, p2, p3, p4, p5, p6, ncol = 3, tag_levels = "A")

node_label controls which nodes carry labels: none, all, categories, items, shared items and exclusive items.

node_label can also be a vector of items: only those items are labelled, and with options(cnetplot_subset = TRUE) the graph itself is subset to the labelled items and the categories they belong to.

g1 <- cnetplot(x, node_label = letters[1:5], node_label_size = 3) + no_size + room

options(cnetplot_subset = TRUE)
g2 <- cnetplot(x, node_label = letters[1:5], node_label_size = 3) + no_size + room
options(cnetplot_subset = FALSE)

plot_list(g1, g2)

Labelling a subset of items without and with cnetplot_subset, which drops the remaining nodes.

External values such as fold changes are mapped to colour. hilight dims the nodes that do not belong to the selected categories, and a separate geom_cnet_label() layer allows the labels to be styled independently.

set.seed(123)
fc <- setNames(rnorm(26), letters)

style_fc <- function(plot) {
    plot +
        scale_color_gradient2(name = "value", low = "#2E7D32",
                              high = "#C62828", mid = "white") +
        guides(size = "none",
               color = guide_colorbar(barwidth = unit(.35, "cm"),
                                      barheight = unit(2.1, "cm"),
                                      title.position = "top")) +
        coord_cartesian(clip = "off") +
        scale_x_continuous(expand = expansion(mult = .12)) +
        scale_y_continuous(expand = expansion(mult = .12)) +
        theme(plot.margin = margin(6, 6, 6, 6),
              legend.margin = margin(0, 0, 0, 0),
              legend.box.margin = margin(0, 0, 0, 6),
              legend.title = element_text(size = 9),
              legend.text = element_text(size = 8))
}

p7 <- style_fc(cnetplot(x, foldChange = fc, node_label_size = 3))

p8 <- style_fc(cnetplot(x, foldChange = fc, node_label = ">1",
                        node_label_size = 3))

p9 <- style_fc(cnetplot(x, foldChange = fc, hilight = c("B", "C"),
                        node_label_size = 3))

p10 <- style_fc(
    cnetplot(x, node_label = "none", foldChange = fc, node_label_size = 3) +
        geom_cnet_label(node_label = "all", fontface = "bold", size = 3)
)

plot_list(p7, p8, p9, p10, ncol = 2, tag_levels = "A")

Associated values mapped to colour; hilight dims the nodes outside the selected categories.