R visNetwork: customize collapse behavior to compress graph visualization

Viewed 354

I would like to customize the collapse functionality of the R package visNetwork.

Iam using R version 3.6.2, RStudio Version 1.2.5033 and visNetwork version 2.0.9.

The standard behavior is that after double click on a node, every outgoing path and corresponding nodes and relationships from this node are collapsed into the choosen node. But I would like to customize the collapse functionality so that n endnodes are not collapsed.

Here is an example graph:

library(dplyr)
library(visNetwork)

nod <- tibble(id = c (1,2,3,4,5,6), label = c("a","b","c","d","e","f"), x= c(0,1,2,3,3,2)*150,y = c(0,0,0,0,-1,1)*150)


# standard behavior
edg <- tibble(id = 1:5, from = c(1,2,3,3,3), to = c(2,3,4,5,6))
edg <- edg %>% mutate(arrows = c("to","to","to","to","to"))


# first solution: under the hood arrows starting from d, e and f and arrow head is at the from-node
edg <- tibble(id = 1:5, from = c(1,2,4,5,6), to = c(2,3,3,3,3))
edg <- edg %>% mutate(arrows = c("to","to","from","from","from"))

##
graph <- visNetwork(nod, edg) %>% 
  visEdges(smooth = F) %>%
  visNodes(fixed = TRUE) %>%
  visOptions(collapse = list(enabled = T, keepCoord = T)) %>%
  visPhysics(enabled = F) %>%
  visLayout(randomSeed = 123)


When double clicking on node b, i would like that only node c is clustered into node b and the endnodes node d, node e and node f are still uncollapsed. The idea is to compress a huge graph with double-clicks to illustrate dynamically only the relationship between the initial nodes and end nodes without the way between.

In the following the image of the initial graph: Initial graph

and the one of the graph that is looking as desired: Clustered, compressed graph

My first solution is to change under the hood the direction of the arrows of the end nodes so that the arrows are pointing from node d, node e and node f to node c, consequently the path from node a over node b is not continuing after node c. Furthermore, I changed the position of the respective arrow heads so that they are at the from-nodes (d, e, f). Hence the graph is looking as desired with the desired collapse behavior.

I am wondering if there is a smarter way like a function:

function(graph, cluster = "node b", other_nodes = c("node c", "node f")) that is ,after executing, only clustering in this example node c and node f into node b from the graph graph. More arguments of the function could be include_last_node = TRUE or FALSE, define the hops from the cluster node to be collapsed with n_hops = number....

--> Does anybody know if it is possible to exclude the last nodes of every path when collapsing? Or to define the number of hops(nodes) from the cluster node to be collapsed?

Thanks in advance for help!

0 Answers
Related