Search code examples
rlayoutnodesgraph-visualizationvisnetwork

r visNetwork node position issue


I am creating graph structure

id    <- c(1,2,3,4,5,6,7,8,9)
label <- c("All", "Cat", "Dog", "Rice","Fish", "Bread","Rice","Fish", "Bread")

nodes <- data.frame(id, label)

edges <- data.frame(
from = c(1,1,2,2,2,3,3,3),
to = c(2,3,4,5,6,7,8,9)
  )



visNetwork(nodes, edges, width = "100%",height = "800px") %>%  visNodes(shape = "square") %>% 
  visEdges(arrows = "to") %>% 
  visInteraction(navigationButtons = TRUE)%>% 
  visHierarchicalLayout(levelSeparation = 200) %>% 
  visOptions(manipulation = TRUE)

expecting it to show up like this.

Expected Output

However the actual output is like this

Actual Output

The node positions are incorrect , I cannot manually move the nodes and this makes it very hard to explain. Need help rearranging the nodes based on the expected output above.


Solution

  • You can specify the level for each node to get the orientation you want.

    library(visNetwork)
    id    <- c(1,2,3,4,5,6,7,8,9)
    label <- c("All", "Cat", "Dog", "Rice","Fish", "Bread","Rice","Fish", "Bread")
    
    nodes <- data.frame(id, label, level = c( 1,2,2,3,3,3,3,3,3))
    
    edges <- data.frame(
      from = c(1,1,2,2,2,3,3,3),
      to = c(2,3,4,5,6,7,8,9)
    )
    
    visNetwork(nodes, edges, width = "100%",height = "800px") %>%  visNodes(shape = "square") %>% 
      visEdges(arrows = "to") %>% 
      visInteraction(navigationButtons = TRUE)%>% 
      visHierarchicalLayout(levelSeparation = 200) %>% 
      visOptions(manipulation = TRUE)
    

    enter image description here