firmo23
firmo23

Reputation: 8404

Set the direction of network circle graph to clockwise

I have the graph below in which I always display node a on top. What I would like to change is to change the direction of the circle network to be always right (clockwise) with igraph. Here is an example based on Set the position of certain node always on top of ring graph

enter image description here

library('igraph')
nodes <- c('a','b','c','d')
x <- c(0,1,2,3)
y <- c(0,1,2,3)
from <- c('a','b','c','d')
to <- c('b','c','d','a')
NodeList <- data.frame(nodes, x ,y)
EdgeList <- data.frame(from, to)
a<- graph_from_data_frame(vertices = NodeList, d= EdgeList, directed = TRUE)

# rotate rows of matrix mat so that row number mx is at top
# where mx defaults to row having largest value in 2nd column
rot <- function(mat, mx = which.max(mat[, 2])) {
  if (mx == 1) mat else mat[c(mx:nrow(mat), 1:(mx-1)), ]
}
plot(a, layout = rot(layout_in_circle(a)))

Upvotes: 1

Views: 299

Answers (2)

Iaroslav Domin
Iaroslav Domin

Reputation: 2718

ggraph does this by default

library(ggraph)

ggraph(a, layout = 'linear', circular = TRUE) +
  geom_edge_link(arrow = arrow(length = unit(4, 'mm')), end_cap = circle(4, 'mm')) +
  geom_node_label(aes(label = name)) +
  coord_fixed()

enter image description here

You can set positions manually as well:

library(ggraph)
library(tidygraph)

a %>% 
  as_tbl_graph() %>% 
  mutate(
    alpha = pi/2 - 0:(gsize(a) - 1)*2*pi/gsize(a),
    x = cos(alpha),
    y = sin(alpha)
  ) %>% 
  ggraph(x = x, y = y) +
  geom_edge_link(arrow = arrow(length = unit(4, 'mm')), end_cap = circle(4, 'mm')) +
  geom_node_label(aes(label = name)) +
  coord_fixed()

enter image description here

Upvotes: 2

Waldi
Waldi

Reputation: 41230

You can determine the direction with the order argument:

plot(a, layout = rot(layout_in_circle(a, order = order(from,decreasing = T))))

enter image description here Note that order(from, decreasing =T) works here because node names are in an increasing alphabetical order.
For a more general solution, see this post.

Upvotes: 2

Related Questions