One can plot networks by either constructing the data.frames of nodes and edges (with x and y coordinates) or use igraph objects.

igraph

If the visualisation was initialised with an object of class igraph then the layout_igraph function can be used to compute the coordinates of nodes and edges.

The layout_igraph function accepts a method which accepts an igraph layout function.

library(g2r)

ig <- igraph::erdos.renyi.game(500, 2/500)

g2(ig, asp(x, y)) %>%
  layout_igraph() %>% 
  fig_edge(strokeOpacity = .5) %>% 
  fig_point(asp(shape = "circle")) %>% 
  axis_hide()

Layout

You can also use the layout_arc function to layout the node in an arc.

ig <- igraph::erdos.renyi.game(100, 1/100)

g2(ig, asp(x, y)) %>% 
  layout_arc() %>% 
  fig_edge(
    asp(
      color = source, 
      shape = "arc"
    ), 
    opacity = .3
  ) %>% 
  fig_point(
    asp(
      color = id, 
      shape = "circle", 
      size = value,
      label = id
    )
  ) %>% 
  coord_type("polar") %>% 
  coord_reflect("y") %>% 
  axis_hide() %>% 
  gauge_label(labelEmit = TRUE) %>% 
  motif(padding = c(30, 5, 75, 5))

Similar as above but without the polar coordinates.

ig <- igraph::erdos.renyi.game(100, 1/100)

g2(ig, asp(x, y)) %>% 
  layout_arc(marginRatio = .5) %>% 
  fig_edge(
    asp(
      color = source, 
      shape = "arc",
      tooltip = source,
      tooltip = target
    ), 
    opacity = .3
  ) %>% 
  fig_point(
    asp(
      color = id, 
      shape = "circle", 
      size = value,
      label = id
    )
  ) %>% 
  axis_hide() %>% 
  gauge_label(
    offset = -10, 
    rotate = pi / 2,
    style = list(
      textAlign = "left",
      fontSize = 8
    )
  ) %>% 
  motif(padding = c(20, 20, 30)) %>% 
  legend_size(FALSE) %>% 
  legend_color(FALSE)

Data.frames

You can also use data.frames but then will have to compute the coordinates for the layout manually. For the edges these coordinates, for the edges, must be list columns.

  • x: source, target x position
  • y: source, target y position
# edges
edges <- data.frame(
  source = sample(letters, 26),
  target = sample(letters, 26)
)

edges$x <- lapply(1:26, function(i){
  c(runif(1, 1, 10), runif(1, 1, 10))
})

edges$y <- lapply(1:26, function(i){
  c(runif(1, 1, 10), runif(1, 1, 10))
})

edges %>% 
  head() %>% 
  knitr::kable()
source target x y
a g 7.115335, 8.857754 8.862057, 7.699192
s e 9.809824, 9.470672 7.913630, 8.129961
w x 9.383775, 7.543744 8.701559, 5.036745
k w 4.610940, 6.490915 7.341527, 2.302007
c o 3.149568, 7.839186 4.136734, 9.968444
m a 9.730766, 1.009607 6.224456, 9.042287

These can then be used as x and y aspects.

g2(asp(x, y)) %>% 
  fig_edge(data = edges) %>% 
  axis_hide()