rvisnetwork

Use visnetwork to recreate hierarchy tree


Im trying to use visNetwork package to recreate the hierarchical tree below as you can see it in the image but I cannot set the hierarchy for the positions.

# Install and load the visNetwork package
install.packages("visNetwork")
library(visNetwork)
# Create nodes data frame
nodes <- data.frame(
  id = 1:7,
  label = c("BLADDER", "TRODELVY", "EV", "NO ADC RECEIVED", "EV", "NO ADC RECEIVED", "TRODELVY "),
  color = c("gray", "red", "blue", "gray", "blue", "gray", "red"),
  shape = "box"
)

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

# Create the network visualization
visNetwork(nodes, edges) %>%
  visNodes(shape = "box") %>%
  visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE)%>%
  visPhysics(solver = "hierarchicalRepulsion", 
             forceAtlas2Based = list(gravitationalConstant = -500))

enter image description here


Solution

  • You also need to set a level definition in nodes and use visHierarchicalLayout. However, what maybe is not possible without more complex hacks is to get the "90 degree" edges.

    enter image description here

    library(visNetwork)
    # Create nodes data frame
    nodes <- data.frame(
      id = 1:7,
      label = c("BLADDER", "TRODELVY", "EV", "NO ADC RECEIVED", "EV", "NO ADC RECEIVED", "TRODELVY "),
      color = c("gray", "red", "blue", "gray", "blue", "gray", "red"),
      shape = "box",
      level = c(1, 2, 2, 3, 3, 3, 3)
    )
    
    # Create edges data frame
    edges <- data.frame(
      from = c(1, 1, 2, 2, 3, 3),
      to = c(2, 3, 4, 5, 6, 7)
    )
    
    # Create the network visualization
    visNetwork(nodes, edges) %>%
      visNodes(shape = "square", size = 500, font = list(color = "white")) %>%
      visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE)%>%
      visHierarchicalLayout(levelSeparation = 200, direction = "LR")