skan
skan

Reputation: 7760

How to create a directed network graph with aligned nodes in R?

I would like to get something like this

enter image description here A network graph with or without labels but with nodes aligned. How can I get it?

I'm already used the packages Diagrammer and Visnetwork for other graphs, so using the same will be a bonus.

library(DiagrammeR)
library(visNetwork)

from=c("A","A","A","A","B","B","B","C","C","D")
to=c("B","C","D","E","C","D","E","D","E","E")
nodesd=c("A","B","C","D","E")

With Diagrammer:

nodes <- create_node_df(  n=length(nodesd), label=nodesd,  width=0.3) 
edges <- create_edge_df(from = factor(from, levels=nodesd), to = factor(to, levels=nodesd), rel = "leading_to")   
graph <- create_graph(nodes_df = nodes, edges_df = edges)
render_graph(graph)

enter image description here

I've also tried with set_node_position() but it doesn't seem to make any difference.

With Visnetwork

nodes <- data.frame(id=nodesd, label= nodesd ) 
edges <- data.frame(from=from, to =to, length=150)
visNetwork(nodes,edges, width="100%" , height="100%")  %>% 
visNodes(shape = "circle") %>%  visEdges(arrows = 'to', smooth =T)  

enter image description here As you can see the nodes are not aligned. How can I force it to do it?

I could drag them manually but it's not something you want to do if you have many graphs, and the result is not good anyway.

enter image description here

I got to do it vertically with visnetwork by adding the line

  %>%   visHierarchicalLayout()

at the end. But it doesn't work well because many edges disappear.

enter image description here

If I want to get a horizontal alignement I need to add this to the nodes definition.

level = c(1,1,1,1,1)

enter image description here

Upvotes: 3

Views: 2056

Answers (1)

G5W
G5W

Reputation: 37661

I can't help you with DiagrammeR or visNetwork, but it is easy to do this with igraph. You just need to specify a simple layout of the nodes. You will also want to adjust the curvature of the edges. My example below has something that works, but you might adjust it to make it more artistic.

library(igraph)
EL = cbind(from, to)
g = graph_from_edgelist(EL)

L = cbind(1:5, 5:1)
CURVE = c(0,0.15, 0.3, 0.45, 0, -0.15, -0.3, 0, 0.15, 0) 
plot(g, layout=L, edge.curved=CURVE)

Graph with Layout

Upvotes: 4

Related Questions